PackageManagerService.java revision d5d5e926eb8ff2541a845d6a5657cee5e5c6e7b6
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.DeviceIdleController;
262import com.android.server.EventLogTags;
263import com.android.server.FgThread;
264import com.android.server.IntentResolver;
265import com.android.server.LocalServices;
266import com.android.server.ServiceThread;
267import com.android.server.SystemConfig;
268import com.android.server.Watchdog;
269import com.android.server.net.NetworkPolicyManagerInternal;
270import com.android.server.pm.Installer.InstallerException;
271import com.android.server.pm.PermissionsState.PermissionState;
272import com.android.server.pm.Settings.DatabaseVersion;
273import com.android.server.pm.Settings.VersionInfo;
274import com.android.server.pm.dex.DexManager;
275import com.android.server.storage.DeviceStorageMonitorInternal;
276
277import dalvik.system.CloseGuard;
278import dalvik.system.DexFile;
279import dalvik.system.VMRuntime;
280
281import libcore.io.IoUtils;
282import libcore.util.EmptyArray;
283
284import org.xmlpull.v1.XmlPullParser;
285import org.xmlpull.v1.XmlPullParserException;
286import org.xmlpull.v1.XmlSerializer;
287
288import java.io.BufferedOutputStream;
289import java.io.BufferedReader;
290import java.io.ByteArrayInputStream;
291import java.io.ByteArrayOutputStream;
292import java.io.File;
293import java.io.FileDescriptor;
294import java.io.FileInputStream;
295import java.io.FileNotFoundException;
296import java.io.FileOutputStream;
297import java.io.FileReader;
298import java.io.FilenameFilter;
299import java.io.IOException;
300import java.io.PrintWriter;
301import java.nio.charset.StandardCharsets;
302import java.security.DigestInputStream;
303import java.security.MessageDigest;
304import java.security.NoSuchAlgorithmException;
305import java.security.PublicKey;
306import java.security.SecureRandom;
307import java.security.cert.Certificate;
308import java.security.cert.CertificateEncodingException;
309import java.security.cert.CertificateException;
310import java.text.SimpleDateFormat;
311import java.util.ArrayList;
312import java.util.Arrays;
313import java.util.Collection;
314import java.util.Collections;
315import java.util.Comparator;
316import java.util.Date;
317import java.util.HashSet;
318import java.util.HashMap;
319import java.util.Iterator;
320import java.util.List;
321import java.util.Map;
322import java.util.Objects;
323import java.util.Set;
324import java.util.concurrent.CountDownLatch;
325import java.util.concurrent.TimeUnit;
326import java.util.concurrent.atomic.AtomicBoolean;
327import java.util.concurrent.atomic.AtomicInteger;
328
329/**
330 * Keep track of all those APKs everywhere.
331 * <p>
332 * Internally there are two important locks:
333 * <ul>
334 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
335 * and other related state. It is a fine-grained lock that should only be held
336 * momentarily, as it's one of the most contended locks in the system.
337 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
338 * operations typically involve heavy lifting of application data on disk. Since
339 * {@code installd} is single-threaded, and it's operations can often be slow,
340 * this lock should never be acquired while already holding {@link #mPackages}.
341 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
342 * holding {@link #mInstallLock}.
343 * </ul>
344 * Many internal methods rely on the caller to hold the appropriate locks, and
345 * this contract is expressed through method name suffixes:
346 * <ul>
347 * <li>fooLI(): the caller must hold {@link #mInstallLock}
348 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
349 * being modified must be frozen
350 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
351 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
352 * </ul>
353 * <p>
354 * Because this class is very central to the platform's security; please run all
355 * CTS and unit tests whenever making modifications:
356 *
357 * <pre>
358 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
359 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
360 * </pre>
361 */
362public class PackageManagerService extends IPackageManager.Stub {
363    static final String TAG = "PackageManager";
364    static final boolean DEBUG_SETTINGS = false;
365    static final boolean DEBUG_PREFERRED = false;
366    static final boolean DEBUG_UPGRADE = false;
367    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
368    private static final boolean DEBUG_BACKUP = false;
369    private static final boolean DEBUG_INSTALL = false;
370    private static final boolean DEBUG_REMOVE = false;
371    private static final boolean DEBUG_BROADCASTS = false;
372    private static final boolean DEBUG_SHOW_INFO = false;
373    private static final boolean DEBUG_PACKAGE_INFO = false;
374    private static final boolean DEBUG_INTENT_MATCHING = false;
375    private static final boolean DEBUG_PACKAGE_SCANNING = false;
376    private static final boolean DEBUG_VERIFY = false;
377    private static final boolean DEBUG_FILTERS = false;
378
379    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
380    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
381    // user, but by default initialize to this.
382    public static final boolean DEBUG_DEXOPT = false;
383
384    private static final boolean DEBUG_ABI_SELECTION = false;
385    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
386    private static final boolean DEBUG_TRIAGED_MISSING = false;
387    private static final boolean DEBUG_APP_DATA = false;
388
389    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
390    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
391
392    private static final boolean DISABLE_EPHEMERAL_APPS = false;
393    private static final boolean HIDE_EPHEMERAL_APIS = false;
394
395    private static final boolean ENABLE_QUOTA =
396            SystemProperties.getBoolean("persist.fw.quota", false);
397
398    private static final int RADIO_UID = Process.PHONE_UID;
399    private static final int LOG_UID = Process.LOG_UID;
400    private static final int NFC_UID = Process.NFC_UID;
401    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
402    private static final int SHELL_UID = Process.SHELL_UID;
403
404    // Cap the size of permission trees that 3rd party apps can define
405    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
406
407    // Suffix used during package installation when copying/moving
408    // package apks to install directory.
409    private static final String INSTALL_PACKAGE_SUFFIX = "-";
410
411    static final int SCAN_NO_DEX = 1<<1;
412    static final int SCAN_FORCE_DEX = 1<<2;
413    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
414    static final int SCAN_NEW_INSTALL = 1<<4;
415    static final int SCAN_UPDATE_TIME = 1<<5;
416    static final int SCAN_BOOTING = 1<<6;
417    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
418    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
419    static final int SCAN_REPLACING = 1<<9;
420    static final int SCAN_REQUIRE_KNOWN = 1<<10;
421    static final int SCAN_MOVE = 1<<11;
422    static final int SCAN_INITIAL = 1<<12;
423    static final int SCAN_CHECK_ONLY = 1<<13;
424    static final int SCAN_DONT_KILL_APP = 1<<14;
425    static final int SCAN_IGNORE_FROZEN = 1<<15;
426    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
427    static final int SCAN_AS_INSTANT_APP = 1<<17;
428    static final int SCAN_AS_FULL_APP = 1<<18;
429    /** Should not be with the scan flags */
430    static final int FLAGS_REMOVE_CHATTY = 1<<31;
431
432    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
433
434    private static final int[] EMPTY_INT_ARRAY = new int[0];
435
436    /**
437     * Timeout (in milliseconds) after which the watchdog should declare that
438     * our handler thread is wedged.  The usual default for such things is one
439     * minute but we sometimes do very lengthy I/O operations on this thread,
440     * such as installing multi-gigabyte applications, so ours needs to be longer.
441     */
442    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
443
444    /**
445     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
446     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
447     * settings entry if available, otherwise we use the hardcoded default.  If it's been
448     * more than this long since the last fstrim, we force one during the boot sequence.
449     *
450     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
451     * one gets run at the next available charging+idle time.  This final mandatory
452     * no-fstrim check kicks in only of the other scheduling criteria is never met.
453     */
454    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
455
456    /**
457     * Whether verification is enabled by default.
458     */
459    private static final boolean DEFAULT_VERIFY_ENABLE = true;
460
461    /**
462     * The default maximum time to wait for the verification agent to return in
463     * milliseconds.
464     */
465    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
466
467    /**
468     * The default response for package verification timeout.
469     *
470     * This can be either PackageManager.VERIFICATION_ALLOW or
471     * PackageManager.VERIFICATION_REJECT.
472     */
473    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
474
475    static final String PLATFORM_PACKAGE_NAME = "android";
476
477    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
478
479    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
480            DEFAULT_CONTAINER_PACKAGE,
481            "com.android.defcontainer.DefaultContainerService");
482
483    private static final String KILL_APP_REASON_GIDS_CHANGED =
484            "permission grant or revoke changed gids";
485
486    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
487            "permissions revoked";
488
489    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
490
491    private static final String PACKAGE_SCHEME = "package";
492
493    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
494    /**
495     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
496     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
497     * VENDOR_OVERLAY_DIR.
498     */
499    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
500    /**
501     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
502     * is in VENDOR_OVERLAY_THEME_PROPERTY.
503     */
504    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
505            = "persist.vendor.overlay.theme";
506
507    /** Permission grant: not grant the permission. */
508    private static final int GRANT_DENIED = 1;
509
510    /** Permission grant: grant the permission as an install permission. */
511    private static final int GRANT_INSTALL = 2;
512
513    /** Permission grant: grant the permission as a runtime one. */
514    private static final int GRANT_RUNTIME = 3;
515
516    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
517    private static final int GRANT_UPGRADE = 4;
518
519    /** Canonical intent used to identify what counts as a "web browser" app */
520    private static final Intent sBrowserIntent;
521    static {
522        sBrowserIntent = new Intent();
523        sBrowserIntent.setAction(Intent.ACTION_VIEW);
524        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
525        sBrowserIntent.setData(Uri.parse("http:"));
526    }
527
528    /**
529     * The set of all protected actions [i.e. those actions for which a high priority
530     * intent filter is disallowed].
531     */
532    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
533    static {
534        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
535        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
536        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
537        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
538    }
539
540    // Compilation reasons.
541    public static final int REASON_FIRST_BOOT = 0;
542    public static final int REASON_BOOT = 1;
543    public static final int REASON_INSTALL = 2;
544    public static final int REASON_BACKGROUND_DEXOPT = 3;
545    public static final int REASON_AB_OTA = 4;
546    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
547    public static final int REASON_SHARED_APK = 6;
548    public static final int REASON_FORCED_DEXOPT = 7;
549    public static final int REASON_CORE_APP = 8;
550
551    public static final int REASON_LAST = REASON_CORE_APP;
552
553    /** All dangerous permission names in the same order as the events in MetricsEvent */
554    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
555            Manifest.permission.READ_CALENDAR,
556            Manifest.permission.WRITE_CALENDAR,
557            Manifest.permission.CAMERA,
558            Manifest.permission.READ_CONTACTS,
559            Manifest.permission.WRITE_CONTACTS,
560            Manifest.permission.GET_ACCOUNTS,
561            Manifest.permission.ACCESS_FINE_LOCATION,
562            Manifest.permission.ACCESS_COARSE_LOCATION,
563            Manifest.permission.RECORD_AUDIO,
564            Manifest.permission.READ_PHONE_STATE,
565            Manifest.permission.CALL_PHONE,
566            Manifest.permission.READ_CALL_LOG,
567            Manifest.permission.WRITE_CALL_LOG,
568            Manifest.permission.ADD_VOICEMAIL,
569            Manifest.permission.USE_SIP,
570            Manifest.permission.PROCESS_OUTGOING_CALLS,
571            Manifest.permission.READ_CELL_BROADCASTS,
572            Manifest.permission.BODY_SENSORS,
573            Manifest.permission.SEND_SMS,
574            Manifest.permission.RECEIVE_SMS,
575            Manifest.permission.READ_SMS,
576            Manifest.permission.RECEIVE_WAP_PUSH,
577            Manifest.permission.RECEIVE_MMS,
578            Manifest.permission.READ_EXTERNAL_STORAGE,
579            Manifest.permission.WRITE_EXTERNAL_STORAGE,
580            Manifest.permission.READ_PHONE_NUMBER);
581
582
583    /**
584     * Version number for the package parser cache. Increment this whenever the format or
585     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
586     */
587    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
588
589    /**
590     * Whether the package parser cache is enabled.
591     */
592    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
593
594    final ServiceThread mHandlerThread;
595
596    final PackageHandler mHandler;
597
598    private final ProcessLoggingHandler mProcessLoggingHandler;
599
600    /**
601     * Messages for {@link #mHandler} that need to wait for system ready before
602     * being dispatched.
603     */
604    private ArrayList<Message> mPostSystemReadyMessages;
605
606    final int mSdkVersion = Build.VERSION.SDK_INT;
607
608    final Context mContext;
609    final boolean mFactoryTest;
610    final boolean mOnlyCore;
611    final DisplayMetrics mMetrics;
612    final int mDefParseFlags;
613    final String[] mSeparateProcesses;
614    final boolean mIsUpgrade;
615    final boolean mIsPreNUpgrade;
616    final boolean mIsPreNMR1Upgrade;
617
618    @GuardedBy("mPackages")
619    private boolean mDexOptDialogShown;
620
621    /** The location for ASEC container files on internal storage. */
622    final String mAsecInternalPath;
623
624    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
625    // LOCK HELD.  Can be called with mInstallLock held.
626    @GuardedBy("mInstallLock")
627    final Installer mInstaller;
628
629    /** Directory where installed third-party apps stored */
630    final File mAppInstallDir;
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 DeviceIdleController.LocalService mDeviceIdleController;
855
856    private File mCacheDir;
857
858    private ArraySet<String> mPrivappPermissionsViolations;
859
860    private static class IFVerificationParams {
861        PackageParser.Package pkg;
862        boolean replacing;
863        int userId;
864        int verifierUid;
865
866        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
867                int _userId, int _verifierUid) {
868            pkg = _pkg;
869            replacing = _replacing;
870            userId = _userId;
871            replacing = _replacing;
872            verifierUid = _verifierUid;
873        }
874    }
875
876    private interface IntentFilterVerifier<T extends IntentFilter> {
877        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
878                                               T filter, String packageName);
879        void startVerifications(int userId);
880        void receiveVerificationResponse(int verificationId);
881    }
882
883    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
884        private Context mContext;
885        private ComponentName mIntentFilterVerifierComponent;
886        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
887
888        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
889            mContext = context;
890            mIntentFilterVerifierComponent = verifierComponent;
891        }
892
893        private String getDefaultScheme() {
894            return IntentFilter.SCHEME_HTTPS;
895        }
896
897        @Override
898        public void startVerifications(int userId) {
899            // Launch verifications requests
900            int count = mCurrentIntentFilterVerifications.size();
901            for (int n=0; n<count; n++) {
902                int verificationId = mCurrentIntentFilterVerifications.get(n);
903                final IntentFilterVerificationState ivs =
904                        mIntentFilterVerificationStates.get(verificationId);
905
906                String packageName = ivs.getPackageName();
907
908                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
909                final int filterCount = filters.size();
910                ArraySet<String> domainsSet = new ArraySet<>();
911                for (int m=0; m<filterCount; m++) {
912                    PackageParser.ActivityIntentInfo filter = filters.get(m);
913                    domainsSet.addAll(filter.getHostsList());
914                }
915                synchronized (mPackages) {
916                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
917                            packageName, domainsSet) != null) {
918                        scheduleWriteSettingsLocked();
919                    }
920                }
921                sendVerificationRequest(userId, verificationId, ivs);
922            }
923            mCurrentIntentFilterVerifications.clear();
924        }
925
926        private void sendVerificationRequest(int userId, int verificationId,
927                IntentFilterVerificationState ivs) {
928
929            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
930            verificationIntent.putExtra(
931                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
932                    verificationId);
933            verificationIntent.putExtra(
934                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
935                    getDefaultScheme());
936            verificationIntent.putExtra(
937                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
938                    ivs.getHostsString());
939            verificationIntent.putExtra(
940                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
941                    ivs.getPackageName());
942            verificationIntent.setComponent(mIntentFilterVerifierComponent);
943            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
944
945            UserHandle user = new UserHandle(userId);
946            mContext.sendBroadcastAsUser(verificationIntent, user);
947            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
948                    "Sending IntentFilter verification broadcast");
949        }
950
951        public void receiveVerificationResponse(int verificationId) {
952            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
953
954            final boolean verified = ivs.isVerified();
955
956            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
957            final int count = filters.size();
958            if (DEBUG_DOMAIN_VERIFICATION) {
959                Slog.i(TAG, "Received verification response " + verificationId
960                        + " for " + count + " filters, verified=" + verified);
961            }
962            for (int n=0; n<count; n++) {
963                PackageParser.ActivityIntentInfo filter = filters.get(n);
964                filter.setVerified(verified);
965
966                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
967                        + " verified with result:" + verified + " and hosts:"
968                        + ivs.getHostsString());
969            }
970
971            mIntentFilterVerificationStates.remove(verificationId);
972
973            final String packageName = ivs.getPackageName();
974            IntentFilterVerificationInfo ivi = null;
975
976            synchronized (mPackages) {
977                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
978            }
979            if (ivi == null) {
980                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
981                        + verificationId + " packageName:" + packageName);
982                return;
983            }
984            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
985                    "Updating IntentFilterVerificationInfo for package " + packageName
986                            +" verificationId:" + verificationId);
987
988            synchronized (mPackages) {
989                if (verified) {
990                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
991                } else {
992                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
993                }
994                scheduleWriteSettingsLocked();
995
996                final int userId = ivs.getUserId();
997                if (userId != UserHandle.USER_ALL) {
998                    final int userStatus =
999                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1000
1001                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1002                    boolean needUpdate = false;
1003
1004                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1005                    // already been set by the User thru the Disambiguation dialog
1006                    switch (userStatus) {
1007                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1008                            if (verified) {
1009                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1010                            } else {
1011                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1012                            }
1013                            needUpdate = true;
1014                            break;
1015
1016                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1017                            if (verified) {
1018                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1019                                needUpdate = true;
1020                            }
1021                            break;
1022
1023                        default:
1024                            // Nothing to do
1025                    }
1026
1027                    if (needUpdate) {
1028                        mSettings.updateIntentFilterVerificationStatusLPw(
1029                                packageName, updatedStatus, userId);
1030                        scheduleWritePackageRestrictionsLocked(userId);
1031                    }
1032                }
1033            }
1034        }
1035
1036        @Override
1037        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1038                    ActivityIntentInfo filter, String packageName) {
1039            if (!hasValidDomains(filter)) {
1040                return false;
1041            }
1042            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1043            if (ivs == null) {
1044                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1045                        packageName);
1046            }
1047            if (DEBUG_DOMAIN_VERIFICATION) {
1048                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1049            }
1050            ivs.addFilter(filter);
1051            return true;
1052        }
1053
1054        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1055                int userId, int verificationId, String packageName) {
1056            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1057                    verifierUid, userId, packageName);
1058            ivs.setPendingState();
1059            synchronized (mPackages) {
1060                mIntentFilterVerificationStates.append(verificationId, ivs);
1061                mCurrentIntentFilterVerifications.add(verificationId);
1062            }
1063            return ivs;
1064        }
1065    }
1066
1067    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1068        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1069                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1070                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1071    }
1072
1073    // Set of pending broadcasts for aggregating enable/disable of components.
1074    static class PendingPackageBroadcasts {
1075        // for each user id, a map of <package name -> components within that package>
1076        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1077
1078        public PendingPackageBroadcasts() {
1079            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1080        }
1081
1082        public ArrayList<String> get(int userId, String packageName) {
1083            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1084            return packages.get(packageName);
1085        }
1086
1087        public void put(int userId, String packageName, ArrayList<String> components) {
1088            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1089            packages.put(packageName, components);
1090        }
1091
1092        public void remove(int userId, String packageName) {
1093            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1094            if (packages != null) {
1095                packages.remove(packageName);
1096            }
1097        }
1098
1099        public void remove(int userId) {
1100            mUidMap.remove(userId);
1101        }
1102
1103        public int userIdCount() {
1104            return mUidMap.size();
1105        }
1106
1107        public int userIdAt(int n) {
1108            return mUidMap.keyAt(n);
1109        }
1110
1111        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1112            return mUidMap.get(userId);
1113        }
1114
1115        public int size() {
1116            // total number of pending broadcast entries across all userIds
1117            int num = 0;
1118            for (int i = 0; i< mUidMap.size(); i++) {
1119                num += mUidMap.valueAt(i).size();
1120            }
1121            return num;
1122        }
1123
1124        public void clear() {
1125            mUidMap.clear();
1126        }
1127
1128        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1129            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1130            if (map == null) {
1131                map = new ArrayMap<String, ArrayList<String>>();
1132                mUidMap.put(userId, map);
1133            }
1134            return map;
1135        }
1136    }
1137    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1138
1139    // Service Connection to remote media container service to copy
1140    // package uri's from external media onto secure containers
1141    // or internal storage.
1142    private IMediaContainerService mContainerService = null;
1143
1144    static final int SEND_PENDING_BROADCAST = 1;
1145    static final int MCS_BOUND = 3;
1146    static final int END_COPY = 4;
1147    static final int INIT_COPY = 5;
1148    static final int MCS_UNBIND = 6;
1149    static final int START_CLEANING_PACKAGE = 7;
1150    static final int FIND_INSTALL_LOC = 8;
1151    static final int POST_INSTALL = 9;
1152    static final int MCS_RECONNECT = 10;
1153    static final int MCS_GIVE_UP = 11;
1154    static final int UPDATED_MEDIA_STATUS = 12;
1155    static final int WRITE_SETTINGS = 13;
1156    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1157    static final int PACKAGE_VERIFIED = 15;
1158    static final int CHECK_PENDING_VERIFICATION = 16;
1159    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1160    static final int INTENT_FILTER_VERIFIED = 18;
1161    static final int WRITE_PACKAGE_LIST = 19;
1162    static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20;
1163
1164    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1165
1166    // Delay time in millisecs
1167    static final int BROADCAST_DELAY = 10 * 1000;
1168
1169    static UserManagerService sUserManager;
1170
1171    // Stores a list of users whose package restrictions file needs to be updated
1172    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1173
1174    final private DefaultContainerConnection mDefContainerConn =
1175            new DefaultContainerConnection();
1176    class DefaultContainerConnection implements ServiceConnection {
1177        public void onServiceConnected(ComponentName name, IBinder service) {
1178            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1179            final IMediaContainerService imcs = IMediaContainerService.Stub
1180                    .asInterface(Binder.allowBlocking(service));
1181            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1182        }
1183
1184        public void onServiceDisconnected(ComponentName name) {
1185            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1186        }
1187    }
1188
1189    // Recordkeeping of restore-after-install operations that are currently in flight
1190    // between the Package Manager and the Backup Manager
1191    static class PostInstallData {
1192        public InstallArgs args;
1193        public PackageInstalledInfo res;
1194
1195        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1196            args = _a;
1197            res = _r;
1198        }
1199    }
1200
1201    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1202    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1203
1204    // XML tags for backup/restore of various bits of state
1205    private static final String TAG_PREFERRED_BACKUP = "pa";
1206    private static final String TAG_DEFAULT_APPS = "da";
1207    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1208
1209    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1210    private static final String TAG_ALL_GRANTS = "rt-grants";
1211    private static final String TAG_GRANT = "grant";
1212    private static final String ATTR_PACKAGE_NAME = "pkg";
1213
1214    private static final String TAG_PERMISSION = "perm";
1215    private static final String ATTR_PERMISSION_NAME = "name";
1216    private static final String ATTR_IS_GRANTED = "g";
1217    private static final String ATTR_USER_SET = "set";
1218    private static final String ATTR_USER_FIXED = "fixed";
1219    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1220
1221    // System/policy permission grants are not backed up
1222    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1223            FLAG_PERMISSION_POLICY_FIXED
1224            | FLAG_PERMISSION_SYSTEM_FIXED
1225            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1226
1227    // And we back up these user-adjusted states
1228    private static final int USER_RUNTIME_GRANT_MASK =
1229            FLAG_PERMISSION_USER_SET
1230            | FLAG_PERMISSION_USER_FIXED
1231            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1232
1233    final @Nullable String mRequiredVerifierPackage;
1234    final @NonNull String mRequiredInstallerPackage;
1235    final @NonNull String mRequiredUninstallerPackage;
1236    final @Nullable String mSetupWizardPackage;
1237    final @Nullable String mStorageManagerPackage;
1238    final @NonNull String mServicesSystemSharedLibraryPackageName;
1239    final @NonNull String mSharedSystemSharedLibraryPackageName;
1240
1241    final boolean mPermissionReviewRequired;
1242
1243    private final PackageUsage mPackageUsage = new PackageUsage();
1244    private final CompilerStats mCompilerStats = new CompilerStats();
1245
1246    class PackageHandler extends Handler {
1247        private boolean mBound = false;
1248        final ArrayList<HandlerParams> mPendingInstalls =
1249            new ArrayList<HandlerParams>();
1250
1251        private boolean connectToService() {
1252            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1253                    " DefaultContainerService");
1254            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1255            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1256            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1257                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1258                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1259                mBound = true;
1260                return true;
1261            }
1262            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1263            return false;
1264        }
1265
1266        private void disconnectService() {
1267            mContainerService = null;
1268            mBound = false;
1269            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1270            mContext.unbindService(mDefContainerConn);
1271            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1272        }
1273
1274        PackageHandler(Looper looper) {
1275            super(looper);
1276        }
1277
1278        public void handleMessage(Message msg) {
1279            try {
1280                doHandleMessage(msg);
1281            } finally {
1282                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1283            }
1284        }
1285
1286        void doHandleMessage(Message msg) {
1287            switch (msg.what) {
1288                case INIT_COPY: {
1289                    HandlerParams params = (HandlerParams) msg.obj;
1290                    int idx = mPendingInstalls.size();
1291                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1292                    // If a bind was already initiated we dont really
1293                    // need to do anything. The pending install
1294                    // will be processed later on.
1295                    if (!mBound) {
1296                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1297                                System.identityHashCode(mHandler));
1298                        // If this is the only one pending we might
1299                        // have to bind to the service again.
1300                        if (!connectToService()) {
1301                            Slog.e(TAG, "Failed to bind to media container service");
1302                            params.serviceError();
1303                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1304                                    System.identityHashCode(mHandler));
1305                            if (params.traceMethod != null) {
1306                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1307                                        params.traceCookie);
1308                            }
1309                            return;
1310                        } else {
1311                            // Once we bind to the service, the first
1312                            // pending request will be processed.
1313                            mPendingInstalls.add(idx, params);
1314                        }
1315                    } else {
1316                        mPendingInstalls.add(idx, params);
1317                        // Already bound to the service. Just make
1318                        // sure we trigger off processing the first request.
1319                        if (idx == 0) {
1320                            mHandler.sendEmptyMessage(MCS_BOUND);
1321                        }
1322                    }
1323                    break;
1324                }
1325                case MCS_BOUND: {
1326                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1327                    if (msg.obj != null) {
1328                        mContainerService = (IMediaContainerService) msg.obj;
1329                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1330                                System.identityHashCode(mHandler));
1331                    }
1332                    if (mContainerService == null) {
1333                        if (!mBound) {
1334                            // Something seriously wrong since we are not bound and we are not
1335                            // waiting for connection. Bail out.
1336                            Slog.e(TAG, "Cannot bind to media container service");
1337                            for (HandlerParams params : mPendingInstalls) {
1338                                // Indicate service bind error
1339                                params.serviceError();
1340                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1341                                        System.identityHashCode(params));
1342                                if (params.traceMethod != null) {
1343                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1344                                            params.traceMethod, params.traceCookie);
1345                                }
1346                                return;
1347                            }
1348                            mPendingInstalls.clear();
1349                        } else {
1350                            Slog.w(TAG, "Waiting to connect to media container service");
1351                        }
1352                    } else if (mPendingInstalls.size() > 0) {
1353                        HandlerParams params = mPendingInstalls.get(0);
1354                        if (params != null) {
1355                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1356                                    System.identityHashCode(params));
1357                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1358                            if (params.startCopy()) {
1359                                // We are done...  look for more work or to
1360                                // go idle.
1361                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1362                                        "Checking for more work or unbind...");
1363                                // Delete pending install
1364                                if (mPendingInstalls.size() > 0) {
1365                                    mPendingInstalls.remove(0);
1366                                }
1367                                if (mPendingInstalls.size() == 0) {
1368                                    if (mBound) {
1369                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1370                                                "Posting delayed MCS_UNBIND");
1371                                        removeMessages(MCS_UNBIND);
1372                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1373                                        // Unbind after a little delay, to avoid
1374                                        // continual thrashing.
1375                                        sendMessageDelayed(ubmsg, 10000);
1376                                    }
1377                                } else {
1378                                    // There are more pending requests in queue.
1379                                    // Just post MCS_BOUND message to trigger processing
1380                                    // of next pending install.
1381                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1382                                            "Posting MCS_BOUND for next work");
1383                                    mHandler.sendEmptyMessage(MCS_BOUND);
1384                                }
1385                            }
1386                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1387                        }
1388                    } else {
1389                        // Should never happen ideally.
1390                        Slog.w(TAG, "Empty queue");
1391                    }
1392                    break;
1393                }
1394                case MCS_RECONNECT: {
1395                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1396                    if (mPendingInstalls.size() > 0) {
1397                        if (mBound) {
1398                            disconnectService();
1399                        }
1400                        if (!connectToService()) {
1401                            Slog.e(TAG, "Failed to bind to media container service");
1402                            for (HandlerParams params : mPendingInstalls) {
1403                                // Indicate service bind error
1404                                params.serviceError();
1405                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1406                                        System.identityHashCode(params));
1407                            }
1408                            mPendingInstalls.clear();
1409                        }
1410                    }
1411                    break;
1412                }
1413                case MCS_UNBIND: {
1414                    // If there is no actual work left, then time to unbind.
1415                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1416
1417                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1418                        if (mBound) {
1419                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1420
1421                            disconnectService();
1422                        }
1423                    } else if (mPendingInstalls.size() > 0) {
1424                        // There are more pending requests in queue.
1425                        // Just post MCS_BOUND message to trigger processing
1426                        // of next pending install.
1427                        mHandler.sendEmptyMessage(MCS_BOUND);
1428                    }
1429
1430                    break;
1431                }
1432                case MCS_GIVE_UP: {
1433                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1434                    HandlerParams params = mPendingInstalls.remove(0);
1435                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1436                            System.identityHashCode(params));
1437                    break;
1438                }
1439                case SEND_PENDING_BROADCAST: {
1440                    String packages[];
1441                    ArrayList<String> components[];
1442                    int size = 0;
1443                    int uids[];
1444                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1445                    synchronized (mPackages) {
1446                        if (mPendingBroadcasts == null) {
1447                            return;
1448                        }
1449                        size = mPendingBroadcasts.size();
1450                        if (size <= 0) {
1451                            // Nothing to be done. Just return
1452                            return;
1453                        }
1454                        packages = new String[size];
1455                        components = new ArrayList[size];
1456                        uids = new int[size];
1457                        int i = 0;  // filling out the above arrays
1458
1459                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1460                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1461                            Iterator<Map.Entry<String, ArrayList<String>>> it
1462                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1463                                            .entrySet().iterator();
1464                            while (it.hasNext() && i < size) {
1465                                Map.Entry<String, ArrayList<String>> ent = it.next();
1466                                packages[i] = ent.getKey();
1467                                components[i] = ent.getValue();
1468                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1469                                uids[i] = (ps != null)
1470                                        ? UserHandle.getUid(packageUserId, ps.appId)
1471                                        : -1;
1472                                i++;
1473                            }
1474                        }
1475                        size = i;
1476                        mPendingBroadcasts.clear();
1477                    }
1478                    // Send broadcasts
1479                    for (int i = 0; i < size; i++) {
1480                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1481                    }
1482                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1483                    break;
1484                }
1485                case START_CLEANING_PACKAGE: {
1486                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1487                    final String packageName = (String)msg.obj;
1488                    final int userId = msg.arg1;
1489                    final boolean andCode = msg.arg2 != 0;
1490                    synchronized (mPackages) {
1491                        if (userId == UserHandle.USER_ALL) {
1492                            int[] users = sUserManager.getUserIds();
1493                            for (int user : users) {
1494                                mSettings.addPackageToCleanLPw(
1495                                        new PackageCleanItem(user, packageName, andCode));
1496                            }
1497                        } else {
1498                            mSettings.addPackageToCleanLPw(
1499                                    new PackageCleanItem(userId, packageName, andCode));
1500                        }
1501                    }
1502                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1503                    startCleaningPackages();
1504                } break;
1505                case POST_INSTALL: {
1506                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1507
1508                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1509                    final boolean didRestore = (msg.arg2 != 0);
1510                    mRunningInstalls.delete(msg.arg1);
1511
1512                    if (data != null) {
1513                        InstallArgs args = data.args;
1514                        PackageInstalledInfo parentRes = data.res;
1515
1516                        final boolean grantPermissions = (args.installFlags
1517                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1518                        final boolean killApp = (args.installFlags
1519                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1520                        final String[] grantedPermissions = args.installGrantPermissions;
1521
1522                        // Handle the parent package
1523                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1524                                grantedPermissions, didRestore, args.installerPackageName,
1525                                args.observer);
1526
1527                        // Handle the child packages
1528                        final int childCount = (parentRes.addedChildPackages != null)
1529                                ? parentRes.addedChildPackages.size() : 0;
1530                        for (int i = 0; i < childCount; i++) {
1531                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1532                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1533                                    grantedPermissions, false, args.installerPackageName,
1534                                    args.observer);
1535                        }
1536
1537                        // Log tracing if needed
1538                        if (args.traceMethod != null) {
1539                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1540                                    args.traceCookie);
1541                        }
1542                    } else {
1543                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1544                    }
1545
1546                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1547                } break;
1548                case UPDATED_MEDIA_STATUS: {
1549                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1550                    boolean reportStatus = msg.arg1 == 1;
1551                    boolean doGc = msg.arg2 == 1;
1552                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1553                    if (doGc) {
1554                        // Force a gc to clear up stale containers.
1555                        Runtime.getRuntime().gc();
1556                    }
1557                    if (msg.obj != null) {
1558                        @SuppressWarnings("unchecked")
1559                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1560                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1561                        // Unload containers
1562                        unloadAllContainers(args);
1563                    }
1564                    if (reportStatus) {
1565                        try {
1566                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1567                                    "Invoking StorageManagerService call back");
1568                            PackageHelper.getStorageManager().finishMediaUpdate();
1569                        } catch (RemoteException e) {
1570                            Log.e(TAG, "StorageManagerService not running?");
1571                        }
1572                    }
1573                } break;
1574                case WRITE_SETTINGS: {
1575                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1576                    synchronized (mPackages) {
1577                        removeMessages(WRITE_SETTINGS);
1578                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1579                        mSettings.writeLPr();
1580                        mDirtyUsers.clear();
1581                    }
1582                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1583                } break;
1584                case WRITE_PACKAGE_RESTRICTIONS: {
1585                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1586                    synchronized (mPackages) {
1587                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1588                        for (int userId : mDirtyUsers) {
1589                            mSettings.writePackageRestrictionsLPr(userId);
1590                        }
1591                        mDirtyUsers.clear();
1592                    }
1593                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1594                } break;
1595                case WRITE_PACKAGE_LIST: {
1596                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1597                    synchronized (mPackages) {
1598                        removeMessages(WRITE_PACKAGE_LIST);
1599                        mSettings.writePackageListLPr(msg.arg1);
1600                    }
1601                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1602                } break;
1603                case CHECK_PENDING_VERIFICATION: {
1604                    final int verificationId = msg.arg1;
1605                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1606
1607                    if ((state != null) && !state.timeoutExtended()) {
1608                        final InstallArgs args = state.getInstallArgs();
1609                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1610
1611                        Slog.i(TAG, "Verification timed out for " + originUri);
1612                        mPendingVerification.remove(verificationId);
1613
1614                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1615
1616                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1617                            Slog.i(TAG, "Continuing with installation of " + originUri);
1618                            state.setVerifierResponse(Binder.getCallingUid(),
1619                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1620                            broadcastPackageVerified(verificationId, originUri,
1621                                    PackageManager.VERIFICATION_ALLOW,
1622                                    state.getInstallArgs().getUser());
1623                            try {
1624                                ret = args.copyApk(mContainerService, true);
1625                            } catch (RemoteException e) {
1626                                Slog.e(TAG, "Could not contact the ContainerService");
1627                            }
1628                        } else {
1629                            broadcastPackageVerified(verificationId, originUri,
1630                                    PackageManager.VERIFICATION_REJECT,
1631                                    state.getInstallArgs().getUser());
1632                        }
1633
1634                        Trace.asyncTraceEnd(
1635                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1636
1637                        processPendingInstall(args, ret);
1638                        mHandler.sendEmptyMessage(MCS_UNBIND);
1639                    }
1640                    break;
1641                }
1642                case PACKAGE_VERIFIED: {
1643                    final int verificationId = msg.arg1;
1644
1645                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1646                    if (state == null) {
1647                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1648                        break;
1649                    }
1650
1651                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1652
1653                    state.setVerifierResponse(response.callerUid, response.code);
1654
1655                    if (state.isVerificationComplete()) {
1656                        mPendingVerification.remove(verificationId);
1657
1658                        final InstallArgs args = state.getInstallArgs();
1659                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1660
1661                        int ret;
1662                        if (state.isInstallAllowed()) {
1663                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1664                            broadcastPackageVerified(verificationId, originUri,
1665                                    response.code, state.getInstallArgs().getUser());
1666                            try {
1667                                ret = args.copyApk(mContainerService, true);
1668                            } catch (RemoteException e) {
1669                                Slog.e(TAG, "Could not contact the ContainerService");
1670                            }
1671                        } else {
1672                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1673                        }
1674
1675                        Trace.asyncTraceEnd(
1676                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1677
1678                        processPendingInstall(args, ret);
1679                        mHandler.sendEmptyMessage(MCS_UNBIND);
1680                    }
1681
1682                    break;
1683                }
1684                case START_INTENT_FILTER_VERIFICATIONS: {
1685                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1686                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1687                            params.replacing, params.pkg);
1688                    break;
1689                }
1690                case INTENT_FILTER_VERIFIED: {
1691                    final int verificationId = msg.arg1;
1692
1693                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1694                            verificationId);
1695                    if (state == null) {
1696                        Slog.w(TAG, "Invalid IntentFilter verification token "
1697                                + verificationId + " received");
1698                        break;
1699                    }
1700
1701                    final int userId = state.getUserId();
1702
1703                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1704                            "Processing IntentFilter verification with token:"
1705                            + verificationId + " and userId:" + userId);
1706
1707                    final IntentFilterVerificationResponse response =
1708                            (IntentFilterVerificationResponse) msg.obj;
1709
1710                    state.setVerifierResponse(response.callerUid, response.code);
1711
1712                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1713                            "IntentFilter verification with token:" + verificationId
1714                            + " and userId:" + userId
1715                            + " is settings verifier response with response code:"
1716                            + response.code);
1717
1718                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1719                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1720                                + response.getFailedDomainsString());
1721                    }
1722
1723                    if (state.isVerificationComplete()) {
1724                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1725                    } else {
1726                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1727                                "IntentFilter verification with token:" + verificationId
1728                                + " was not said to be complete");
1729                    }
1730
1731                    break;
1732                }
1733                case EPHEMERAL_RESOLUTION_PHASE_TWO: {
1734                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1735                            mEphemeralResolverConnection,
1736                            (EphemeralRequest) msg.obj,
1737                            mEphemeralInstallerActivity,
1738                            mHandler);
1739                }
1740            }
1741        }
1742    }
1743
1744    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1745            boolean killApp, String[] grantedPermissions,
1746            boolean launchedForRestore, String installerPackage,
1747            IPackageInstallObserver2 installObserver) {
1748        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1749            // Send the removed broadcasts
1750            if (res.removedInfo != null) {
1751                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1752            }
1753
1754            // Now that we successfully installed the package, grant runtime
1755            // permissions if requested before broadcasting the install. Also
1756            // for legacy apps in permission review mode we clear the permission
1757            // review flag which is used to emulate runtime permissions for
1758            // legacy apps.
1759            if (grantPermissions) {
1760                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1761            }
1762
1763            final boolean update = res.removedInfo != null
1764                    && res.removedInfo.removedPackage != null;
1765
1766            // If this is the first time we have child packages for a disabled privileged
1767            // app that had no children, we grant requested runtime permissions to the new
1768            // children if the parent on the system image had them already granted.
1769            if (res.pkg.parentPackage != null) {
1770                synchronized (mPackages) {
1771                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1772                }
1773            }
1774
1775            synchronized (mPackages) {
1776                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1777            }
1778
1779            final String packageName = res.pkg.applicationInfo.packageName;
1780
1781            // Determine the set of users who are adding this package for
1782            // the first time vs. those who are seeing an update.
1783            int[] firstUsers = EMPTY_INT_ARRAY;
1784            int[] updateUsers = EMPTY_INT_ARRAY;
1785            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1786            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1787            for (int newUser : res.newUsers) {
1788                if (ps.getInstantApp(newUser)) {
1789                    continue;
1790                }
1791                if (allNewUsers) {
1792                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1793                    continue;
1794                }
1795                boolean isNew = true;
1796                for (int origUser : res.origUsers) {
1797                    if (origUser == newUser) {
1798                        isNew = false;
1799                        break;
1800                    }
1801                }
1802                if (isNew) {
1803                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1804                } else {
1805                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1806                }
1807            }
1808
1809            // Send installed broadcasts if the package is not a static shared lib.
1810            if (res.pkg.staticSharedLibName == null) {
1811                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1812
1813                // Send added for users that see the package for the first time
1814                // sendPackageAddedForNewUsers also deals with system apps
1815                int appId = UserHandle.getAppId(res.uid);
1816                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1817                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1818
1819                // Send added for users that don't see the package for the first time
1820                Bundle extras = new Bundle(1);
1821                extras.putInt(Intent.EXTRA_UID, res.uid);
1822                if (update) {
1823                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1824                }
1825                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1826                        extras, 0 /*flags*/, null /*targetPackage*/,
1827                        null /*finishedReceiver*/, updateUsers);
1828
1829                // Send replaced for users that don't see the package for the first time
1830                if (update) {
1831                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1832                            packageName, extras, 0 /*flags*/,
1833                            null /*targetPackage*/, null /*finishedReceiver*/,
1834                            updateUsers);
1835                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1836                            null /*package*/, null /*extras*/, 0 /*flags*/,
1837                            packageName /*targetPackage*/,
1838                            null /*finishedReceiver*/, updateUsers);
1839                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1840                    // First-install and we did a restore, so we're responsible for the
1841                    // first-launch broadcast.
1842                    if (DEBUG_BACKUP) {
1843                        Slog.i(TAG, "Post-restore of " + packageName
1844                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1845                    }
1846                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1847                }
1848
1849                // Send broadcast package appeared if forward locked/external for all users
1850                // treat asec-hosted packages like removable media on upgrade
1851                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1852                    if (DEBUG_INSTALL) {
1853                        Slog.i(TAG, "upgrading pkg " + res.pkg
1854                                + " is ASEC-hosted -> AVAILABLE");
1855                    }
1856                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1857                    ArrayList<String> pkgList = new ArrayList<>(1);
1858                    pkgList.add(packageName);
1859                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1860                }
1861            }
1862
1863            // Work that needs to happen on first install within each user
1864            if (firstUsers != null && firstUsers.length > 0) {
1865                synchronized (mPackages) {
1866                    for (int userId : firstUsers) {
1867                        // If this app is a browser and it's newly-installed for some
1868                        // users, clear any default-browser state in those users. The
1869                        // app's nature doesn't depend on the user, so we can just check
1870                        // its browser nature in any user and generalize.
1871                        if (packageIsBrowser(packageName, userId)) {
1872                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1873                        }
1874
1875                        // We may also need to apply pending (restored) runtime
1876                        // permission grants within these users.
1877                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1878                    }
1879                }
1880            }
1881
1882            // Log current value of "unknown sources" setting
1883            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1884                    getUnknownSourcesSettings());
1885
1886            // Force a gc to clear up things
1887            Runtime.getRuntime().gc();
1888
1889            // Remove the replaced package's older resources safely now
1890            // We delete after a gc for applications  on sdcard.
1891            if (res.removedInfo != null && res.removedInfo.args != null) {
1892                synchronized (mInstallLock) {
1893                    res.removedInfo.args.doPostDeleteLI(true);
1894                }
1895            }
1896
1897            // Notify DexManager that the package was installed for new users.
1898            // The updated users should already be indexed and the package code paths
1899            // should not change.
1900            // Don't notify the manager for ephemeral apps as they are not expected to
1901            // survive long enough to benefit of background optimizations.
1902            for (int userId : firstUsers) {
1903                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1904                mDexManager.notifyPackageInstalled(info, userId);
1905            }
1906        }
1907
1908        // If someone is watching installs - notify them
1909        if (installObserver != null) {
1910            try {
1911                Bundle extras = extrasForInstallResult(res);
1912                installObserver.onPackageInstalled(res.name, res.returnCode,
1913                        res.returnMsg, extras);
1914            } catch (RemoteException e) {
1915                Slog.i(TAG, "Observer no longer exists.");
1916            }
1917        }
1918    }
1919
1920    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1921            PackageParser.Package pkg) {
1922        if (pkg.parentPackage == null) {
1923            return;
1924        }
1925        if (pkg.requestedPermissions == null) {
1926            return;
1927        }
1928        final PackageSetting disabledSysParentPs = mSettings
1929                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1930        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1931                || !disabledSysParentPs.isPrivileged()
1932                || (disabledSysParentPs.childPackageNames != null
1933                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1934            return;
1935        }
1936        final int[] allUserIds = sUserManager.getUserIds();
1937        final int permCount = pkg.requestedPermissions.size();
1938        for (int i = 0; i < permCount; i++) {
1939            String permission = pkg.requestedPermissions.get(i);
1940            BasePermission bp = mSettings.mPermissions.get(permission);
1941            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1942                continue;
1943            }
1944            for (int userId : allUserIds) {
1945                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1946                        permission, userId)) {
1947                    grantRuntimePermission(pkg.packageName, permission, userId);
1948                }
1949            }
1950        }
1951    }
1952
1953    private StorageEventListener mStorageListener = new StorageEventListener() {
1954        @Override
1955        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1956            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1957                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1958                    final String volumeUuid = vol.getFsUuid();
1959
1960                    // Clean up any users or apps that were removed or recreated
1961                    // while this volume was missing
1962                    sUserManager.reconcileUsers(volumeUuid);
1963                    reconcileApps(volumeUuid);
1964
1965                    // Clean up any install sessions that expired or were
1966                    // cancelled while this volume was missing
1967                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1968
1969                    loadPrivatePackages(vol);
1970
1971                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1972                    unloadPrivatePackages(vol);
1973                }
1974            }
1975
1976            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1977                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1978                    updateExternalMediaStatus(true, false);
1979                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1980                    updateExternalMediaStatus(false, false);
1981                }
1982            }
1983        }
1984
1985        @Override
1986        public void onVolumeForgotten(String fsUuid) {
1987            if (TextUtils.isEmpty(fsUuid)) {
1988                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1989                return;
1990            }
1991
1992            // Remove any apps installed on the forgotten volume
1993            synchronized (mPackages) {
1994                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1995                for (PackageSetting ps : packages) {
1996                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1997                    deletePackageVersioned(new VersionedPackage(ps.name,
1998                            PackageManager.VERSION_CODE_HIGHEST),
1999                            new LegacyPackageDeleteObserver(null).getBinder(),
2000                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2001                    // Try very hard to release any references to this package
2002                    // so we don't risk the system server being killed due to
2003                    // open FDs
2004                    AttributeCache.instance().removePackage(ps.name);
2005                }
2006
2007                mSettings.onVolumeForgotten(fsUuid);
2008                mSettings.writeLPr();
2009            }
2010        }
2011    };
2012
2013    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2014            String[] grantedPermissions) {
2015        for (int userId : userIds) {
2016            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2017        }
2018    }
2019
2020    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2021            String[] grantedPermissions) {
2022        SettingBase sb = (SettingBase) pkg.mExtras;
2023        if (sb == null) {
2024            return;
2025        }
2026
2027        PermissionsState permissionsState = sb.getPermissionsState();
2028
2029        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2030                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2031
2032        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2033                >= Build.VERSION_CODES.M;
2034
2035        for (String permission : pkg.requestedPermissions) {
2036            final BasePermission bp;
2037            synchronized (mPackages) {
2038                bp = mSettings.mPermissions.get(permission);
2039            }
2040            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2041                    && (grantedPermissions == null
2042                           || ArrayUtils.contains(grantedPermissions, permission))) {
2043                final int flags = permissionsState.getPermissionFlags(permission, userId);
2044                if (supportsRuntimePermissions) {
2045                    // Installer cannot change immutable permissions.
2046                    if ((flags & immutableFlags) == 0) {
2047                        grantRuntimePermission(pkg.packageName, permission, userId);
2048                    }
2049                } else if (mPermissionReviewRequired) {
2050                    // In permission review mode we clear the review flag when we
2051                    // are asked to install the app with all permissions granted.
2052                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2053                        updatePermissionFlags(permission, pkg.packageName,
2054                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2055                    }
2056                }
2057            }
2058        }
2059    }
2060
2061    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2062        Bundle extras = null;
2063        switch (res.returnCode) {
2064            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2065                extras = new Bundle();
2066                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2067                        res.origPermission);
2068                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2069                        res.origPackage);
2070                break;
2071            }
2072            case PackageManager.INSTALL_SUCCEEDED: {
2073                extras = new Bundle();
2074                extras.putBoolean(Intent.EXTRA_REPLACING,
2075                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2076                break;
2077            }
2078        }
2079        return extras;
2080    }
2081
2082    void scheduleWriteSettingsLocked() {
2083        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2084            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2085        }
2086    }
2087
2088    void scheduleWritePackageListLocked(int userId) {
2089        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2090            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2091            msg.arg1 = userId;
2092            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2093        }
2094    }
2095
2096    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2097        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2098        scheduleWritePackageRestrictionsLocked(userId);
2099    }
2100
2101    void scheduleWritePackageRestrictionsLocked(int userId) {
2102        final int[] userIds = (userId == UserHandle.USER_ALL)
2103                ? sUserManager.getUserIds() : new int[]{userId};
2104        for (int nextUserId : userIds) {
2105            if (!sUserManager.exists(nextUserId)) return;
2106            mDirtyUsers.add(nextUserId);
2107            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2108                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2109            }
2110        }
2111    }
2112
2113    public static PackageManagerService main(Context context, Installer installer,
2114            boolean factoryTest, boolean onlyCore) {
2115        // Self-check for initial settings.
2116        PackageManagerServiceCompilerMapping.checkProperties();
2117
2118        PackageManagerService m = new PackageManagerService(context, installer,
2119                factoryTest, onlyCore);
2120        m.enableSystemUserPackages();
2121        ServiceManager.addService("package", m);
2122        return m;
2123    }
2124
2125    private void enableSystemUserPackages() {
2126        if (!UserManager.isSplitSystemUser()) {
2127            return;
2128        }
2129        // For system user, enable apps based on the following conditions:
2130        // - app is whitelisted or belong to one of these groups:
2131        //   -- system app which has no launcher icons
2132        //   -- system app which has INTERACT_ACROSS_USERS permission
2133        //   -- system IME app
2134        // - app is not in the blacklist
2135        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2136        Set<String> enableApps = new ArraySet<>();
2137        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2138                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2139                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2140        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2141        enableApps.addAll(wlApps);
2142        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2143                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2144        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2145        enableApps.removeAll(blApps);
2146        Log.i(TAG, "Applications installed for system user: " + enableApps);
2147        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2148                UserHandle.SYSTEM);
2149        final int allAppsSize = allAps.size();
2150        synchronized (mPackages) {
2151            for (int i = 0; i < allAppsSize; i++) {
2152                String pName = allAps.get(i);
2153                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2154                // Should not happen, but we shouldn't be failing if it does
2155                if (pkgSetting == null) {
2156                    continue;
2157                }
2158                boolean install = enableApps.contains(pName);
2159                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2160                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2161                            + " for system user");
2162                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2163                }
2164            }
2165            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2166        }
2167    }
2168
2169    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2170        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2171                Context.DISPLAY_SERVICE);
2172        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2173    }
2174
2175    /**
2176     * Requests that files preopted on a secondary system partition be copied to the data partition
2177     * if possible.  Note that the actual copying of the files is accomplished by init for security
2178     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2179     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2180     */
2181    private static void requestCopyPreoptedFiles() {
2182        final int WAIT_TIME_MS = 100;
2183        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2184        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2185            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2186            // We will wait for up to 100 seconds.
2187            final long timeStart = SystemClock.uptimeMillis();
2188            final long timeEnd = timeStart + 100 * 1000;
2189            long timeNow = timeStart;
2190            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2191                try {
2192                    Thread.sleep(WAIT_TIME_MS);
2193                } catch (InterruptedException e) {
2194                    // Do nothing
2195                }
2196                timeNow = SystemClock.uptimeMillis();
2197                if (timeNow > timeEnd) {
2198                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2199                    Slog.wtf(TAG, "cppreopt did not finish!");
2200                    break;
2201                }
2202            }
2203
2204            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2205        }
2206    }
2207
2208    public PackageManagerService(Context context, Installer installer,
2209            boolean factoryTest, boolean onlyCore) {
2210        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2211        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2212                SystemClock.uptimeMillis());
2213
2214        if (mSdkVersion <= 0) {
2215            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2216        }
2217
2218        mContext = context;
2219
2220        mPermissionReviewRequired = context.getResources().getBoolean(
2221                R.bool.config_permissionReviewRequired);
2222
2223        mFactoryTest = factoryTest;
2224        mOnlyCore = onlyCore;
2225        mMetrics = new DisplayMetrics();
2226        mSettings = new Settings(mPackages);
2227        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2228                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2229        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2230                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2231        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2232                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2233        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2234                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2235        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2236                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2237        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2238                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2239
2240        String separateProcesses = SystemProperties.get("debug.separate_processes");
2241        if (separateProcesses != null && separateProcesses.length() > 0) {
2242            if ("*".equals(separateProcesses)) {
2243                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2244                mSeparateProcesses = null;
2245                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2246            } else {
2247                mDefParseFlags = 0;
2248                mSeparateProcesses = separateProcesses.split(",");
2249                Slog.w(TAG, "Running with debug.separate_processes: "
2250                        + separateProcesses);
2251            }
2252        } else {
2253            mDefParseFlags = 0;
2254            mSeparateProcesses = null;
2255        }
2256
2257        mInstaller = installer;
2258        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2259                "*dexopt*");
2260        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2261        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2262
2263        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2264                FgThread.get().getLooper());
2265
2266        getDefaultDisplayMetrics(context, mMetrics);
2267
2268        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2269        SystemConfig systemConfig = SystemConfig.getInstance();
2270        mGlobalGids = systemConfig.getGlobalGids();
2271        mSystemPermissions = systemConfig.getSystemPermissions();
2272        mAvailableFeatures = systemConfig.getAvailableFeatures();
2273        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2274
2275        mProtectedPackages = new ProtectedPackages(mContext);
2276
2277        synchronized (mInstallLock) {
2278        // writer
2279        synchronized (mPackages) {
2280            mHandlerThread = new ServiceThread(TAG,
2281                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2282            mHandlerThread.start();
2283            mHandler = new PackageHandler(mHandlerThread.getLooper());
2284            mProcessLoggingHandler = new ProcessLoggingHandler();
2285            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2286
2287            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2288            mInstantAppRegistry = new InstantAppRegistry(this);
2289
2290            File dataDir = Environment.getDataDirectory();
2291            mAppInstallDir = new File(dataDir, "app");
2292            mAppLib32InstallDir = new File(dataDir, "app-lib");
2293            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2294            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2295            sUserManager = new UserManagerService(context, this,
2296                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2297
2298            // Propagate permission configuration in to package manager.
2299            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2300                    = systemConfig.getPermissions();
2301            for (int i=0; i<permConfig.size(); i++) {
2302                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2303                BasePermission bp = mSettings.mPermissions.get(perm.name);
2304                if (bp == null) {
2305                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2306                    mSettings.mPermissions.put(perm.name, bp);
2307                }
2308                if (perm.gids != null) {
2309                    bp.setGids(perm.gids, perm.perUser);
2310                }
2311            }
2312
2313            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2314            final int builtInLibCount = libConfig.size();
2315            for (int i = 0; i < builtInLibCount; i++) {
2316                String name = libConfig.keyAt(i);
2317                String path = libConfig.valueAt(i);
2318                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2319                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2320            }
2321
2322            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2323
2324            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2325            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2326            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2327
2328            // Clean up orphaned packages for which the code path doesn't exist
2329            // and they are an update to a system app - caused by bug/32321269
2330            final int packageSettingCount = mSettings.mPackages.size();
2331            for (int i = packageSettingCount - 1; i >= 0; i--) {
2332                PackageSetting ps = mSettings.mPackages.valueAt(i);
2333                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2334                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2335                    mSettings.mPackages.removeAt(i);
2336                    mSettings.enableSystemPackageLPw(ps.name);
2337                }
2338            }
2339
2340            if (mFirstBoot) {
2341                requestCopyPreoptedFiles();
2342            }
2343
2344            String customResolverActivity = Resources.getSystem().getString(
2345                    R.string.config_customResolverActivity);
2346            if (TextUtils.isEmpty(customResolverActivity)) {
2347                customResolverActivity = null;
2348            } else {
2349                mCustomResolverComponentName = ComponentName.unflattenFromString(
2350                        customResolverActivity);
2351            }
2352
2353            long startTime = SystemClock.uptimeMillis();
2354
2355            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2356                    startTime);
2357
2358            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2359            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2360
2361            if (bootClassPath == null) {
2362                Slog.w(TAG, "No BOOTCLASSPATH found!");
2363            }
2364
2365            if (systemServerClassPath == null) {
2366                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2367            }
2368
2369            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2370            final String[] dexCodeInstructionSets =
2371                    getDexCodeInstructionSets(
2372                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2373
2374            /**
2375             * Ensure all external libraries have had dexopt run on them.
2376             */
2377            if (mSharedLibraries.size() > 0) {
2378                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2379                // NOTE: For now, we're compiling these system "shared libraries"
2380                // (and framework jars) into all available architectures. It's possible
2381                // to compile them only when we come across an app that uses them (there's
2382                // already logic for that in scanPackageLI) but that adds some complexity.
2383                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2384                    final int libCount = mSharedLibraries.size();
2385                    for (int i = 0; i < libCount; i++) {
2386                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2387                        final int versionCount = versionedLib.size();
2388                        for (int j = 0; j < versionCount; j++) {
2389                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2390                            final String libPath = libEntry.path != null
2391                                    ? libEntry.path : libEntry.apk;
2392                            if (libPath == null) {
2393                                continue;
2394                            }
2395                            try {
2396                                // Shared libraries do not have profiles so we perform a full
2397                                // AOT compilation (if needed).
2398                                int dexoptNeeded = DexFile.getDexOptNeeded(
2399                                        libPath, dexCodeInstructionSet,
2400                                        getCompilerFilterForReason(REASON_SHARED_APK),
2401                                        false /* newProfile */);
2402                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2403                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2404                                            dexCodeInstructionSet, dexoptNeeded, null,
2405                                            DEXOPT_PUBLIC,
2406                                            getCompilerFilterForReason(REASON_SHARED_APK),
2407                                            StorageManager.UUID_PRIVATE_INTERNAL,
2408                                            PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK);
2409                                }
2410                            } catch (FileNotFoundException e) {
2411                                Slog.w(TAG, "Library not found: " + libPath);
2412                            } catch (IOException | InstallerException e) {
2413                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2414                                        + e.getMessage());
2415                            }
2416                        }
2417                    }
2418                }
2419                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2420            }
2421
2422            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2423
2424            final VersionInfo ver = mSettings.getInternalVersion();
2425            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2426
2427            // when upgrading from pre-M, promote system app permissions from install to runtime
2428            mPromoteSystemApps =
2429                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2430
2431            // When upgrading from pre-N, we need to handle package extraction like first boot,
2432            // as there is no profiling data available.
2433            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2434
2435            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2436
2437            // save off the names of pre-existing system packages prior to scanning; we don't
2438            // want to automatically grant runtime permissions for new system apps
2439            if (mPromoteSystemApps) {
2440                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2441                while (pkgSettingIter.hasNext()) {
2442                    PackageSetting ps = pkgSettingIter.next();
2443                    if (isSystemApp(ps)) {
2444                        mExistingSystemPackages.add(ps.name);
2445                    }
2446                }
2447            }
2448
2449            mCacheDir = preparePackageParserCache(mIsUpgrade);
2450
2451            // Set flag to monitor and not change apk file paths when
2452            // scanning install directories.
2453            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2454
2455            if (mIsUpgrade || mFirstBoot) {
2456                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2457            }
2458
2459            // Collect vendor overlay packages. (Do this before scanning any apps.)
2460            // For security and version matching reason, only consider
2461            // overlay packages if they reside in the right directory.
2462            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2463            if (overlayThemeDir.isEmpty()) {
2464                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2465            }
2466            if (!overlayThemeDir.isEmpty()) {
2467                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2468                        | PackageParser.PARSE_IS_SYSTEM
2469                        | PackageParser.PARSE_IS_SYSTEM_DIR
2470                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2471            }
2472            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2473                    | PackageParser.PARSE_IS_SYSTEM
2474                    | PackageParser.PARSE_IS_SYSTEM_DIR
2475                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2476
2477            // Find base frameworks (resource packages without code).
2478            scanDirTracedLI(frameworkDir, mDefParseFlags
2479                    | PackageParser.PARSE_IS_SYSTEM
2480                    | PackageParser.PARSE_IS_SYSTEM_DIR
2481                    | PackageParser.PARSE_IS_PRIVILEGED,
2482                    scanFlags | SCAN_NO_DEX, 0);
2483
2484            // Collected privileged system packages.
2485            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2486            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2487                    | PackageParser.PARSE_IS_SYSTEM
2488                    | PackageParser.PARSE_IS_SYSTEM_DIR
2489                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2490
2491            // Collect ordinary system packages.
2492            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2493            scanDirTracedLI(systemAppDir, mDefParseFlags
2494                    | PackageParser.PARSE_IS_SYSTEM
2495                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2496
2497            // Collect all vendor packages.
2498            File vendorAppDir = new File("/vendor/app");
2499            try {
2500                vendorAppDir = vendorAppDir.getCanonicalFile();
2501            } catch (IOException e) {
2502                // failed to look up canonical path, continue with original one
2503            }
2504            scanDirTracedLI(vendorAppDir, mDefParseFlags
2505                    | PackageParser.PARSE_IS_SYSTEM
2506                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2507
2508            // Collect all OEM packages.
2509            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2510            scanDirTracedLI(oemAppDir, mDefParseFlags
2511                    | PackageParser.PARSE_IS_SYSTEM
2512                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2513
2514            // Prune any system packages that no longer exist.
2515            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2516            if (!mOnlyCore) {
2517                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2518                while (psit.hasNext()) {
2519                    PackageSetting ps = psit.next();
2520
2521                    /*
2522                     * If this is not a system app, it can't be a
2523                     * disable system app.
2524                     */
2525                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2526                        continue;
2527                    }
2528
2529                    /*
2530                     * If the package is scanned, it's not erased.
2531                     */
2532                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2533                    if (scannedPkg != null) {
2534                        /*
2535                         * If the system app is both scanned and in the
2536                         * disabled packages list, then it must have been
2537                         * added via OTA. Remove it from the currently
2538                         * scanned package so the previously user-installed
2539                         * application can be scanned.
2540                         */
2541                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2542                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2543                                    + ps.name + "; removing system app.  Last known codePath="
2544                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2545                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2546                                    + scannedPkg.mVersionCode);
2547                            removePackageLI(scannedPkg, true);
2548                            mExpectingBetter.put(ps.name, ps.codePath);
2549                        }
2550
2551                        continue;
2552                    }
2553
2554                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2555                        psit.remove();
2556                        logCriticalInfo(Log.WARN, "System package " + ps.name
2557                                + " no longer exists; it's data will be wiped");
2558                        // Actual deletion of code and data will be handled by later
2559                        // reconciliation step
2560                    } else {
2561                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2562                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2563                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2564                        }
2565                    }
2566                }
2567            }
2568
2569            //look for any incomplete package installations
2570            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2571            for (int i = 0; i < deletePkgsList.size(); i++) {
2572                // Actual deletion of code and data will be handled by later
2573                // reconciliation step
2574                final String packageName = deletePkgsList.get(i).name;
2575                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2576                synchronized (mPackages) {
2577                    mSettings.removePackageLPw(packageName);
2578                }
2579            }
2580
2581            //delete tmp files
2582            deleteTempPackageFiles();
2583
2584            // Remove any shared userIDs that have no associated packages
2585            mSettings.pruneSharedUsersLPw();
2586
2587            if (!mOnlyCore) {
2588                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2589                        SystemClock.uptimeMillis());
2590                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2591
2592                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2593                        | PackageParser.PARSE_FORWARD_LOCK,
2594                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2595
2596                /**
2597                 * Remove disable package settings for any updated system
2598                 * apps that were removed via an OTA. If they're not a
2599                 * previously-updated app, remove them completely.
2600                 * Otherwise, just revoke their system-level permissions.
2601                 */
2602                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2603                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2604                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2605
2606                    String msg;
2607                    if (deletedPkg == null) {
2608                        msg = "Updated system package " + deletedAppName
2609                                + " no longer exists; it's data will be wiped";
2610                        // Actual deletion of code and data will be handled by later
2611                        // reconciliation step
2612                    } else {
2613                        msg = "Updated system app + " + deletedAppName
2614                                + " no longer present; removing system privileges for "
2615                                + deletedAppName;
2616
2617                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2618
2619                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2620                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2621                    }
2622                    logCriticalInfo(Log.WARN, msg);
2623                }
2624
2625                /**
2626                 * Make sure all system apps that we expected to appear on
2627                 * the userdata partition actually showed up. If they never
2628                 * appeared, crawl back and revive the system version.
2629                 */
2630                for (int i = 0; i < mExpectingBetter.size(); i++) {
2631                    final String packageName = mExpectingBetter.keyAt(i);
2632                    if (!mPackages.containsKey(packageName)) {
2633                        final File scanFile = mExpectingBetter.valueAt(i);
2634
2635                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2636                                + " but never showed up; reverting to system");
2637
2638                        int reparseFlags = mDefParseFlags;
2639                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2640                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2641                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2642                                    | PackageParser.PARSE_IS_PRIVILEGED;
2643                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2644                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2645                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2646                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2647                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2648                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2649                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2650                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2651                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2652                        } else {
2653                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2654                            continue;
2655                        }
2656
2657                        mSettings.enableSystemPackageLPw(packageName);
2658
2659                        try {
2660                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2661                        } catch (PackageManagerException e) {
2662                            Slog.e(TAG, "Failed to parse original system package: "
2663                                    + e.getMessage());
2664                        }
2665                    }
2666                }
2667            }
2668            mExpectingBetter.clear();
2669
2670            // Resolve the storage manager.
2671            mStorageManagerPackage = getStorageManagerPackageName();
2672
2673            // Resolve protected action filters. Only the setup wizard is allowed to
2674            // have a high priority filter for these actions.
2675            mSetupWizardPackage = getSetupWizardPackageName();
2676            if (mProtectedFilters.size() > 0) {
2677                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2678                    Slog.i(TAG, "No setup wizard;"
2679                        + " All protected intents capped to priority 0");
2680                }
2681                for (ActivityIntentInfo filter : mProtectedFilters) {
2682                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2683                        if (DEBUG_FILTERS) {
2684                            Slog.i(TAG, "Found setup wizard;"
2685                                + " allow priority " + filter.getPriority() + ";"
2686                                + " package: " + filter.activity.info.packageName
2687                                + " activity: " + filter.activity.className
2688                                + " priority: " + filter.getPriority());
2689                        }
2690                        // skip setup wizard; allow it to keep the high priority filter
2691                        continue;
2692                    }
2693                    Slog.w(TAG, "Protected action; cap priority to 0;"
2694                            + " package: " + filter.activity.info.packageName
2695                            + " activity: " + filter.activity.className
2696                            + " origPrio: " + filter.getPriority());
2697                    filter.setPriority(0);
2698                }
2699            }
2700            mDeferProtectedFilters = false;
2701            mProtectedFilters.clear();
2702
2703            // Now that we know all of the shared libraries, update all clients to have
2704            // the correct library paths.
2705            updateAllSharedLibrariesLPw(null);
2706
2707            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2708                // NOTE: We ignore potential failures here during a system scan (like
2709                // the rest of the commands above) because there's precious little we
2710                // can do about it. A settings error is reported, though.
2711                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2712            }
2713
2714            // Now that we know all the packages we are keeping,
2715            // read and update their last usage times.
2716            mPackageUsage.read(mPackages);
2717            mCompilerStats.read();
2718
2719            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2720                    SystemClock.uptimeMillis());
2721            Slog.i(TAG, "Time to scan packages: "
2722                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2723                    + " seconds");
2724
2725            // If the platform SDK has changed since the last time we booted,
2726            // we need to re-grant app permission to catch any new ones that
2727            // appear.  This is really a hack, and means that apps can in some
2728            // cases get permissions that the user didn't initially explicitly
2729            // allow...  it would be nice to have some better way to handle
2730            // this situation.
2731            int updateFlags = UPDATE_PERMISSIONS_ALL;
2732            if (ver.sdkVersion != mSdkVersion) {
2733                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2734                        + mSdkVersion + "; regranting permissions for internal storage");
2735                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2736            }
2737            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2738            ver.sdkVersion = mSdkVersion;
2739
2740            // If this is the first boot or an update from pre-M, and it is a normal
2741            // boot, then we need to initialize the default preferred apps across
2742            // all defined users.
2743            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2744                for (UserInfo user : sUserManager.getUsers(true)) {
2745                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2746                    applyFactoryDefaultBrowserLPw(user.id);
2747                    primeDomainVerificationsLPw(user.id);
2748                }
2749            }
2750
2751            // Prepare storage for system user really early during boot,
2752            // since core system apps like SettingsProvider and SystemUI
2753            // can't wait for user to start
2754            final int storageFlags;
2755            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2756                storageFlags = StorageManager.FLAG_STORAGE_DE;
2757            } else {
2758                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2759            }
2760            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2761                    storageFlags, true /* migrateAppData */);
2762
2763            // If this is first boot after an OTA, and a normal boot, then
2764            // we need to clear code cache directories.
2765            // Note that we do *not* clear the application profiles. These remain valid
2766            // across OTAs and are used to drive profile verification (post OTA) and
2767            // profile compilation (without waiting to collect a fresh set of profiles).
2768            if (mIsUpgrade && !onlyCore) {
2769                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2770                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2771                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2772                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2773                        // No apps are running this early, so no need to freeze
2774                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2775                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2776                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2777                    }
2778                }
2779                ver.fingerprint = Build.FINGERPRINT;
2780            }
2781
2782            checkDefaultBrowser();
2783
2784            // clear only after permissions and other defaults have been updated
2785            mExistingSystemPackages.clear();
2786            mPromoteSystemApps = false;
2787
2788            // All the changes are done during package scanning.
2789            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2790
2791            // can downgrade to reader
2792            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2793            mSettings.writeLPr();
2794            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2795
2796            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2797            // early on (before the package manager declares itself as early) because other
2798            // components in the system server might ask for package contexts for these apps.
2799            //
2800            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2801            // (i.e, that the data partition is unavailable).
2802            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2803                long start = System.nanoTime();
2804                List<PackageParser.Package> coreApps = new ArrayList<>();
2805                for (PackageParser.Package pkg : mPackages.values()) {
2806                    if (pkg.coreApp) {
2807                        coreApps.add(pkg);
2808                    }
2809                }
2810
2811                int[] stats = performDexOptUpgrade(coreApps, false,
2812                        getCompilerFilterForReason(REASON_CORE_APP));
2813
2814                final int elapsedTimeSeconds =
2815                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2816                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2817
2818                if (DEBUG_DEXOPT) {
2819                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2820                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2821                }
2822
2823
2824                // TODO: Should we log these stats to tron too ?
2825                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2826                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2827                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2828                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2829            }
2830
2831            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2832                    SystemClock.uptimeMillis());
2833
2834            if (!mOnlyCore) {
2835                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2836                mRequiredInstallerPackage = getRequiredInstallerLPr();
2837                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2838                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2839                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2840                        mIntentFilterVerifierComponent);
2841                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2842                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2843                        SharedLibraryInfo.VERSION_UNDEFINED);
2844                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2845                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2846                        SharedLibraryInfo.VERSION_UNDEFINED);
2847            } else {
2848                mRequiredVerifierPackage = null;
2849                mRequiredInstallerPackage = null;
2850                mRequiredUninstallerPackage = null;
2851                mIntentFilterVerifierComponent = null;
2852                mIntentFilterVerifier = null;
2853                mServicesSystemSharedLibraryPackageName = null;
2854                mSharedSystemSharedLibraryPackageName = null;
2855            }
2856
2857            mInstallerService = new PackageInstallerService(context, this);
2858
2859            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2860            if (ephemeralResolverComponent != null) {
2861                if (DEBUG_EPHEMERAL) {
2862                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2863                }
2864                mEphemeralResolverConnection =
2865                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2866            } else {
2867                mEphemeralResolverConnection = null;
2868            }
2869            mEphemeralInstallerComponent = getEphemeralInstallerLPr();
2870            if (mEphemeralInstallerComponent != null) {
2871                if (DEBUG_EPHEMERAL) {
2872                    Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent);
2873                }
2874                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2875            }
2876
2877            // Read and update the usage of dex files.
2878            // Do this at the end of PM init so that all the packages have their
2879            // data directory reconciled.
2880            // At this point we know the code paths of the packages, so we can validate
2881            // the disk file and build the internal cache.
2882            // The usage file is expected to be small so loading and verifying it
2883            // should take a fairly small time compare to the other activities (e.g. package
2884            // scanning).
2885            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2886            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2887            for (int userId : currentUserIds) {
2888                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2889            }
2890            mDexManager.load(userPackages);
2891        } // synchronized (mPackages)
2892        } // synchronized (mInstallLock)
2893
2894        // Now after opening every single application zip, make sure they
2895        // are all flushed.  Not really needed, but keeps things nice and
2896        // tidy.
2897        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2898        Runtime.getRuntime().gc();
2899        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2900
2901        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2902        FallbackCategoryProvider.loadFallbacks();
2903        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2904
2905        // The initial scanning above does many calls into installd while
2906        // holding the mPackages lock, but we're mostly interested in yelling
2907        // once we have a booted system.
2908        mInstaller.setWarnIfHeld(mPackages);
2909
2910        // Expose private service for system components to use.
2911        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2912        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2913    }
2914
2915    private static File preparePackageParserCache(boolean isUpgrade) {
2916        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2917            return null;
2918        }
2919
2920        // Disable package parsing on eng builds to allow for faster incremental development.
2921        if ("eng".equals(Build.TYPE)) {
2922            return null;
2923        }
2924
2925        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2926            Slog.i(TAG, "Disabling package parser cache due to system property.");
2927            return null;
2928        }
2929
2930        // The base directory for the package parser cache lives under /data/system/.
2931        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2932                "package_cache");
2933        if (cacheBaseDir == null) {
2934            return null;
2935        }
2936
2937        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2938        // This also serves to "GC" unused entries when the package cache version changes (which
2939        // can only happen during upgrades).
2940        if (isUpgrade) {
2941            FileUtils.deleteContents(cacheBaseDir);
2942        }
2943
2944
2945        // Return the versioned package cache directory. This is something like
2946        // "/data/system/package_cache/1"
2947        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2948
2949        // The following is a workaround to aid development on non-numbered userdebug
2950        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2951        // the system partition is newer.
2952        //
2953        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2954        // that starts with "eng." to signify that this is an engineering build and not
2955        // destined for release.
2956        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2957            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2958
2959            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2960            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2961            // in general and should not be used for production changes. In this specific case,
2962            // we know that they will work.
2963            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2964            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2965                FileUtils.deleteContents(cacheBaseDir);
2966                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2967            }
2968        }
2969
2970        return cacheDir;
2971    }
2972
2973    @Override
2974    public boolean isFirstBoot() {
2975        return mFirstBoot;
2976    }
2977
2978    @Override
2979    public boolean isOnlyCoreApps() {
2980        return mOnlyCore;
2981    }
2982
2983    @Override
2984    public boolean isUpgrade() {
2985        return mIsUpgrade;
2986    }
2987
2988    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2989        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2990
2991        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2992                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2993                UserHandle.USER_SYSTEM);
2994        if (matches.size() == 1) {
2995            return matches.get(0).getComponentInfo().packageName;
2996        } else if (matches.size() == 0) {
2997            Log.e(TAG, "There should probably be a verifier, but, none were found");
2998            return null;
2999        }
3000        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3001    }
3002
3003    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3004        synchronized (mPackages) {
3005            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3006            if (libraryEntry == null) {
3007                throw new IllegalStateException("Missing required shared library:" + name);
3008            }
3009            return libraryEntry.apk;
3010        }
3011    }
3012
3013    private @NonNull String getRequiredInstallerLPr() {
3014        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3015        intent.addCategory(Intent.CATEGORY_DEFAULT);
3016        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3017
3018        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3019                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3020                UserHandle.USER_SYSTEM);
3021        if (matches.size() == 1) {
3022            ResolveInfo resolveInfo = matches.get(0);
3023            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3024                throw new RuntimeException("The installer must be a privileged app");
3025            }
3026            return matches.get(0).getComponentInfo().packageName;
3027        } else {
3028            throw new RuntimeException("There must be exactly one installer; found " + matches);
3029        }
3030    }
3031
3032    private @NonNull String getRequiredUninstallerLPr() {
3033        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3034        intent.addCategory(Intent.CATEGORY_DEFAULT);
3035        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3036
3037        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3038                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3039                UserHandle.USER_SYSTEM);
3040        if (resolveInfo == null ||
3041                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3042            throw new RuntimeException("There must be exactly one uninstaller; found "
3043                    + resolveInfo);
3044        }
3045        return resolveInfo.getComponentInfo().packageName;
3046    }
3047
3048    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3049        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3050
3051        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3052                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3053                UserHandle.USER_SYSTEM);
3054        ResolveInfo best = null;
3055        final int N = matches.size();
3056        for (int i = 0; i < N; i++) {
3057            final ResolveInfo cur = matches.get(i);
3058            final String packageName = cur.getComponentInfo().packageName;
3059            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3060                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3061                continue;
3062            }
3063
3064            if (best == null || cur.priority > best.priority) {
3065                best = cur;
3066            }
3067        }
3068
3069        if (best != null) {
3070            return best.getComponentInfo().getComponentName();
3071        } else {
3072            throw new RuntimeException("There must be at least one intent filter verifier");
3073        }
3074    }
3075
3076    private @Nullable ComponentName getEphemeralResolverLPr() {
3077        final String[] packageArray =
3078                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3079        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3080            if (DEBUG_EPHEMERAL) {
3081                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3082            }
3083            return null;
3084        }
3085
3086        final int resolveFlags =
3087                MATCH_DIRECT_BOOT_AWARE
3088                | MATCH_DIRECT_BOOT_UNAWARE
3089                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3090        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3091        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3092                resolveFlags, UserHandle.USER_SYSTEM);
3093
3094        final int N = resolvers.size();
3095        if (N == 0) {
3096            if (DEBUG_EPHEMERAL) {
3097                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3098            }
3099            return null;
3100        }
3101
3102        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3103        for (int i = 0; i < N; i++) {
3104            final ResolveInfo info = resolvers.get(i);
3105
3106            if (info.serviceInfo == null) {
3107                continue;
3108            }
3109
3110            final String packageName = info.serviceInfo.packageName;
3111            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3112                if (DEBUG_EPHEMERAL) {
3113                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3114                            + " pkg: " + packageName + ", info:" + info);
3115                }
3116                continue;
3117            }
3118
3119            if (DEBUG_EPHEMERAL) {
3120                Slog.v(TAG, "Ephemeral resolver found;"
3121                        + " pkg: " + packageName + ", info:" + info);
3122            }
3123            return new ComponentName(packageName, info.serviceInfo.name);
3124        }
3125        if (DEBUG_EPHEMERAL) {
3126            Slog.v(TAG, "Ephemeral resolver NOT found");
3127        }
3128        return null;
3129    }
3130
3131    private @Nullable ComponentName getEphemeralInstallerLPr() {
3132        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3133        intent.addCategory(Intent.CATEGORY_DEFAULT);
3134        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3135
3136        final int resolveFlags =
3137                MATCH_DIRECT_BOOT_AWARE
3138                | MATCH_DIRECT_BOOT_UNAWARE
3139                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3140        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3141                resolveFlags, UserHandle.USER_SYSTEM);
3142        Iterator<ResolveInfo> iter = matches.iterator();
3143        while (iter.hasNext()) {
3144            final ResolveInfo rInfo = iter.next();
3145            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3146            if (ps != null) {
3147                final PermissionsState permissionsState = ps.getPermissionsState();
3148                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3149                    continue;
3150                }
3151            }
3152            iter.remove();
3153        }
3154        if (matches.size() == 0) {
3155            return null;
3156        } else if (matches.size() == 1) {
3157            return matches.get(0).getComponentInfo().getComponentName();
3158        } else {
3159            throw new RuntimeException(
3160                    "There must be at most one ephemeral installer; found " + matches);
3161        }
3162    }
3163
3164    private void primeDomainVerificationsLPw(int userId) {
3165        if (DEBUG_DOMAIN_VERIFICATION) {
3166            Slog.d(TAG, "Priming domain verifications in user " + userId);
3167        }
3168
3169        SystemConfig systemConfig = SystemConfig.getInstance();
3170        ArraySet<String> packages = systemConfig.getLinkedApps();
3171
3172        for (String packageName : packages) {
3173            PackageParser.Package pkg = mPackages.get(packageName);
3174            if (pkg != null) {
3175                if (!pkg.isSystemApp()) {
3176                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3177                    continue;
3178                }
3179
3180                ArraySet<String> domains = null;
3181                for (PackageParser.Activity a : pkg.activities) {
3182                    for (ActivityIntentInfo filter : a.intents) {
3183                        if (hasValidDomains(filter)) {
3184                            if (domains == null) {
3185                                domains = new ArraySet<String>();
3186                            }
3187                            domains.addAll(filter.getHostsList());
3188                        }
3189                    }
3190                }
3191
3192                if (domains != null && domains.size() > 0) {
3193                    if (DEBUG_DOMAIN_VERIFICATION) {
3194                        Slog.v(TAG, "      + " + packageName);
3195                    }
3196                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3197                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3198                    // and then 'always' in the per-user state actually used for intent resolution.
3199                    final IntentFilterVerificationInfo ivi;
3200                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3201                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3202                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3203                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3204                } else {
3205                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3206                            + "' does not handle web links");
3207                }
3208            } else {
3209                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3210            }
3211        }
3212
3213        scheduleWritePackageRestrictionsLocked(userId);
3214        scheduleWriteSettingsLocked();
3215    }
3216
3217    private void applyFactoryDefaultBrowserLPw(int userId) {
3218        // The default browser app's package name is stored in a string resource,
3219        // with a product-specific overlay used for vendor customization.
3220        String browserPkg = mContext.getResources().getString(
3221                com.android.internal.R.string.default_browser);
3222        if (!TextUtils.isEmpty(browserPkg)) {
3223            // non-empty string => required to be a known package
3224            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3225            if (ps == null) {
3226                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3227                browserPkg = null;
3228            } else {
3229                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3230            }
3231        }
3232
3233        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3234        // default.  If there's more than one, just leave everything alone.
3235        if (browserPkg == null) {
3236            calculateDefaultBrowserLPw(userId);
3237        }
3238    }
3239
3240    private void calculateDefaultBrowserLPw(int userId) {
3241        List<String> allBrowsers = resolveAllBrowserApps(userId);
3242        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3243        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3244    }
3245
3246    private List<String> resolveAllBrowserApps(int userId) {
3247        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3248        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3249                PackageManager.MATCH_ALL, userId);
3250
3251        final int count = list.size();
3252        List<String> result = new ArrayList<String>(count);
3253        for (int i=0; i<count; i++) {
3254            ResolveInfo info = list.get(i);
3255            if (info.activityInfo == null
3256                    || !info.handleAllWebDataURI
3257                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3258                    || result.contains(info.activityInfo.packageName)) {
3259                continue;
3260            }
3261            result.add(info.activityInfo.packageName);
3262        }
3263
3264        return result;
3265    }
3266
3267    private boolean packageIsBrowser(String packageName, int userId) {
3268        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3269                PackageManager.MATCH_ALL, userId);
3270        final int N = list.size();
3271        for (int i = 0; i < N; i++) {
3272            ResolveInfo info = list.get(i);
3273            if (packageName.equals(info.activityInfo.packageName)) {
3274                return true;
3275            }
3276        }
3277        return false;
3278    }
3279
3280    private void checkDefaultBrowser() {
3281        final int myUserId = UserHandle.myUserId();
3282        final String packageName = getDefaultBrowserPackageName(myUserId);
3283        if (packageName != null) {
3284            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3285            if (info == null) {
3286                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3287                synchronized (mPackages) {
3288                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3289                }
3290            }
3291        }
3292    }
3293
3294    @Override
3295    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3296            throws RemoteException {
3297        try {
3298            return super.onTransact(code, data, reply, flags);
3299        } catch (RuntimeException e) {
3300            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3301                Slog.wtf(TAG, "Package Manager Crash", e);
3302            }
3303            throw e;
3304        }
3305    }
3306
3307    static int[] appendInts(int[] cur, int[] add) {
3308        if (add == null) return cur;
3309        if (cur == null) return add;
3310        final int N = add.length;
3311        for (int i=0; i<N; i++) {
3312            cur = appendInt(cur, add[i]);
3313        }
3314        return cur;
3315    }
3316
3317    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3318        if (!sUserManager.exists(userId)) return null;
3319        if (ps == null) {
3320            return null;
3321        }
3322        final PackageParser.Package p = ps.pkg;
3323        if (p == null) {
3324            return null;
3325        }
3326        // Filter out ephemeral app metadata:
3327        //   * The system/shell/root can see metadata for any app
3328        //   * An installed app can see metadata for 1) other installed apps
3329        //     and 2) ephemeral apps that have explicitly interacted with it
3330        //   * Ephemeral apps can only see their own metadata
3331        //   * Holding a signature permission allows seeing instant apps
3332        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3333        if (callingAppId != Process.SYSTEM_UID
3334                && callingAppId != Process.SHELL_UID
3335                && callingAppId != Process.ROOT_UID
3336                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3337                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3338            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3339            if (instantAppPackageName != null) {
3340                // ephemeral apps can only get information on themselves
3341                if (!instantAppPackageName.equals(p.packageName)) {
3342                    return null;
3343                }
3344            } else {
3345                if (ps.getInstantApp(userId)) {
3346                    // only get access to the ephemeral app if we've been granted access
3347                    if (!mInstantAppRegistry.isInstantAccessGranted(
3348                            userId, callingAppId, ps.appId)) {
3349                        return null;
3350                    }
3351                }
3352            }
3353        }
3354
3355        final PermissionsState permissionsState = ps.getPermissionsState();
3356
3357        // Compute GIDs only if requested
3358        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3359                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3360        // Compute granted permissions only if package has requested permissions
3361        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3362                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3363        final PackageUserState state = ps.readUserState(userId);
3364
3365        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3366                && ps.isSystem()) {
3367            flags |= MATCH_ANY_USER;
3368        }
3369
3370        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3371                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3372
3373        if (packageInfo == null) {
3374            return null;
3375        }
3376
3377        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3378                resolveExternalPackageNameLPr(p);
3379
3380        return packageInfo;
3381    }
3382
3383    @Override
3384    public void checkPackageStartable(String packageName, int userId) {
3385        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3386
3387        synchronized (mPackages) {
3388            final PackageSetting ps = mSettings.mPackages.get(packageName);
3389            if (ps == null) {
3390                throw new SecurityException("Package " + packageName + " was not found!");
3391            }
3392
3393            if (!ps.getInstalled(userId)) {
3394                throw new SecurityException(
3395                        "Package " + packageName + " was not installed for user " + userId + "!");
3396            }
3397
3398            if (mSafeMode && !ps.isSystem()) {
3399                throw new SecurityException("Package " + packageName + " not a system app!");
3400            }
3401
3402            if (mFrozenPackages.contains(packageName)) {
3403                throw new SecurityException("Package " + packageName + " is currently frozen!");
3404            }
3405
3406            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3407                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3408                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3409            }
3410        }
3411    }
3412
3413    @Override
3414    public boolean isPackageAvailable(String packageName, int userId) {
3415        if (!sUserManager.exists(userId)) return false;
3416        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3417                false /* requireFullPermission */, false /* checkShell */, "is package available");
3418        synchronized (mPackages) {
3419            PackageParser.Package p = mPackages.get(packageName);
3420            if (p != null) {
3421                final PackageSetting ps = (PackageSetting) p.mExtras;
3422                if (ps != null) {
3423                    final PackageUserState state = ps.readUserState(userId);
3424                    if (state != null) {
3425                        return PackageParser.isAvailable(state);
3426                    }
3427                }
3428            }
3429        }
3430        return false;
3431    }
3432
3433    @Override
3434    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3435        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3436                flags, userId);
3437    }
3438
3439    @Override
3440    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3441            int flags, int userId) {
3442        return getPackageInfoInternal(versionedPackage.getPackageName(),
3443                // TODO: We will change version code to long, so in the new API it is long
3444                (int) versionedPackage.getVersionCode(), flags, userId);
3445    }
3446
3447    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3448            int flags, int userId) {
3449        if (!sUserManager.exists(userId)) return null;
3450        flags = updateFlagsForPackage(flags, userId, packageName);
3451        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3452                false /* requireFullPermission */, false /* checkShell */, "get package info");
3453
3454        // reader
3455        synchronized (mPackages) {
3456            // Normalize package name to handle renamed packages and static libs
3457            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3458
3459            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3460            if (matchFactoryOnly) {
3461                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3462                if (ps != null) {
3463                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3464                        return null;
3465                    }
3466                    return generatePackageInfo(ps, flags, userId);
3467                }
3468            }
3469
3470            PackageParser.Package p = mPackages.get(packageName);
3471            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3472                return null;
3473            }
3474            if (DEBUG_PACKAGE_INFO)
3475                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3476            if (p != null) {
3477                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3478                        Binder.getCallingUid(), userId)) {
3479                    return null;
3480                }
3481                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3482            }
3483            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3484                final PackageSetting ps = mSettings.mPackages.get(packageName);
3485                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3486                    return null;
3487                }
3488                return generatePackageInfo(ps, flags, userId);
3489            }
3490        }
3491        return null;
3492    }
3493
3494
3495    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3496        // System/shell/root get to see all static libs
3497        final int appId = UserHandle.getAppId(uid);
3498        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3499                || appId == Process.ROOT_UID) {
3500            return false;
3501        }
3502
3503        // No package means no static lib as it is always on internal storage
3504        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3505            return false;
3506        }
3507
3508        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3509                ps.pkg.staticSharedLibVersion);
3510        if (libEntry == null) {
3511            return false;
3512        }
3513
3514        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3515        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3516        if (uidPackageNames == null) {
3517            return true;
3518        }
3519
3520        for (String uidPackageName : uidPackageNames) {
3521            if (ps.name.equals(uidPackageName)) {
3522                return false;
3523            }
3524            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3525            if (uidPs != null) {
3526                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3527                        libEntry.info.getName());
3528                if (index < 0) {
3529                    continue;
3530                }
3531                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3532                    return false;
3533                }
3534            }
3535        }
3536        return true;
3537    }
3538
3539    @Override
3540    public String[] currentToCanonicalPackageNames(String[] names) {
3541        String[] out = new String[names.length];
3542        // reader
3543        synchronized (mPackages) {
3544            for (int i=names.length-1; i>=0; i--) {
3545                PackageSetting ps = mSettings.mPackages.get(names[i]);
3546                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3547            }
3548        }
3549        return out;
3550    }
3551
3552    @Override
3553    public String[] canonicalToCurrentPackageNames(String[] names) {
3554        String[] out = new String[names.length];
3555        // reader
3556        synchronized (mPackages) {
3557            for (int i=names.length-1; i>=0; i--) {
3558                String cur = mSettings.getRenamedPackageLPr(names[i]);
3559                out[i] = cur != null ? cur : names[i];
3560            }
3561        }
3562        return out;
3563    }
3564
3565    @Override
3566    public int getPackageUid(String packageName, int flags, int userId) {
3567        if (!sUserManager.exists(userId)) return -1;
3568        flags = updateFlagsForPackage(flags, userId, packageName);
3569        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3570                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3571
3572        // reader
3573        synchronized (mPackages) {
3574            final PackageParser.Package p = mPackages.get(packageName);
3575            if (p != null && p.isMatch(flags)) {
3576                return UserHandle.getUid(userId, p.applicationInfo.uid);
3577            }
3578            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3579                final PackageSetting ps = mSettings.mPackages.get(packageName);
3580                if (ps != null && ps.isMatch(flags)) {
3581                    return UserHandle.getUid(userId, ps.appId);
3582                }
3583            }
3584        }
3585
3586        return -1;
3587    }
3588
3589    @Override
3590    public int[] getPackageGids(String packageName, int flags, int userId) {
3591        if (!sUserManager.exists(userId)) return null;
3592        flags = updateFlagsForPackage(flags, userId, packageName);
3593        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3594                false /* requireFullPermission */, false /* checkShell */,
3595                "getPackageGids");
3596
3597        // reader
3598        synchronized (mPackages) {
3599            final PackageParser.Package p = mPackages.get(packageName);
3600            if (p != null && p.isMatch(flags)) {
3601                PackageSetting ps = (PackageSetting) p.mExtras;
3602                // TODO: Shouldn't this be checking for package installed state for userId and
3603                // return null?
3604                return ps.getPermissionsState().computeGids(userId);
3605            }
3606            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3607                final PackageSetting ps = mSettings.mPackages.get(packageName);
3608                if (ps != null && ps.isMatch(flags)) {
3609                    return ps.getPermissionsState().computeGids(userId);
3610                }
3611            }
3612        }
3613
3614        return null;
3615    }
3616
3617    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3618        if (bp.perm != null) {
3619            return PackageParser.generatePermissionInfo(bp.perm, flags);
3620        }
3621        PermissionInfo pi = new PermissionInfo();
3622        pi.name = bp.name;
3623        pi.packageName = bp.sourcePackage;
3624        pi.nonLocalizedLabel = bp.name;
3625        pi.protectionLevel = bp.protectionLevel;
3626        return pi;
3627    }
3628
3629    @Override
3630    public PermissionInfo getPermissionInfo(String name, int flags) {
3631        // reader
3632        synchronized (mPackages) {
3633            final BasePermission p = mSettings.mPermissions.get(name);
3634            if (p != null) {
3635                return generatePermissionInfo(p, flags);
3636            }
3637            return null;
3638        }
3639    }
3640
3641    @Override
3642    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3643            int flags) {
3644        // reader
3645        synchronized (mPackages) {
3646            if (group != null && !mPermissionGroups.containsKey(group)) {
3647                // This is thrown as NameNotFoundException
3648                return null;
3649            }
3650
3651            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3652            for (BasePermission p : mSettings.mPermissions.values()) {
3653                if (group == null) {
3654                    if (p.perm == null || p.perm.info.group == null) {
3655                        out.add(generatePermissionInfo(p, flags));
3656                    }
3657                } else {
3658                    if (p.perm != null && group.equals(p.perm.info.group)) {
3659                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3660                    }
3661                }
3662            }
3663            return new ParceledListSlice<>(out);
3664        }
3665    }
3666
3667    @Override
3668    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3669        // reader
3670        synchronized (mPackages) {
3671            return PackageParser.generatePermissionGroupInfo(
3672                    mPermissionGroups.get(name), flags);
3673        }
3674    }
3675
3676    @Override
3677    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3678        // reader
3679        synchronized (mPackages) {
3680            final int N = mPermissionGroups.size();
3681            ArrayList<PermissionGroupInfo> out
3682                    = new ArrayList<PermissionGroupInfo>(N);
3683            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3684                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3685            }
3686            return new ParceledListSlice<>(out);
3687        }
3688    }
3689
3690    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3691            int uid, int userId) {
3692        if (!sUserManager.exists(userId)) return null;
3693        PackageSetting ps = mSettings.mPackages.get(packageName);
3694        if (ps != null) {
3695            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3696                return null;
3697            }
3698            if (ps.pkg == null) {
3699                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3700                if (pInfo != null) {
3701                    return pInfo.applicationInfo;
3702                }
3703                return null;
3704            }
3705            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3706                    ps.readUserState(userId), userId);
3707            if (ai != null) {
3708                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3709            }
3710            return ai;
3711        }
3712        return null;
3713    }
3714
3715    @Override
3716    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3717        if (!sUserManager.exists(userId)) return null;
3718        flags = updateFlagsForApplication(flags, userId, packageName);
3719        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3720                false /* requireFullPermission */, false /* checkShell */, "get application info");
3721
3722        // writer
3723        synchronized (mPackages) {
3724            // Normalize package name to handle renamed packages and static libs
3725            packageName = resolveInternalPackageNameLPr(packageName,
3726                    PackageManager.VERSION_CODE_HIGHEST);
3727
3728            PackageParser.Package p = mPackages.get(packageName);
3729            if (DEBUG_PACKAGE_INFO) Log.v(
3730                    TAG, "getApplicationInfo " + packageName
3731                    + ": " + p);
3732            if (p != null) {
3733                PackageSetting ps = mSettings.mPackages.get(packageName);
3734                if (ps == null) return null;
3735                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3736                    return null;
3737                }
3738                // Note: isEnabledLP() does not apply here - always return info
3739                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3740                        p, flags, ps.readUserState(userId), userId);
3741                if (ai != null) {
3742                    ai.packageName = resolveExternalPackageNameLPr(p);
3743                }
3744                return ai;
3745            }
3746            if ("android".equals(packageName)||"system".equals(packageName)) {
3747                return mAndroidApplication;
3748            }
3749            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3750                // Already generates the external package name
3751                return generateApplicationInfoFromSettingsLPw(packageName,
3752                        Binder.getCallingUid(), flags, userId);
3753            }
3754        }
3755        return null;
3756    }
3757
3758    private String normalizePackageNameLPr(String packageName) {
3759        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3760        return normalizedPackageName != null ? normalizedPackageName : packageName;
3761    }
3762
3763    @Override
3764    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3765            final IPackageDataObserver observer) {
3766        mContext.enforceCallingOrSelfPermission(
3767                android.Manifest.permission.CLEAR_APP_CACHE, null);
3768        // Queue up an async operation since clearing cache may take a little while.
3769        mHandler.post(new Runnable() {
3770            public void run() {
3771                mHandler.removeCallbacks(this);
3772                boolean success = true;
3773                synchronized (mInstallLock) {
3774                    try {
3775                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3776                    } catch (InstallerException e) {
3777                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3778                        success = false;
3779                    }
3780                }
3781                if (observer != null) {
3782                    try {
3783                        observer.onRemoveCompleted(null, success);
3784                    } catch (RemoteException e) {
3785                        Slog.w(TAG, "RemoveException when invoking call back");
3786                    }
3787                }
3788            }
3789        });
3790    }
3791
3792    @Override
3793    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3794            final IntentSender pi) {
3795        mContext.enforceCallingOrSelfPermission(
3796                android.Manifest.permission.CLEAR_APP_CACHE, null);
3797        // Queue up an async operation since clearing cache may take a little while.
3798        mHandler.post(new Runnable() {
3799            public void run() {
3800                mHandler.removeCallbacks(this);
3801                boolean success = true;
3802                synchronized (mInstallLock) {
3803                    try {
3804                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3805                    } catch (InstallerException e) {
3806                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3807                        success = false;
3808                    }
3809                }
3810                if(pi != null) {
3811                    try {
3812                        // Callback via pending intent
3813                        int code = success ? 1 : 0;
3814                        pi.sendIntent(null, code, null,
3815                                null, null);
3816                    } catch (SendIntentException e1) {
3817                        Slog.i(TAG, "Failed to send pending intent");
3818                    }
3819                }
3820            }
3821        });
3822    }
3823
3824    public void freeStorage(String volumeUuid, long freeStorageSize, int storageFlags)
3825            throws IOException {
3826        synchronized (mInstallLock) {
3827            try {
3828                mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3829            } catch (InstallerException e) {
3830                throw new IOException("Failed to free enough space", e);
3831            }
3832        }
3833    }
3834
3835    /**
3836     * Update given flags based on encryption status of current user.
3837     */
3838    private int updateFlags(int flags, int userId) {
3839        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3840                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3841            // Caller expressed an explicit opinion about what encryption
3842            // aware/unaware components they want to see, so fall through and
3843            // give them what they want
3844        } else {
3845            // Caller expressed no opinion, so match based on user state
3846            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3847                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3848            } else {
3849                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3850            }
3851        }
3852        return flags;
3853    }
3854
3855    private UserManagerInternal getUserManagerInternal() {
3856        if (mUserManagerInternal == null) {
3857            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3858        }
3859        return mUserManagerInternal;
3860    }
3861
3862    private DeviceIdleController.LocalService getDeviceIdleController() {
3863        if (mDeviceIdleController == null) {
3864            mDeviceIdleController =
3865                    LocalServices.getService(DeviceIdleController.LocalService.class);
3866        }
3867        return mDeviceIdleController;
3868    }
3869
3870    /**
3871     * Update given flags when being used to request {@link PackageInfo}.
3872     */
3873    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3874        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3875        boolean triaged = true;
3876        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3877                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3878            // Caller is asking for component details, so they'd better be
3879            // asking for specific encryption matching behavior, or be triaged
3880            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3881                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3882                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3883                triaged = false;
3884            }
3885        }
3886        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3887                | PackageManager.MATCH_SYSTEM_ONLY
3888                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3889            triaged = false;
3890        }
3891        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3892            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3893                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3894                    + Debug.getCallers(5));
3895        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3896                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3897            // If the caller wants all packages and has a restricted profile associated with it,
3898            // then match all users. This is to make sure that launchers that need to access work
3899            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3900            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3901            flags |= PackageManager.MATCH_ANY_USER;
3902        }
3903        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3904            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3905                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3906        }
3907        return updateFlags(flags, userId);
3908    }
3909
3910    /**
3911     * Update given flags when being used to request {@link ApplicationInfo}.
3912     */
3913    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3914        return updateFlagsForPackage(flags, userId, cookie);
3915    }
3916
3917    /**
3918     * Update given flags when being used to request {@link ComponentInfo}.
3919     */
3920    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3921        if (cookie instanceof Intent) {
3922            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3923                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3924            }
3925        }
3926
3927        boolean triaged = true;
3928        // Caller is asking for component details, so they'd better be
3929        // asking for specific encryption matching behavior, or be triaged
3930        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3931                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3932                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3933            triaged = false;
3934        }
3935        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3936            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3937                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3938        }
3939
3940        return updateFlags(flags, userId);
3941    }
3942
3943    /**
3944     * Update given intent when being used to request {@link ResolveInfo}.
3945     */
3946    private Intent updateIntentForResolve(Intent intent) {
3947        if (intent.getSelector() != null) {
3948            intent = intent.getSelector();
3949        }
3950        if (DEBUG_PREFERRED) {
3951            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3952        }
3953        return intent;
3954    }
3955
3956    /**
3957     * Update given flags when being used to request {@link ResolveInfo}.
3958     */
3959    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3960        // Safe mode means we shouldn't match any third-party components
3961        if (mSafeMode) {
3962            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3963        }
3964        final int callingUid = Binder.getCallingUid();
3965        if (getInstantAppPackageName(callingUid) != null) {
3966            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
3967            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
3968            flags |= PackageManager.MATCH_INSTANT;
3969        } else {
3970            // Otherwise, prevent leaking ephemeral components
3971            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
3972            if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3973                // Unless called from the system process
3974                flags &= ~PackageManager.MATCH_INSTANT;
3975            }
3976        }
3977        return updateFlagsForComponent(flags, userId, cookie);
3978    }
3979
3980    @Override
3981    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3982        if (!sUserManager.exists(userId)) return null;
3983        flags = updateFlagsForComponent(flags, userId, component);
3984        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3985                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3986        synchronized (mPackages) {
3987            PackageParser.Activity a = mActivities.mActivities.get(component);
3988
3989            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3990            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3991                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3992                if (ps == null) return null;
3993                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3994                        userId);
3995            }
3996            if (mResolveComponentName.equals(component)) {
3997                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3998                        new PackageUserState(), userId);
3999            }
4000        }
4001        return null;
4002    }
4003
4004    @Override
4005    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4006            String resolvedType) {
4007        synchronized (mPackages) {
4008            if (component.equals(mResolveComponentName)) {
4009                // The resolver supports EVERYTHING!
4010                return true;
4011            }
4012            PackageParser.Activity a = mActivities.mActivities.get(component);
4013            if (a == null) {
4014                return false;
4015            }
4016            for (int i=0; i<a.intents.size(); i++) {
4017                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4018                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4019                    return true;
4020                }
4021            }
4022            return false;
4023        }
4024    }
4025
4026    @Override
4027    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4028        if (!sUserManager.exists(userId)) return null;
4029        flags = updateFlagsForComponent(flags, userId, component);
4030        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4031                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4032        synchronized (mPackages) {
4033            PackageParser.Activity a = mReceivers.mActivities.get(component);
4034            if (DEBUG_PACKAGE_INFO) Log.v(
4035                TAG, "getReceiverInfo " + component + ": " + a);
4036            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4037                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4038                if (ps == null) return null;
4039                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4040                        userId);
4041            }
4042        }
4043        return null;
4044    }
4045
4046    @Override
4047    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4048        if (!sUserManager.exists(userId)) return null;
4049        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4050
4051        flags = updateFlagsForPackage(flags, userId, null);
4052
4053        final boolean canSeeStaticLibraries =
4054                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4055                        == PERMISSION_GRANTED
4056                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4057                        == PERMISSION_GRANTED
4058                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4059                        == PERMISSION_GRANTED
4060                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4061                        == PERMISSION_GRANTED;
4062
4063        synchronized (mPackages) {
4064            List<SharedLibraryInfo> result = null;
4065
4066            final int libCount = mSharedLibraries.size();
4067            for (int i = 0; i < libCount; i++) {
4068                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4069                if (versionedLib == null) {
4070                    continue;
4071                }
4072
4073                final int versionCount = versionedLib.size();
4074                for (int j = 0; j < versionCount; j++) {
4075                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4076                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4077                        break;
4078                    }
4079                    final long identity = Binder.clearCallingIdentity();
4080                    try {
4081                        // TODO: We will change version code to long, so in the new API it is long
4082                        PackageInfo packageInfo = getPackageInfoVersioned(
4083                                libInfo.getDeclaringPackage(), flags, userId);
4084                        if (packageInfo == null) {
4085                            continue;
4086                        }
4087                    } finally {
4088                        Binder.restoreCallingIdentity(identity);
4089                    }
4090
4091                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4092                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4093                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4094
4095                    if (result == null) {
4096                        result = new ArrayList<>();
4097                    }
4098                    result.add(resLibInfo);
4099                }
4100            }
4101
4102            return result != null ? new ParceledListSlice<>(result) : null;
4103        }
4104    }
4105
4106    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4107            SharedLibraryInfo libInfo, int flags, int userId) {
4108        List<VersionedPackage> versionedPackages = null;
4109        final int packageCount = mSettings.mPackages.size();
4110        for (int i = 0; i < packageCount; i++) {
4111            PackageSetting ps = mSettings.mPackages.valueAt(i);
4112
4113            if (ps == null) {
4114                continue;
4115            }
4116
4117            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4118                continue;
4119            }
4120
4121            final String libName = libInfo.getName();
4122            if (libInfo.isStatic()) {
4123                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4124                if (libIdx < 0) {
4125                    continue;
4126                }
4127                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4128                    continue;
4129                }
4130                if (versionedPackages == null) {
4131                    versionedPackages = new ArrayList<>();
4132                }
4133                // If the dependent is a static shared lib, use the public package name
4134                String dependentPackageName = ps.name;
4135                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4136                    dependentPackageName = ps.pkg.manifestPackageName;
4137                }
4138                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4139            } else if (ps.pkg != null) {
4140                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4141                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4142                    if (versionedPackages == null) {
4143                        versionedPackages = new ArrayList<>();
4144                    }
4145                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4146                }
4147            }
4148        }
4149
4150        return versionedPackages;
4151    }
4152
4153    @Override
4154    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4155        if (!sUserManager.exists(userId)) return null;
4156        flags = updateFlagsForComponent(flags, userId, component);
4157        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4158                false /* requireFullPermission */, false /* checkShell */, "get service info");
4159        synchronized (mPackages) {
4160            PackageParser.Service s = mServices.mServices.get(component);
4161            if (DEBUG_PACKAGE_INFO) Log.v(
4162                TAG, "getServiceInfo " + component + ": " + s);
4163            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4164                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4165                if (ps == null) return null;
4166                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
4167                        userId);
4168            }
4169        }
4170        return null;
4171    }
4172
4173    @Override
4174    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4175        if (!sUserManager.exists(userId)) return null;
4176        flags = updateFlagsForComponent(flags, userId, component);
4177        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4178                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4179        synchronized (mPackages) {
4180            PackageParser.Provider p = mProviders.mProviders.get(component);
4181            if (DEBUG_PACKAGE_INFO) Log.v(
4182                TAG, "getProviderInfo " + component + ": " + p);
4183            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4184                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4185                if (ps == null) return null;
4186                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
4187                        userId);
4188            }
4189        }
4190        return null;
4191    }
4192
4193    @Override
4194    public String[] getSystemSharedLibraryNames() {
4195        synchronized (mPackages) {
4196            Set<String> libs = null;
4197            final int libCount = mSharedLibraries.size();
4198            for (int i = 0; i < libCount; i++) {
4199                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4200                if (versionedLib == null) {
4201                    continue;
4202                }
4203                final int versionCount = versionedLib.size();
4204                for (int j = 0; j < versionCount; j++) {
4205                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4206                    if (!libEntry.info.isStatic()) {
4207                        if (libs == null) {
4208                            libs = new ArraySet<>();
4209                        }
4210                        libs.add(libEntry.info.getName());
4211                        break;
4212                    }
4213                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4214                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4215                            UserHandle.getUserId(Binder.getCallingUid()))) {
4216                        if (libs == null) {
4217                            libs = new ArraySet<>();
4218                        }
4219                        libs.add(libEntry.info.getName());
4220                        break;
4221                    }
4222                }
4223            }
4224
4225            if (libs != null) {
4226                String[] libsArray = new String[libs.size()];
4227                libs.toArray(libsArray);
4228                return libsArray;
4229            }
4230
4231            return null;
4232        }
4233    }
4234
4235    @Override
4236    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4237        synchronized (mPackages) {
4238            return mServicesSystemSharedLibraryPackageName;
4239        }
4240    }
4241
4242    @Override
4243    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4244        synchronized (mPackages) {
4245            return mSharedSystemSharedLibraryPackageName;
4246        }
4247    }
4248
4249    private void updateSequenceNumberLP(String packageName, int[] userList) {
4250        for (int i = userList.length - 1; i >= 0; --i) {
4251            final int userId = userList[i];
4252            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4253            if (changedPackages == null) {
4254                changedPackages = new SparseArray<>();
4255                mChangedPackages.put(userId, changedPackages);
4256            }
4257            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4258            if (sequenceNumbers == null) {
4259                sequenceNumbers = new HashMap<>();
4260                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4261            }
4262            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4263            if (sequenceNumber != null) {
4264                changedPackages.remove(sequenceNumber);
4265            }
4266            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4267            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4268        }
4269        mChangedPackagesSequenceNumber++;
4270    }
4271
4272    @Override
4273    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4274        synchronized (mPackages) {
4275            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4276                return null;
4277            }
4278            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4279            if (changedPackages == null) {
4280                return null;
4281            }
4282            final List<String> packageNames =
4283                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4284            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4285                final String packageName = changedPackages.get(i);
4286                if (packageName != null) {
4287                    packageNames.add(packageName);
4288                }
4289            }
4290            return packageNames.isEmpty()
4291                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4292        }
4293    }
4294
4295    @Override
4296    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4297        ArrayList<FeatureInfo> res;
4298        synchronized (mAvailableFeatures) {
4299            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4300            res.addAll(mAvailableFeatures.values());
4301        }
4302        final FeatureInfo fi = new FeatureInfo();
4303        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4304                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4305        res.add(fi);
4306
4307        return new ParceledListSlice<>(res);
4308    }
4309
4310    @Override
4311    public boolean hasSystemFeature(String name, int version) {
4312        synchronized (mAvailableFeatures) {
4313            final FeatureInfo feat = mAvailableFeatures.get(name);
4314            if (feat == null) {
4315                return false;
4316            } else {
4317                return feat.version >= version;
4318            }
4319        }
4320    }
4321
4322    @Override
4323    public int checkPermission(String permName, String pkgName, int userId) {
4324        if (!sUserManager.exists(userId)) {
4325            return PackageManager.PERMISSION_DENIED;
4326        }
4327
4328        synchronized (mPackages) {
4329            final PackageParser.Package p = mPackages.get(pkgName);
4330            if (p != null && p.mExtras != null) {
4331                final PackageSetting ps = (PackageSetting) p.mExtras;
4332                final PermissionsState permissionsState = ps.getPermissionsState();
4333                if (permissionsState.hasPermission(permName, userId)) {
4334                    return PackageManager.PERMISSION_GRANTED;
4335                }
4336                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4337                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4338                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4339                    return PackageManager.PERMISSION_GRANTED;
4340                }
4341            }
4342        }
4343
4344        return PackageManager.PERMISSION_DENIED;
4345    }
4346
4347    @Override
4348    public int checkUidPermission(String permName, int uid) {
4349        final int userId = UserHandle.getUserId(uid);
4350
4351        if (!sUserManager.exists(userId)) {
4352            return PackageManager.PERMISSION_DENIED;
4353        }
4354
4355        synchronized (mPackages) {
4356            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4357            if (obj != null) {
4358                final SettingBase ps = (SettingBase) obj;
4359                final PermissionsState permissionsState = ps.getPermissionsState();
4360                if (permissionsState.hasPermission(permName, userId)) {
4361                    return PackageManager.PERMISSION_GRANTED;
4362                }
4363                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4364                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4365                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4366                    return PackageManager.PERMISSION_GRANTED;
4367                }
4368            } else {
4369                ArraySet<String> perms = mSystemPermissions.get(uid);
4370                if (perms != null) {
4371                    if (perms.contains(permName)) {
4372                        return PackageManager.PERMISSION_GRANTED;
4373                    }
4374                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4375                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4376                        return PackageManager.PERMISSION_GRANTED;
4377                    }
4378                }
4379            }
4380        }
4381
4382        return PackageManager.PERMISSION_DENIED;
4383    }
4384
4385    @Override
4386    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4387        if (UserHandle.getCallingUserId() != userId) {
4388            mContext.enforceCallingPermission(
4389                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4390                    "isPermissionRevokedByPolicy for user " + userId);
4391        }
4392
4393        if (checkPermission(permission, packageName, userId)
4394                == PackageManager.PERMISSION_GRANTED) {
4395            return false;
4396        }
4397
4398        final long identity = Binder.clearCallingIdentity();
4399        try {
4400            final int flags = getPermissionFlags(permission, packageName, userId);
4401            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4402        } finally {
4403            Binder.restoreCallingIdentity(identity);
4404        }
4405    }
4406
4407    @Override
4408    public String getPermissionControllerPackageName() {
4409        synchronized (mPackages) {
4410            return mRequiredInstallerPackage;
4411        }
4412    }
4413
4414    /**
4415     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4416     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4417     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4418     * @param message the message to log on security exception
4419     */
4420    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4421            boolean checkShell, String message) {
4422        if (userId < 0) {
4423            throw new IllegalArgumentException("Invalid userId " + userId);
4424        }
4425        if (checkShell) {
4426            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4427        }
4428        if (userId == UserHandle.getUserId(callingUid)) return;
4429        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4430            if (requireFullPermission) {
4431                mContext.enforceCallingOrSelfPermission(
4432                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4433            } else {
4434                try {
4435                    mContext.enforceCallingOrSelfPermission(
4436                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4437                } catch (SecurityException se) {
4438                    mContext.enforceCallingOrSelfPermission(
4439                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4440                }
4441            }
4442        }
4443    }
4444
4445    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4446        if (callingUid == Process.SHELL_UID) {
4447            if (userHandle >= 0
4448                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4449                throw new SecurityException("Shell does not have permission to access user "
4450                        + userHandle);
4451            } else if (userHandle < 0) {
4452                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4453                        + Debug.getCallers(3));
4454            }
4455        }
4456    }
4457
4458    private BasePermission findPermissionTreeLP(String permName) {
4459        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4460            if (permName.startsWith(bp.name) &&
4461                    permName.length() > bp.name.length() &&
4462                    permName.charAt(bp.name.length()) == '.') {
4463                return bp;
4464            }
4465        }
4466        return null;
4467    }
4468
4469    private BasePermission checkPermissionTreeLP(String permName) {
4470        if (permName != null) {
4471            BasePermission bp = findPermissionTreeLP(permName);
4472            if (bp != null) {
4473                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4474                    return bp;
4475                }
4476                throw new SecurityException("Calling uid "
4477                        + Binder.getCallingUid()
4478                        + " is not allowed to add to permission tree "
4479                        + bp.name + " owned by uid " + bp.uid);
4480            }
4481        }
4482        throw new SecurityException("No permission tree found for " + permName);
4483    }
4484
4485    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4486        if (s1 == null) {
4487            return s2 == null;
4488        }
4489        if (s2 == null) {
4490            return false;
4491        }
4492        if (s1.getClass() != s2.getClass()) {
4493            return false;
4494        }
4495        return s1.equals(s2);
4496    }
4497
4498    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4499        if (pi1.icon != pi2.icon) return false;
4500        if (pi1.logo != pi2.logo) return false;
4501        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4502        if (!compareStrings(pi1.name, pi2.name)) return false;
4503        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4504        // We'll take care of setting this one.
4505        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4506        // These are not currently stored in settings.
4507        //if (!compareStrings(pi1.group, pi2.group)) return false;
4508        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4509        //if (pi1.labelRes != pi2.labelRes) return false;
4510        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4511        return true;
4512    }
4513
4514    int permissionInfoFootprint(PermissionInfo info) {
4515        int size = info.name.length();
4516        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4517        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4518        return size;
4519    }
4520
4521    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4522        int size = 0;
4523        for (BasePermission perm : mSettings.mPermissions.values()) {
4524            if (perm.uid == tree.uid) {
4525                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4526            }
4527        }
4528        return size;
4529    }
4530
4531    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4532        // We calculate the max size of permissions defined by this uid and throw
4533        // if that plus the size of 'info' would exceed our stated maximum.
4534        if (tree.uid != Process.SYSTEM_UID) {
4535            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4536            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4537                throw new SecurityException("Permission tree size cap exceeded");
4538            }
4539        }
4540    }
4541
4542    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4543        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4544            throw new SecurityException("Label must be specified in permission");
4545        }
4546        BasePermission tree = checkPermissionTreeLP(info.name);
4547        BasePermission bp = mSettings.mPermissions.get(info.name);
4548        boolean added = bp == null;
4549        boolean changed = true;
4550        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4551        if (added) {
4552            enforcePermissionCapLocked(info, tree);
4553            bp = new BasePermission(info.name, tree.sourcePackage,
4554                    BasePermission.TYPE_DYNAMIC);
4555        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4556            throw new SecurityException(
4557                    "Not allowed to modify non-dynamic permission "
4558                    + info.name);
4559        } else {
4560            if (bp.protectionLevel == fixedLevel
4561                    && bp.perm.owner.equals(tree.perm.owner)
4562                    && bp.uid == tree.uid
4563                    && comparePermissionInfos(bp.perm.info, info)) {
4564                changed = false;
4565            }
4566        }
4567        bp.protectionLevel = fixedLevel;
4568        info = new PermissionInfo(info);
4569        info.protectionLevel = fixedLevel;
4570        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4571        bp.perm.info.packageName = tree.perm.info.packageName;
4572        bp.uid = tree.uid;
4573        if (added) {
4574            mSettings.mPermissions.put(info.name, bp);
4575        }
4576        if (changed) {
4577            if (!async) {
4578                mSettings.writeLPr();
4579            } else {
4580                scheduleWriteSettingsLocked();
4581            }
4582        }
4583        return added;
4584    }
4585
4586    @Override
4587    public boolean addPermission(PermissionInfo info) {
4588        synchronized (mPackages) {
4589            return addPermissionLocked(info, false);
4590        }
4591    }
4592
4593    @Override
4594    public boolean addPermissionAsync(PermissionInfo info) {
4595        synchronized (mPackages) {
4596            return addPermissionLocked(info, true);
4597        }
4598    }
4599
4600    @Override
4601    public void removePermission(String name) {
4602        synchronized (mPackages) {
4603            checkPermissionTreeLP(name);
4604            BasePermission bp = mSettings.mPermissions.get(name);
4605            if (bp != null) {
4606                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4607                    throw new SecurityException(
4608                            "Not allowed to modify non-dynamic permission "
4609                            + name);
4610                }
4611                mSettings.mPermissions.remove(name);
4612                mSettings.writeLPr();
4613            }
4614        }
4615    }
4616
4617    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4618            BasePermission bp) {
4619        int index = pkg.requestedPermissions.indexOf(bp.name);
4620        if (index == -1) {
4621            throw new SecurityException("Package " + pkg.packageName
4622                    + " has not requested permission " + bp.name);
4623        }
4624        if (!bp.isRuntime() && !bp.isDevelopment()) {
4625            throw new SecurityException("Permission " + bp.name
4626                    + " is not a changeable permission type");
4627        }
4628    }
4629
4630    @Override
4631    public void grantRuntimePermission(String packageName, String name, final int userId) {
4632        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4633    }
4634
4635    private void grantRuntimePermission(String packageName, String name, final int userId,
4636            boolean overridePolicy) {
4637        if (!sUserManager.exists(userId)) {
4638            Log.e(TAG, "No such user:" + userId);
4639            return;
4640        }
4641
4642        mContext.enforceCallingOrSelfPermission(
4643                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4644                "grantRuntimePermission");
4645
4646        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4647                true /* requireFullPermission */, true /* checkShell */,
4648                "grantRuntimePermission");
4649
4650        final int uid;
4651        final SettingBase sb;
4652
4653        synchronized (mPackages) {
4654            final PackageParser.Package pkg = mPackages.get(packageName);
4655            if (pkg == null) {
4656                throw new IllegalArgumentException("Unknown package: " + packageName);
4657            }
4658
4659            final BasePermission bp = mSettings.mPermissions.get(name);
4660            if (bp == null) {
4661                throw new IllegalArgumentException("Unknown permission: " + name);
4662            }
4663
4664            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4665
4666            // If a permission review is required for legacy apps we represent
4667            // their permissions as always granted runtime ones since we need
4668            // to keep the review required permission flag per user while an
4669            // install permission's state is shared across all users.
4670            if (mPermissionReviewRequired
4671                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4672                    && bp.isRuntime()) {
4673                return;
4674            }
4675
4676            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4677            sb = (SettingBase) pkg.mExtras;
4678            if (sb == null) {
4679                throw new IllegalArgumentException("Unknown package: " + packageName);
4680            }
4681
4682            final PermissionsState permissionsState = sb.getPermissionsState();
4683
4684            final int flags = permissionsState.getPermissionFlags(name, userId);
4685            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4686                throw new SecurityException("Cannot grant system fixed permission "
4687                        + name + " for package " + packageName);
4688            }
4689            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4690                throw new SecurityException("Cannot grant policy fixed permission "
4691                        + name + " for package " + packageName);
4692            }
4693
4694            if (bp.isDevelopment()) {
4695                // Development permissions must be handled specially, since they are not
4696                // normal runtime permissions.  For now they apply to all users.
4697                if (permissionsState.grantInstallPermission(bp) !=
4698                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4699                    scheduleWriteSettingsLocked();
4700                }
4701                return;
4702            }
4703
4704            final PackageSetting ps = mSettings.mPackages.get(packageName);
4705            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4706                throw new SecurityException("Cannot grant non-ephemeral permission"
4707                        + name + " for package " + packageName);
4708            }
4709
4710            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4711                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4712                return;
4713            }
4714
4715            final int result = permissionsState.grantRuntimePermission(bp, userId);
4716            switch (result) {
4717                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4718                    return;
4719                }
4720
4721                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4722                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4723                    mHandler.post(new Runnable() {
4724                        @Override
4725                        public void run() {
4726                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4727                        }
4728                    });
4729                }
4730                break;
4731            }
4732
4733            if (bp.isRuntime()) {
4734                logPermissionGranted(mContext, name, packageName);
4735            }
4736
4737            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4738
4739            // Not critical if that is lost - app has to request again.
4740            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4741        }
4742
4743        // Only need to do this if user is initialized. Otherwise it's a new user
4744        // and there are no processes running as the user yet and there's no need
4745        // to make an expensive call to remount processes for the changed permissions.
4746        if (READ_EXTERNAL_STORAGE.equals(name)
4747                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4748            final long token = Binder.clearCallingIdentity();
4749            try {
4750                if (sUserManager.isInitialized(userId)) {
4751                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4752                            StorageManagerInternal.class);
4753                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4754                }
4755            } finally {
4756                Binder.restoreCallingIdentity(token);
4757            }
4758        }
4759    }
4760
4761    @Override
4762    public void revokeRuntimePermission(String packageName, String name, int userId) {
4763        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4764    }
4765
4766    private void revokeRuntimePermission(String packageName, String name, int userId,
4767            boolean overridePolicy) {
4768        if (!sUserManager.exists(userId)) {
4769            Log.e(TAG, "No such user:" + userId);
4770            return;
4771        }
4772
4773        mContext.enforceCallingOrSelfPermission(
4774                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4775                "revokeRuntimePermission");
4776
4777        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4778                true /* requireFullPermission */, true /* checkShell */,
4779                "revokeRuntimePermission");
4780
4781        final int appId;
4782
4783        synchronized (mPackages) {
4784            final PackageParser.Package pkg = mPackages.get(packageName);
4785            if (pkg == null) {
4786                throw new IllegalArgumentException("Unknown package: " + packageName);
4787            }
4788
4789            final BasePermission bp = mSettings.mPermissions.get(name);
4790            if (bp == null) {
4791                throw new IllegalArgumentException("Unknown permission: " + name);
4792            }
4793
4794            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4795
4796            // If a permission review is required for legacy apps we represent
4797            // their permissions as always granted runtime ones since we need
4798            // to keep the review required permission flag per user while an
4799            // install permission's state is shared across all users.
4800            if (mPermissionReviewRequired
4801                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4802                    && bp.isRuntime()) {
4803                return;
4804            }
4805
4806            SettingBase sb = (SettingBase) pkg.mExtras;
4807            if (sb == null) {
4808                throw new IllegalArgumentException("Unknown package: " + packageName);
4809            }
4810
4811            final PermissionsState permissionsState = sb.getPermissionsState();
4812
4813            final int flags = permissionsState.getPermissionFlags(name, userId);
4814            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4815                throw new SecurityException("Cannot revoke system fixed permission "
4816                        + name + " for package " + packageName);
4817            }
4818            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4819                throw new SecurityException("Cannot revoke policy fixed permission "
4820                        + name + " for package " + packageName);
4821            }
4822
4823            if (bp.isDevelopment()) {
4824                // Development permissions must be handled specially, since they are not
4825                // normal runtime permissions.  For now they apply to all users.
4826                if (permissionsState.revokeInstallPermission(bp) !=
4827                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4828                    scheduleWriteSettingsLocked();
4829                }
4830                return;
4831            }
4832
4833            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4834                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4835                return;
4836            }
4837
4838            if (bp.isRuntime()) {
4839                logPermissionRevoked(mContext, name, packageName);
4840            }
4841
4842            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4843
4844            // Critical, after this call app should never have the permission.
4845            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4846
4847            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4848        }
4849
4850        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4851    }
4852
4853    /**
4854     * Get the first event id for the permission.
4855     *
4856     * <p>There are four events for each permission: <ul>
4857     *     <li>Request permission: first id + 0</li>
4858     *     <li>Grant permission: first id + 1</li>
4859     *     <li>Request for permission denied: first id + 2</li>
4860     *     <li>Revoke permission: first id + 3</li>
4861     * </ul></p>
4862     *
4863     * @param name name of the permission
4864     *
4865     * @return The first event id for the permission
4866     */
4867    private static int getBaseEventId(@NonNull String name) {
4868        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4869
4870        if (eventIdIndex == -1) {
4871            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4872                    || "user".equals(Build.TYPE)) {
4873                Log.i(TAG, "Unknown permission " + name);
4874
4875                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4876            } else {
4877                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4878                //
4879                // Also update
4880                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4881                // - metrics_constants.proto
4882                throw new IllegalStateException("Unknown permission " + name);
4883            }
4884        }
4885
4886        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4887    }
4888
4889    /**
4890     * Log that a permission was revoked.
4891     *
4892     * @param context Context of the caller
4893     * @param name name of the permission
4894     * @param packageName package permission if for
4895     */
4896    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4897            @NonNull String packageName) {
4898        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4899    }
4900
4901    /**
4902     * Log that a permission request was granted.
4903     *
4904     * @param context Context of the caller
4905     * @param name name of the permission
4906     * @param packageName package permission if for
4907     */
4908    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4909            @NonNull String packageName) {
4910        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4911    }
4912
4913    @Override
4914    public void resetRuntimePermissions() {
4915        mContext.enforceCallingOrSelfPermission(
4916                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4917                "revokeRuntimePermission");
4918
4919        int callingUid = Binder.getCallingUid();
4920        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4921            mContext.enforceCallingOrSelfPermission(
4922                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4923                    "resetRuntimePermissions");
4924        }
4925
4926        synchronized (mPackages) {
4927            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4928            for (int userId : UserManagerService.getInstance().getUserIds()) {
4929                final int packageCount = mPackages.size();
4930                for (int i = 0; i < packageCount; i++) {
4931                    PackageParser.Package pkg = mPackages.valueAt(i);
4932                    if (!(pkg.mExtras instanceof PackageSetting)) {
4933                        continue;
4934                    }
4935                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4936                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4937                }
4938            }
4939        }
4940    }
4941
4942    @Override
4943    public int getPermissionFlags(String name, String packageName, int userId) {
4944        if (!sUserManager.exists(userId)) {
4945            return 0;
4946        }
4947
4948        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4949
4950        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4951                true /* requireFullPermission */, false /* checkShell */,
4952                "getPermissionFlags");
4953
4954        synchronized (mPackages) {
4955            final PackageParser.Package pkg = mPackages.get(packageName);
4956            if (pkg == null) {
4957                return 0;
4958            }
4959
4960            final BasePermission bp = mSettings.mPermissions.get(name);
4961            if (bp == null) {
4962                return 0;
4963            }
4964
4965            SettingBase sb = (SettingBase) pkg.mExtras;
4966            if (sb == null) {
4967                return 0;
4968            }
4969
4970            PermissionsState permissionsState = sb.getPermissionsState();
4971            return permissionsState.getPermissionFlags(name, userId);
4972        }
4973    }
4974
4975    @Override
4976    public void updatePermissionFlags(String name, String packageName, int flagMask,
4977            int flagValues, int userId) {
4978        if (!sUserManager.exists(userId)) {
4979            return;
4980        }
4981
4982        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4983
4984        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4985                true /* requireFullPermission */, true /* checkShell */,
4986                "updatePermissionFlags");
4987
4988        // Only the system can change these flags and nothing else.
4989        if (getCallingUid() != Process.SYSTEM_UID) {
4990            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4991            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4992            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4993            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4994            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4995        }
4996
4997        synchronized (mPackages) {
4998            final PackageParser.Package pkg = mPackages.get(packageName);
4999            if (pkg == null) {
5000                throw new IllegalArgumentException("Unknown package: " + packageName);
5001            }
5002
5003            final BasePermission bp = mSettings.mPermissions.get(name);
5004            if (bp == null) {
5005                throw new IllegalArgumentException("Unknown permission: " + name);
5006            }
5007
5008            SettingBase sb = (SettingBase) pkg.mExtras;
5009            if (sb == null) {
5010                throw new IllegalArgumentException("Unknown package: " + packageName);
5011            }
5012
5013            PermissionsState permissionsState = sb.getPermissionsState();
5014
5015            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5016
5017            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5018                // Install and runtime permissions are stored in different places,
5019                // so figure out what permission changed and persist the change.
5020                if (permissionsState.getInstallPermissionState(name) != null) {
5021                    scheduleWriteSettingsLocked();
5022                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5023                        || hadState) {
5024                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5025                }
5026            }
5027        }
5028    }
5029
5030    /**
5031     * Update the permission flags for all packages and runtime permissions of a user in order
5032     * to allow device or profile owner to remove POLICY_FIXED.
5033     */
5034    @Override
5035    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5036        if (!sUserManager.exists(userId)) {
5037            return;
5038        }
5039
5040        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5041
5042        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5043                true /* requireFullPermission */, true /* checkShell */,
5044                "updatePermissionFlagsForAllApps");
5045
5046        // Only the system can change system fixed flags.
5047        if (getCallingUid() != Process.SYSTEM_UID) {
5048            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5049            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5050        }
5051
5052        synchronized (mPackages) {
5053            boolean changed = false;
5054            final int packageCount = mPackages.size();
5055            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5056                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5057                SettingBase sb = (SettingBase) pkg.mExtras;
5058                if (sb == null) {
5059                    continue;
5060                }
5061                PermissionsState permissionsState = sb.getPermissionsState();
5062                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5063                        userId, flagMask, flagValues);
5064            }
5065            if (changed) {
5066                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5067            }
5068        }
5069    }
5070
5071    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5072        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5073                != PackageManager.PERMISSION_GRANTED
5074            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5075                != PackageManager.PERMISSION_GRANTED) {
5076            throw new SecurityException(message + " requires "
5077                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5078                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5079        }
5080    }
5081
5082    @Override
5083    public boolean shouldShowRequestPermissionRationale(String permissionName,
5084            String packageName, int userId) {
5085        if (UserHandle.getCallingUserId() != userId) {
5086            mContext.enforceCallingPermission(
5087                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5088                    "canShowRequestPermissionRationale for user " + userId);
5089        }
5090
5091        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5092        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5093            return false;
5094        }
5095
5096        if (checkPermission(permissionName, packageName, userId)
5097                == PackageManager.PERMISSION_GRANTED) {
5098            return false;
5099        }
5100
5101        final int flags;
5102
5103        final long identity = Binder.clearCallingIdentity();
5104        try {
5105            flags = getPermissionFlags(permissionName,
5106                    packageName, userId);
5107        } finally {
5108            Binder.restoreCallingIdentity(identity);
5109        }
5110
5111        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5112                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5113                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5114
5115        if ((flags & fixedFlags) != 0) {
5116            return false;
5117        }
5118
5119        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5120    }
5121
5122    @Override
5123    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5124        mContext.enforceCallingOrSelfPermission(
5125                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5126                "addOnPermissionsChangeListener");
5127
5128        synchronized (mPackages) {
5129            mOnPermissionChangeListeners.addListenerLocked(listener);
5130        }
5131    }
5132
5133    @Override
5134    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5135        synchronized (mPackages) {
5136            mOnPermissionChangeListeners.removeListenerLocked(listener);
5137        }
5138    }
5139
5140    @Override
5141    public boolean isProtectedBroadcast(String actionName) {
5142        synchronized (mPackages) {
5143            if (mProtectedBroadcasts.contains(actionName)) {
5144                return true;
5145            } else if (actionName != null) {
5146                // TODO: remove these terrible hacks
5147                if (actionName.startsWith("android.net.netmon.lingerExpired")
5148                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5149                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5150                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5151                    return true;
5152                }
5153            }
5154        }
5155        return false;
5156    }
5157
5158    @Override
5159    public int checkSignatures(String pkg1, String pkg2) {
5160        synchronized (mPackages) {
5161            final PackageParser.Package p1 = mPackages.get(pkg1);
5162            final PackageParser.Package p2 = mPackages.get(pkg2);
5163            if (p1 == null || p1.mExtras == null
5164                    || p2 == null || p2.mExtras == null) {
5165                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5166            }
5167            return compareSignatures(p1.mSignatures, p2.mSignatures);
5168        }
5169    }
5170
5171    @Override
5172    public int checkUidSignatures(int uid1, int uid2) {
5173        // Map to base uids.
5174        uid1 = UserHandle.getAppId(uid1);
5175        uid2 = UserHandle.getAppId(uid2);
5176        // reader
5177        synchronized (mPackages) {
5178            Signature[] s1;
5179            Signature[] s2;
5180            Object obj = mSettings.getUserIdLPr(uid1);
5181            if (obj != null) {
5182                if (obj instanceof SharedUserSetting) {
5183                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5184                } else if (obj instanceof PackageSetting) {
5185                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5186                } else {
5187                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5188                }
5189            } else {
5190                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5191            }
5192            obj = mSettings.getUserIdLPr(uid2);
5193            if (obj != null) {
5194                if (obj instanceof SharedUserSetting) {
5195                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5196                } else if (obj instanceof PackageSetting) {
5197                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5198                } else {
5199                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5200                }
5201            } else {
5202                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5203            }
5204            return compareSignatures(s1, s2);
5205        }
5206    }
5207
5208    /**
5209     * This method should typically only be used when granting or revoking
5210     * permissions, since the app may immediately restart after this call.
5211     * <p>
5212     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5213     * guard your work against the app being relaunched.
5214     */
5215    private void killUid(int appId, int userId, String reason) {
5216        final long identity = Binder.clearCallingIdentity();
5217        try {
5218            IActivityManager am = ActivityManager.getService();
5219            if (am != null) {
5220                try {
5221                    am.killUid(appId, userId, reason);
5222                } catch (RemoteException e) {
5223                    /* ignore - same process */
5224                }
5225            }
5226        } finally {
5227            Binder.restoreCallingIdentity(identity);
5228        }
5229    }
5230
5231    /**
5232     * Compares two sets of signatures. Returns:
5233     * <br />
5234     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5235     * <br />
5236     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5237     * <br />
5238     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5239     * <br />
5240     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5241     * <br />
5242     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5243     */
5244    static int compareSignatures(Signature[] s1, Signature[] s2) {
5245        if (s1 == null) {
5246            return s2 == null
5247                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5248                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5249        }
5250
5251        if (s2 == null) {
5252            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5253        }
5254
5255        if (s1.length != s2.length) {
5256            return PackageManager.SIGNATURE_NO_MATCH;
5257        }
5258
5259        // Since both signature sets are of size 1, we can compare without HashSets.
5260        if (s1.length == 1) {
5261            return s1[0].equals(s2[0]) ?
5262                    PackageManager.SIGNATURE_MATCH :
5263                    PackageManager.SIGNATURE_NO_MATCH;
5264        }
5265
5266        ArraySet<Signature> set1 = new ArraySet<Signature>();
5267        for (Signature sig : s1) {
5268            set1.add(sig);
5269        }
5270        ArraySet<Signature> set2 = new ArraySet<Signature>();
5271        for (Signature sig : s2) {
5272            set2.add(sig);
5273        }
5274        // Make sure s2 contains all signatures in s1.
5275        if (set1.equals(set2)) {
5276            return PackageManager.SIGNATURE_MATCH;
5277        }
5278        return PackageManager.SIGNATURE_NO_MATCH;
5279    }
5280
5281    /**
5282     * If the database version for this type of package (internal storage or
5283     * external storage) is less than the version where package signatures
5284     * were updated, return true.
5285     */
5286    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5287        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5288        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5289    }
5290
5291    /**
5292     * Used for backward compatibility to make sure any packages with
5293     * certificate chains get upgraded to the new style. {@code existingSigs}
5294     * will be in the old format (since they were stored on disk from before the
5295     * system upgrade) and {@code scannedSigs} will be in the newer format.
5296     */
5297    private int compareSignaturesCompat(PackageSignatures existingSigs,
5298            PackageParser.Package scannedPkg) {
5299        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5300            return PackageManager.SIGNATURE_NO_MATCH;
5301        }
5302
5303        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5304        for (Signature sig : existingSigs.mSignatures) {
5305            existingSet.add(sig);
5306        }
5307        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5308        for (Signature sig : scannedPkg.mSignatures) {
5309            try {
5310                Signature[] chainSignatures = sig.getChainSignatures();
5311                for (Signature chainSig : chainSignatures) {
5312                    scannedCompatSet.add(chainSig);
5313                }
5314            } catch (CertificateEncodingException e) {
5315                scannedCompatSet.add(sig);
5316            }
5317        }
5318        /*
5319         * Make sure the expanded scanned set contains all signatures in the
5320         * existing one.
5321         */
5322        if (scannedCompatSet.equals(existingSet)) {
5323            // Migrate the old signatures to the new scheme.
5324            existingSigs.assignSignatures(scannedPkg.mSignatures);
5325            // The new KeySets will be re-added later in the scanning process.
5326            synchronized (mPackages) {
5327                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5328            }
5329            return PackageManager.SIGNATURE_MATCH;
5330        }
5331        return PackageManager.SIGNATURE_NO_MATCH;
5332    }
5333
5334    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5335        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5336        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5337    }
5338
5339    private int compareSignaturesRecover(PackageSignatures existingSigs,
5340            PackageParser.Package scannedPkg) {
5341        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5342            return PackageManager.SIGNATURE_NO_MATCH;
5343        }
5344
5345        String msg = null;
5346        try {
5347            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5348                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5349                        + scannedPkg.packageName);
5350                return PackageManager.SIGNATURE_MATCH;
5351            }
5352        } catch (CertificateException e) {
5353            msg = e.getMessage();
5354        }
5355
5356        logCriticalInfo(Log.INFO,
5357                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5358        return PackageManager.SIGNATURE_NO_MATCH;
5359    }
5360
5361    @Override
5362    public List<String> getAllPackages() {
5363        synchronized (mPackages) {
5364            return new ArrayList<String>(mPackages.keySet());
5365        }
5366    }
5367
5368    @Override
5369    public String[] getPackagesForUid(int uid) {
5370        final int userId = UserHandle.getUserId(uid);
5371        uid = UserHandle.getAppId(uid);
5372        // reader
5373        synchronized (mPackages) {
5374            Object obj = mSettings.getUserIdLPr(uid);
5375            if (obj instanceof SharedUserSetting) {
5376                final SharedUserSetting sus = (SharedUserSetting) obj;
5377                final int N = sus.packages.size();
5378                String[] res = new String[N];
5379                final Iterator<PackageSetting> it = sus.packages.iterator();
5380                int i = 0;
5381                while (it.hasNext()) {
5382                    PackageSetting ps = it.next();
5383                    if (ps.getInstalled(userId)) {
5384                        res[i++] = ps.name;
5385                    } else {
5386                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5387                    }
5388                }
5389                return res;
5390            } else if (obj instanceof PackageSetting) {
5391                final PackageSetting ps = (PackageSetting) obj;
5392                if (ps.getInstalled(userId)) {
5393                    return new String[]{ps.name};
5394                }
5395            }
5396        }
5397        return null;
5398    }
5399
5400    @Override
5401    public String getNameForUid(int uid) {
5402        // reader
5403        synchronized (mPackages) {
5404            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5405            if (obj instanceof SharedUserSetting) {
5406                final SharedUserSetting sus = (SharedUserSetting) obj;
5407                return sus.name + ":" + sus.userId;
5408            } else if (obj instanceof PackageSetting) {
5409                final PackageSetting ps = (PackageSetting) obj;
5410                return ps.name;
5411            }
5412        }
5413        return null;
5414    }
5415
5416    @Override
5417    public int getUidForSharedUser(String sharedUserName) {
5418        if(sharedUserName == null) {
5419            return -1;
5420        }
5421        // reader
5422        synchronized (mPackages) {
5423            SharedUserSetting suid;
5424            try {
5425                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5426                if (suid != null) {
5427                    return suid.userId;
5428                }
5429            } catch (PackageManagerException ignore) {
5430                // can't happen, but, still need to catch it
5431            }
5432            return -1;
5433        }
5434    }
5435
5436    @Override
5437    public int getFlagsForUid(int uid) {
5438        synchronized (mPackages) {
5439            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5440            if (obj instanceof SharedUserSetting) {
5441                final SharedUserSetting sus = (SharedUserSetting) obj;
5442                return sus.pkgFlags;
5443            } else if (obj instanceof PackageSetting) {
5444                final PackageSetting ps = (PackageSetting) obj;
5445                return ps.pkgFlags;
5446            }
5447        }
5448        return 0;
5449    }
5450
5451    @Override
5452    public int getPrivateFlagsForUid(int uid) {
5453        synchronized (mPackages) {
5454            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5455            if (obj instanceof SharedUserSetting) {
5456                final SharedUserSetting sus = (SharedUserSetting) obj;
5457                return sus.pkgPrivateFlags;
5458            } else if (obj instanceof PackageSetting) {
5459                final PackageSetting ps = (PackageSetting) obj;
5460                return ps.pkgPrivateFlags;
5461            }
5462        }
5463        return 0;
5464    }
5465
5466    @Override
5467    public boolean isUidPrivileged(int uid) {
5468        uid = UserHandle.getAppId(uid);
5469        // reader
5470        synchronized (mPackages) {
5471            Object obj = mSettings.getUserIdLPr(uid);
5472            if (obj instanceof SharedUserSetting) {
5473                final SharedUserSetting sus = (SharedUserSetting) obj;
5474                final Iterator<PackageSetting> it = sus.packages.iterator();
5475                while (it.hasNext()) {
5476                    if (it.next().isPrivileged()) {
5477                        return true;
5478                    }
5479                }
5480            } else if (obj instanceof PackageSetting) {
5481                final PackageSetting ps = (PackageSetting) obj;
5482                return ps.isPrivileged();
5483            }
5484        }
5485        return false;
5486    }
5487
5488    @Override
5489    public String[] getAppOpPermissionPackages(String permissionName) {
5490        synchronized (mPackages) {
5491            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5492            if (pkgs == null) {
5493                return null;
5494            }
5495            return pkgs.toArray(new String[pkgs.size()]);
5496        }
5497    }
5498
5499    @Override
5500    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5501            int flags, int userId) {
5502        try {
5503            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5504
5505            if (!sUserManager.exists(userId)) return null;
5506            flags = updateFlagsForResolve(flags, userId, intent);
5507            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5508                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5509
5510            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5511            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5512                    flags, userId);
5513            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5514
5515            final ResolveInfo bestChoice =
5516                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5517            return bestChoice;
5518        } finally {
5519            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5520        }
5521    }
5522
5523    @Override
5524    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5525        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5526            throw new SecurityException(
5527                    "findPersistentPreferredActivity can only be run by the system");
5528        }
5529        if (!sUserManager.exists(userId)) {
5530            return null;
5531        }
5532        intent = updateIntentForResolve(intent);
5533        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5534        final int flags = updateFlagsForResolve(0, userId, intent);
5535        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5536                userId);
5537        synchronized (mPackages) {
5538            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5539                    userId);
5540        }
5541    }
5542
5543    @Override
5544    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5545            IntentFilter filter, int match, ComponentName activity) {
5546        final int userId = UserHandle.getCallingUserId();
5547        if (DEBUG_PREFERRED) {
5548            Log.v(TAG, "setLastChosenActivity intent=" + intent
5549                + " resolvedType=" + resolvedType
5550                + " flags=" + flags
5551                + " filter=" + filter
5552                + " match=" + match
5553                + " activity=" + activity);
5554            filter.dump(new PrintStreamPrinter(System.out), "    ");
5555        }
5556        intent.setComponent(null);
5557        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5558                userId);
5559        // Find any earlier preferred or last chosen entries and nuke them
5560        findPreferredActivity(intent, resolvedType,
5561                flags, query, 0, false, true, false, userId);
5562        // Add the new activity as the last chosen for this filter
5563        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5564                "Setting last chosen");
5565    }
5566
5567    @Override
5568    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5569        final int userId = UserHandle.getCallingUserId();
5570        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5571        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5572                userId);
5573        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5574                false, false, false, userId);
5575    }
5576
5577    private boolean isEphemeralDisabled() {
5578        // ephemeral apps have been disabled across the board
5579        if (DISABLE_EPHEMERAL_APPS) {
5580            return true;
5581        }
5582        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5583        if (!mSystemReady) {
5584            return true;
5585        }
5586        // we can't get a content resolver until the system is ready; these checks must happen last
5587        final ContentResolver resolver = mContext.getContentResolver();
5588        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5589            return true;
5590        }
5591        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5592    }
5593
5594    private boolean isEphemeralAllowed(
5595            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5596            boolean skipPackageCheck) {
5597        // Short circuit and return early if possible.
5598        if (isEphemeralDisabled()) {
5599            return false;
5600        }
5601        final int callingUser = UserHandle.getCallingUserId();
5602        if (callingUser != UserHandle.USER_SYSTEM) {
5603            return false;
5604        }
5605        if (mEphemeralResolverConnection == null) {
5606            return false;
5607        }
5608        if (mEphemeralInstallerComponent == null) {
5609            return false;
5610        }
5611        if (intent.getComponent() != null) {
5612            return false;
5613        }
5614        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5615            return false;
5616        }
5617        if (!skipPackageCheck && intent.getPackage() != null) {
5618            return false;
5619        }
5620        final boolean isWebUri = hasWebURI(intent);
5621        if (!isWebUri || intent.getData().getHost() == null) {
5622            return false;
5623        }
5624        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5625        synchronized (mPackages) {
5626            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5627            for (int n = 0; n < count; n++) {
5628                ResolveInfo info = resolvedActivities.get(n);
5629                String packageName = info.activityInfo.packageName;
5630                PackageSetting ps = mSettings.mPackages.get(packageName);
5631                if (ps != null) {
5632                    // Try to get the status from User settings first
5633                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5634                    int status = (int) (packedStatus >> 32);
5635                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5636                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5637                        if (DEBUG_EPHEMERAL) {
5638                            Slog.v(TAG, "DENY ephemeral apps;"
5639                                + " pkg: " + packageName + ", status: " + status);
5640                        }
5641                        return false;
5642                    }
5643                }
5644            }
5645        }
5646        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5647        return true;
5648    }
5649
5650    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
5651            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
5652            int userId) {
5653        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
5654                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
5655                        callingPackage, userId));
5656        mHandler.sendMessage(msg);
5657    }
5658
5659    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5660            int flags, List<ResolveInfo> query, int userId) {
5661        if (query != null) {
5662            final int N = query.size();
5663            if (N == 1) {
5664                return query.get(0);
5665            } else if (N > 1) {
5666                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5667                // If there is more than one activity with the same priority,
5668                // then let the user decide between them.
5669                ResolveInfo r0 = query.get(0);
5670                ResolveInfo r1 = query.get(1);
5671                if (DEBUG_INTENT_MATCHING || debug) {
5672                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5673                            + r1.activityInfo.name + "=" + r1.priority);
5674                }
5675                // If the first activity has a higher priority, or a different
5676                // default, then it is always desirable to pick it.
5677                if (r0.priority != r1.priority
5678                        || r0.preferredOrder != r1.preferredOrder
5679                        || r0.isDefault != r1.isDefault) {
5680                    return query.get(0);
5681                }
5682                // If we have saved a preference for a preferred activity for
5683                // this Intent, use that.
5684                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5685                        flags, query, r0.priority, true, false, debug, userId);
5686                if (ri != null) {
5687                    return ri;
5688                }
5689                ri = new ResolveInfo(mResolveInfo);
5690                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5691                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5692                // If all of the options come from the same package, show the application's
5693                // label and icon instead of the generic resolver's.
5694                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5695                // and then throw away the ResolveInfo itself, meaning that the caller loses
5696                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5697                // a fallback for this case; we only set the target package's resources on
5698                // the ResolveInfo, not the ActivityInfo.
5699                final String intentPackage = intent.getPackage();
5700                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5701                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5702                    ri.resolvePackageName = intentPackage;
5703                    if (userNeedsBadging(userId)) {
5704                        ri.noResourceId = true;
5705                    } else {
5706                        ri.icon = appi.icon;
5707                    }
5708                    ri.iconResourceId = appi.icon;
5709                    ri.labelRes = appi.labelRes;
5710                }
5711                ri.activityInfo.applicationInfo = new ApplicationInfo(
5712                        ri.activityInfo.applicationInfo);
5713                if (userId != 0) {
5714                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5715                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5716                }
5717                // Make sure that the resolver is displayable in car mode
5718                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5719                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5720                return ri;
5721            }
5722        }
5723        return null;
5724    }
5725
5726    /**
5727     * Return true if the given list is not empty and all of its contents have
5728     * an activityInfo with the given package name.
5729     */
5730    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5731        if (ArrayUtils.isEmpty(list)) {
5732            return false;
5733        }
5734        for (int i = 0, N = list.size(); i < N; i++) {
5735            final ResolveInfo ri = list.get(i);
5736            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5737            if (ai == null || !packageName.equals(ai.packageName)) {
5738                return false;
5739            }
5740        }
5741        return true;
5742    }
5743
5744    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5745            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5746        final int N = query.size();
5747        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5748                .get(userId);
5749        // Get the list of persistent preferred activities that handle the intent
5750        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5751        List<PersistentPreferredActivity> pprefs = ppir != null
5752                ? ppir.queryIntent(intent, resolvedType,
5753                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5754                        userId)
5755                : null;
5756        if (pprefs != null && pprefs.size() > 0) {
5757            final int M = pprefs.size();
5758            for (int i=0; i<M; i++) {
5759                final PersistentPreferredActivity ppa = pprefs.get(i);
5760                if (DEBUG_PREFERRED || debug) {
5761                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5762                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5763                            + "\n  component=" + ppa.mComponent);
5764                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5765                }
5766                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5767                        flags | MATCH_DISABLED_COMPONENTS, userId);
5768                if (DEBUG_PREFERRED || debug) {
5769                    Slog.v(TAG, "Found persistent preferred activity:");
5770                    if (ai != null) {
5771                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5772                    } else {
5773                        Slog.v(TAG, "  null");
5774                    }
5775                }
5776                if (ai == null) {
5777                    // This previously registered persistent preferred activity
5778                    // component is no longer known. Ignore it and do NOT remove it.
5779                    continue;
5780                }
5781                for (int j=0; j<N; j++) {
5782                    final ResolveInfo ri = query.get(j);
5783                    if (!ri.activityInfo.applicationInfo.packageName
5784                            .equals(ai.applicationInfo.packageName)) {
5785                        continue;
5786                    }
5787                    if (!ri.activityInfo.name.equals(ai.name)) {
5788                        continue;
5789                    }
5790                    //  Found a persistent preference that can handle the intent.
5791                    if (DEBUG_PREFERRED || debug) {
5792                        Slog.v(TAG, "Returning persistent preferred activity: " +
5793                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5794                    }
5795                    return ri;
5796                }
5797            }
5798        }
5799        return null;
5800    }
5801
5802    // TODO: handle preferred activities missing while user has amnesia
5803    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5804            List<ResolveInfo> query, int priority, boolean always,
5805            boolean removeMatches, boolean debug, int userId) {
5806        if (!sUserManager.exists(userId)) return null;
5807        flags = updateFlagsForResolve(flags, userId, intent);
5808        intent = updateIntentForResolve(intent);
5809        // writer
5810        synchronized (mPackages) {
5811            // Try to find a matching persistent preferred activity.
5812            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5813                    debug, userId);
5814
5815            // If a persistent preferred activity matched, use it.
5816            if (pri != null) {
5817                return pri;
5818            }
5819
5820            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5821            // Get the list of preferred activities that handle the intent
5822            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5823            List<PreferredActivity> prefs = pir != null
5824                    ? pir.queryIntent(intent, resolvedType,
5825                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5826                            userId)
5827                    : null;
5828            if (prefs != null && prefs.size() > 0) {
5829                boolean changed = false;
5830                try {
5831                    // First figure out how good the original match set is.
5832                    // We will only allow preferred activities that came
5833                    // from the same match quality.
5834                    int match = 0;
5835
5836                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5837
5838                    final int N = query.size();
5839                    for (int j=0; j<N; j++) {
5840                        final ResolveInfo ri = query.get(j);
5841                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5842                                + ": 0x" + Integer.toHexString(match));
5843                        if (ri.match > match) {
5844                            match = ri.match;
5845                        }
5846                    }
5847
5848                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5849                            + Integer.toHexString(match));
5850
5851                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5852                    final int M = prefs.size();
5853                    for (int i=0; i<M; i++) {
5854                        final PreferredActivity pa = prefs.get(i);
5855                        if (DEBUG_PREFERRED || debug) {
5856                            Slog.v(TAG, "Checking PreferredActivity ds="
5857                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5858                                    + "\n  component=" + pa.mPref.mComponent);
5859                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5860                        }
5861                        if (pa.mPref.mMatch != match) {
5862                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5863                                    + Integer.toHexString(pa.mPref.mMatch));
5864                            continue;
5865                        }
5866                        // If it's not an "always" type preferred activity and that's what we're
5867                        // looking for, skip it.
5868                        if (always && !pa.mPref.mAlways) {
5869                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5870                            continue;
5871                        }
5872                        final ActivityInfo ai = getActivityInfo(
5873                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5874                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5875                                userId);
5876                        if (DEBUG_PREFERRED || debug) {
5877                            Slog.v(TAG, "Found preferred activity:");
5878                            if (ai != null) {
5879                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5880                            } else {
5881                                Slog.v(TAG, "  null");
5882                            }
5883                        }
5884                        if (ai == null) {
5885                            // This previously registered preferred activity
5886                            // component is no longer known.  Most likely an update
5887                            // to the app was installed and in the new version this
5888                            // component no longer exists.  Clean it up by removing
5889                            // it from the preferred activities list, and skip it.
5890                            Slog.w(TAG, "Removing dangling preferred activity: "
5891                                    + pa.mPref.mComponent);
5892                            pir.removeFilter(pa);
5893                            changed = true;
5894                            continue;
5895                        }
5896                        for (int j=0; j<N; j++) {
5897                            final ResolveInfo ri = query.get(j);
5898                            if (!ri.activityInfo.applicationInfo.packageName
5899                                    .equals(ai.applicationInfo.packageName)) {
5900                                continue;
5901                            }
5902                            if (!ri.activityInfo.name.equals(ai.name)) {
5903                                continue;
5904                            }
5905
5906                            if (removeMatches) {
5907                                pir.removeFilter(pa);
5908                                changed = true;
5909                                if (DEBUG_PREFERRED) {
5910                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5911                                }
5912                                break;
5913                            }
5914
5915                            // Okay we found a previously set preferred or last chosen app.
5916                            // If the result set is different from when this
5917                            // was created, we need to clear it and re-ask the
5918                            // user their preference, if we're looking for an "always" type entry.
5919                            if (always && !pa.mPref.sameSet(query)) {
5920                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5921                                        + intent + " type " + resolvedType);
5922                                if (DEBUG_PREFERRED) {
5923                                    Slog.v(TAG, "Removing preferred activity since set changed "
5924                                            + pa.mPref.mComponent);
5925                                }
5926                                pir.removeFilter(pa);
5927                                // Re-add the filter as a "last chosen" entry (!always)
5928                                PreferredActivity lastChosen = new PreferredActivity(
5929                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5930                                pir.addFilter(lastChosen);
5931                                changed = true;
5932                                return null;
5933                            }
5934
5935                            // Yay! Either the set matched or we're looking for the last chosen
5936                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5937                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5938                            return ri;
5939                        }
5940                    }
5941                } finally {
5942                    if (changed) {
5943                        if (DEBUG_PREFERRED) {
5944                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5945                        }
5946                        scheduleWritePackageRestrictionsLocked(userId);
5947                    }
5948                }
5949            }
5950        }
5951        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5952        return null;
5953    }
5954
5955    /*
5956     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5957     */
5958    @Override
5959    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5960            int targetUserId) {
5961        mContext.enforceCallingOrSelfPermission(
5962                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5963        List<CrossProfileIntentFilter> matches =
5964                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5965        if (matches != null) {
5966            int size = matches.size();
5967            for (int i = 0; i < size; i++) {
5968                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5969            }
5970        }
5971        if (hasWebURI(intent)) {
5972            // cross-profile app linking works only towards the parent.
5973            final UserInfo parent = getProfileParent(sourceUserId);
5974            synchronized(mPackages) {
5975                int flags = updateFlagsForResolve(0, parent.id, intent);
5976                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5977                        intent, resolvedType, flags, sourceUserId, parent.id);
5978                return xpDomainInfo != null;
5979            }
5980        }
5981        return false;
5982    }
5983
5984    private UserInfo getProfileParent(int userId) {
5985        final long identity = Binder.clearCallingIdentity();
5986        try {
5987            return sUserManager.getProfileParent(userId);
5988        } finally {
5989            Binder.restoreCallingIdentity(identity);
5990        }
5991    }
5992
5993    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5994            String resolvedType, int userId) {
5995        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5996        if (resolver != null) {
5997            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
5998        }
5999        return null;
6000    }
6001
6002    @Override
6003    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6004            String resolvedType, int flags, int userId) {
6005        try {
6006            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6007
6008            return new ParceledListSlice<>(
6009                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6010        } finally {
6011            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6012        }
6013    }
6014
6015    /**
6016     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6017     * instant, returns {@code null}.
6018     */
6019    private String getInstantAppPackageName(int callingUid) {
6020        final int appId = UserHandle.getAppId(callingUid);
6021        synchronized (mPackages) {
6022            final Object obj = mSettings.getUserIdLPr(appId);
6023            if (obj instanceof PackageSetting) {
6024                final PackageSetting ps = (PackageSetting) obj;
6025                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6026                return isInstantApp ? ps.pkg.packageName : null;
6027            }
6028        }
6029        return null;
6030    }
6031
6032    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6033            String resolvedType, int flags, int userId) {
6034        if (!sUserManager.exists(userId)) return Collections.emptyList();
6035        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
6036        flags = updateFlagsForResolve(flags, userId, intent);
6037        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6038                false /* requireFullPermission */, false /* checkShell */,
6039                "query intent activities");
6040        ComponentName comp = intent.getComponent();
6041        if (comp == null) {
6042            if (intent.getSelector() != null) {
6043                intent = intent.getSelector();
6044                comp = intent.getComponent();
6045            }
6046        }
6047
6048        if (comp != null) {
6049            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6050            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6051            if (ai != null) {
6052                // When specifying an explicit component, we prevent the activity from being
6053                // used when either 1) the calling package is normal and the activity is within
6054                // an ephemeral application or 2) the calling package is ephemeral and the
6055                // activity is not visible to ephemeral applications.
6056                final boolean matchInstantApp =
6057                        (flags & PackageManager.MATCH_INSTANT) != 0;
6058                final boolean matchVisibleToInstantAppOnly =
6059                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6060                final boolean isCallerInstantApp =
6061                        instantAppPkgName != null;
6062                final boolean isTargetSameInstantApp =
6063                        comp.getPackageName().equals(instantAppPkgName);
6064                final boolean isTargetInstantApp =
6065                        (ai.applicationInfo.privateFlags
6066                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6067                final boolean isTargetHiddenFromInstantApp =
6068                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6069                final boolean blockResolution =
6070                        !isTargetSameInstantApp
6071                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6072                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6073                                        && isTargetHiddenFromInstantApp));
6074                if (!blockResolution) {
6075                    final ResolveInfo ri = new ResolveInfo();
6076                    ri.activityInfo = ai;
6077                    list.add(ri);
6078                }
6079            }
6080            return list;
6081        }
6082
6083        // reader
6084        boolean sortResult = false;
6085        boolean addEphemeral = false;
6086        List<ResolveInfo> result;
6087        final String pkgName = intent.getPackage();
6088        synchronized (mPackages) {
6089            if (pkgName == null) {
6090                List<CrossProfileIntentFilter> matchingFilters =
6091                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6092                // Check for results that need to skip the current profile.
6093                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6094                        resolvedType, flags, userId);
6095                if (xpResolveInfo != null) {
6096                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6097                    xpResult.add(xpResolveInfo);
6098                    return filterForEphemeral(
6099                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6100                }
6101
6102                // Check for results in the current profile.
6103                result = filterIfNotSystemUser(mActivities.queryIntent(
6104                        intent, resolvedType, flags, userId), userId);
6105                addEphemeral =
6106                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6107
6108                // Check for cross profile results.
6109                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6110                xpResolveInfo = queryCrossProfileIntents(
6111                        matchingFilters, intent, resolvedType, flags, userId,
6112                        hasNonNegativePriorityResult);
6113                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6114                    boolean isVisibleToUser = filterIfNotSystemUser(
6115                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6116                    if (isVisibleToUser) {
6117                        result.add(xpResolveInfo);
6118                        sortResult = true;
6119                    }
6120                }
6121                if (hasWebURI(intent)) {
6122                    CrossProfileDomainInfo xpDomainInfo = null;
6123                    final UserInfo parent = getProfileParent(userId);
6124                    if (parent != null) {
6125                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6126                                flags, userId, parent.id);
6127                    }
6128                    if (xpDomainInfo != null) {
6129                        if (xpResolveInfo != null) {
6130                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6131                            // in the result.
6132                            result.remove(xpResolveInfo);
6133                        }
6134                        if (result.size() == 0 && !addEphemeral) {
6135                            // No result in current profile, but found candidate in parent user.
6136                            // And we are not going to add emphemeral app, so we can return the
6137                            // result straight away.
6138                            result.add(xpDomainInfo.resolveInfo);
6139                            return filterForEphemeral(result, instantAppPkgName);
6140                        }
6141                    } else if (result.size() <= 1 && !addEphemeral) {
6142                        // No result in parent user and <= 1 result in current profile, and we
6143                        // are not going to add emphemeral app, so we can return the result without
6144                        // further processing.
6145                        return filterForEphemeral(result, instantAppPkgName);
6146                    }
6147                    // We have more than one candidate (combining results from current and parent
6148                    // profile), so we need filtering and sorting.
6149                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6150                            intent, flags, result, xpDomainInfo, userId);
6151                    sortResult = true;
6152                }
6153            } else {
6154                final PackageParser.Package pkg = mPackages.get(pkgName);
6155                if (pkg != null) {
6156                    result = filterForEphemeral(filterIfNotSystemUser(
6157                            mActivities.queryIntentForPackage(
6158                                    intent, resolvedType, flags, pkg.activities, userId),
6159                            userId), instantAppPkgName);
6160                } else {
6161                    // the caller wants to resolve for a particular package; however, there
6162                    // were no installed results, so, try to find an ephemeral result
6163                    addEphemeral = isEphemeralAllowed(
6164                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
6165                    result = new ArrayList<ResolveInfo>();
6166                }
6167            }
6168        }
6169        if (addEphemeral) {
6170            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6171            final EphemeralRequest requestObject = new EphemeralRequest(
6172                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6173                    null /*launchIntent*/, null /*callingPackage*/, userId);
6174            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
6175                    mContext, mEphemeralResolverConnection, requestObject);
6176            if (intentInfo != null) {
6177                if (DEBUG_EPHEMERAL) {
6178                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6179                }
6180                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
6181                ephemeralInstaller.ephemeralResponse = intentInfo;
6182                // make sure this resolver is the default
6183                ephemeralInstaller.isDefault = true;
6184                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6185                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6186                // add a non-generic filter
6187                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6188                ephemeralInstaller.filter.addDataPath(
6189                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6190                result.add(ephemeralInstaller);
6191            }
6192            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6193        }
6194        if (sortResult) {
6195            Collections.sort(result, mResolvePrioritySorter);
6196        }
6197        return filterForEphemeral(result, instantAppPkgName);
6198    }
6199
6200    private static class CrossProfileDomainInfo {
6201        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6202        ResolveInfo resolveInfo;
6203        /* Best domain verification status of the activities found in the other profile */
6204        int bestDomainVerificationStatus;
6205    }
6206
6207    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6208            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6209        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6210                sourceUserId)) {
6211            return null;
6212        }
6213        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6214                resolvedType, flags, parentUserId);
6215
6216        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6217            return null;
6218        }
6219        CrossProfileDomainInfo result = null;
6220        int size = resultTargetUser.size();
6221        for (int i = 0; i < size; i++) {
6222            ResolveInfo riTargetUser = resultTargetUser.get(i);
6223            // Intent filter verification is only for filters that specify a host. So don't return
6224            // those that handle all web uris.
6225            if (riTargetUser.handleAllWebDataURI) {
6226                continue;
6227            }
6228            String packageName = riTargetUser.activityInfo.packageName;
6229            PackageSetting ps = mSettings.mPackages.get(packageName);
6230            if (ps == null) {
6231                continue;
6232            }
6233            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6234            int status = (int)(verificationState >> 32);
6235            if (result == null) {
6236                result = new CrossProfileDomainInfo();
6237                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6238                        sourceUserId, parentUserId);
6239                result.bestDomainVerificationStatus = status;
6240            } else {
6241                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6242                        result.bestDomainVerificationStatus);
6243            }
6244        }
6245        // Don't consider matches with status NEVER across profiles.
6246        if (result != null && result.bestDomainVerificationStatus
6247                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6248            return null;
6249        }
6250        return result;
6251    }
6252
6253    /**
6254     * Verification statuses are ordered from the worse to the best, except for
6255     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6256     */
6257    private int bestDomainVerificationStatus(int status1, int status2) {
6258        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6259            return status2;
6260        }
6261        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6262            return status1;
6263        }
6264        return (int) MathUtils.max(status1, status2);
6265    }
6266
6267    private boolean isUserEnabled(int userId) {
6268        long callingId = Binder.clearCallingIdentity();
6269        try {
6270            UserInfo userInfo = sUserManager.getUserInfo(userId);
6271            return userInfo != null && userInfo.isEnabled();
6272        } finally {
6273            Binder.restoreCallingIdentity(callingId);
6274        }
6275    }
6276
6277    /**
6278     * Filter out activities with systemUserOnly flag set, when current user is not System.
6279     *
6280     * @return filtered list
6281     */
6282    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6283        if (userId == UserHandle.USER_SYSTEM) {
6284            return resolveInfos;
6285        }
6286        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6287            ResolveInfo info = resolveInfos.get(i);
6288            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6289                resolveInfos.remove(i);
6290            }
6291        }
6292        return resolveInfos;
6293    }
6294
6295    /**
6296     * Filters out ephemeral activities.
6297     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6298     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6299     *
6300     * @param resolveInfos The pre-filtered list of resolved activities
6301     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6302     *          is performed.
6303     * @return A filtered list of resolved activities.
6304     */
6305    private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos,
6306            String ephemeralPkgName) {
6307        if (ephemeralPkgName == null) {
6308            return resolveInfos;
6309        }
6310        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6311            ResolveInfo info = resolveInfos.get(i);
6312            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6313            // allow activities that are defined in the provided package
6314            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6315                continue;
6316            }
6317            // allow activities that have been explicitly exposed to ephemeral apps
6318            if (!isEphemeralApp
6319                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6320                continue;
6321            }
6322            resolveInfos.remove(i);
6323        }
6324        return resolveInfos;
6325    }
6326
6327    /**
6328     * @param resolveInfos list of resolve infos in descending priority order
6329     * @return if the list contains a resolve info with non-negative priority
6330     */
6331    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6332        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6333    }
6334
6335    private static boolean hasWebURI(Intent intent) {
6336        if (intent.getData() == null) {
6337            return false;
6338        }
6339        final String scheme = intent.getScheme();
6340        if (TextUtils.isEmpty(scheme)) {
6341            return false;
6342        }
6343        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6344    }
6345
6346    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6347            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6348            int userId) {
6349        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6350
6351        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6352            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6353                    candidates.size());
6354        }
6355
6356        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6357        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6358        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6359        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6360        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6361        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6362
6363        synchronized (mPackages) {
6364            final int count = candidates.size();
6365            // First, try to use linked apps. Partition the candidates into four lists:
6366            // one for the final results, one for the "do not use ever", one for "undefined status"
6367            // and finally one for "browser app type".
6368            for (int n=0; n<count; n++) {
6369                ResolveInfo info = candidates.get(n);
6370                String packageName = info.activityInfo.packageName;
6371                PackageSetting ps = mSettings.mPackages.get(packageName);
6372                if (ps != null) {
6373                    // Add to the special match all list (Browser use case)
6374                    if (info.handleAllWebDataURI) {
6375                        matchAllList.add(info);
6376                        continue;
6377                    }
6378                    // Try to get the status from User settings first
6379                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6380                    int status = (int)(packedStatus >> 32);
6381                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6382                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6383                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6384                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6385                                    + " : linkgen=" + linkGeneration);
6386                        }
6387                        // Use link-enabled generation as preferredOrder, i.e.
6388                        // prefer newly-enabled over earlier-enabled.
6389                        info.preferredOrder = linkGeneration;
6390                        alwaysList.add(info);
6391                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6392                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6393                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6394                        }
6395                        neverList.add(info);
6396                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6397                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6398                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6399                        }
6400                        alwaysAskList.add(info);
6401                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6402                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6403                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6404                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6405                        }
6406                        undefinedList.add(info);
6407                    }
6408                }
6409            }
6410
6411            // We'll want to include browser possibilities in a few cases
6412            boolean includeBrowser = false;
6413
6414            // First try to add the "always" resolution(s) for the current user, if any
6415            if (alwaysList.size() > 0) {
6416                result.addAll(alwaysList);
6417            } else {
6418                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6419                result.addAll(undefinedList);
6420                // Maybe add one for the other profile.
6421                if (xpDomainInfo != null && (
6422                        xpDomainInfo.bestDomainVerificationStatus
6423                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6424                    result.add(xpDomainInfo.resolveInfo);
6425                }
6426                includeBrowser = true;
6427            }
6428
6429            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6430            // If there were 'always' entries their preferred order has been set, so we also
6431            // back that off to make the alternatives equivalent
6432            if (alwaysAskList.size() > 0) {
6433                for (ResolveInfo i : result) {
6434                    i.preferredOrder = 0;
6435                }
6436                result.addAll(alwaysAskList);
6437                includeBrowser = true;
6438            }
6439
6440            if (includeBrowser) {
6441                // Also add browsers (all of them or only the default one)
6442                if (DEBUG_DOMAIN_VERIFICATION) {
6443                    Slog.v(TAG, "   ...including browsers in candidate set");
6444                }
6445                if ((matchFlags & MATCH_ALL) != 0) {
6446                    result.addAll(matchAllList);
6447                } else {
6448                    // Browser/generic handling case.  If there's a default browser, go straight
6449                    // to that (but only if there is no other higher-priority match).
6450                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6451                    int maxMatchPrio = 0;
6452                    ResolveInfo defaultBrowserMatch = null;
6453                    final int numCandidates = matchAllList.size();
6454                    for (int n = 0; n < numCandidates; n++) {
6455                        ResolveInfo info = matchAllList.get(n);
6456                        // track the highest overall match priority...
6457                        if (info.priority > maxMatchPrio) {
6458                            maxMatchPrio = info.priority;
6459                        }
6460                        // ...and the highest-priority default browser match
6461                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6462                            if (defaultBrowserMatch == null
6463                                    || (defaultBrowserMatch.priority < info.priority)) {
6464                                if (debug) {
6465                                    Slog.v(TAG, "Considering default browser match " + info);
6466                                }
6467                                defaultBrowserMatch = info;
6468                            }
6469                        }
6470                    }
6471                    if (defaultBrowserMatch != null
6472                            && defaultBrowserMatch.priority >= maxMatchPrio
6473                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6474                    {
6475                        if (debug) {
6476                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6477                        }
6478                        result.add(defaultBrowserMatch);
6479                    } else {
6480                        result.addAll(matchAllList);
6481                    }
6482                }
6483
6484                // If there is nothing selected, add all candidates and remove the ones that the user
6485                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6486                if (result.size() == 0) {
6487                    result.addAll(candidates);
6488                    result.removeAll(neverList);
6489                }
6490            }
6491        }
6492        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6493            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6494                    result.size());
6495            for (ResolveInfo info : result) {
6496                Slog.v(TAG, "  + " + info.activityInfo);
6497            }
6498        }
6499        return result;
6500    }
6501
6502    // Returns a packed value as a long:
6503    //
6504    // high 'int'-sized word: link status: undefined/ask/never/always.
6505    // low 'int'-sized word: relative priority among 'always' results.
6506    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6507        long result = ps.getDomainVerificationStatusForUser(userId);
6508        // if none available, get the master status
6509        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6510            if (ps.getIntentFilterVerificationInfo() != null) {
6511                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6512            }
6513        }
6514        return result;
6515    }
6516
6517    private ResolveInfo querySkipCurrentProfileIntents(
6518            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6519            int flags, int sourceUserId) {
6520        if (matchingFilters != null) {
6521            int size = matchingFilters.size();
6522            for (int i = 0; i < size; i ++) {
6523                CrossProfileIntentFilter filter = matchingFilters.get(i);
6524                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6525                    // Checking if there are activities in the target user that can handle the
6526                    // intent.
6527                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6528                            resolvedType, flags, sourceUserId);
6529                    if (resolveInfo != null) {
6530                        return resolveInfo;
6531                    }
6532                }
6533            }
6534        }
6535        return null;
6536    }
6537
6538    // Return matching ResolveInfo in target user if any.
6539    private ResolveInfo queryCrossProfileIntents(
6540            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6541            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6542        if (matchingFilters != null) {
6543            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6544            // match the same intent. For performance reasons, it is better not to
6545            // run queryIntent twice for the same userId
6546            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6547            int size = matchingFilters.size();
6548            for (int i = 0; i < size; i++) {
6549                CrossProfileIntentFilter filter = matchingFilters.get(i);
6550                int targetUserId = filter.getTargetUserId();
6551                boolean skipCurrentProfile =
6552                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6553                boolean skipCurrentProfileIfNoMatchFound =
6554                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6555                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6556                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6557                    // Checking if there are activities in the target user that can handle the
6558                    // intent.
6559                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6560                            resolvedType, flags, sourceUserId);
6561                    if (resolveInfo != null) return resolveInfo;
6562                    alreadyTriedUserIds.put(targetUserId, true);
6563                }
6564            }
6565        }
6566        return null;
6567    }
6568
6569    /**
6570     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6571     * will forward the intent to the filter's target user.
6572     * Otherwise, returns null.
6573     */
6574    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6575            String resolvedType, int flags, int sourceUserId) {
6576        int targetUserId = filter.getTargetUserId();
6577        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6578                resolvedType, flags, targetUserId);
6579        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6580            // If all the matches in the target profile are suspended, return null.
6581            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6582                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6583                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6584                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6585                            targetUserId);
6586                }
6587            }
6588        }
6589        return null;
6590    }
6591
6592    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6593            int sourceUserId, int targetUserId) {
6594        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6595        long ident = Binder.clearCallingIdentity();
6596        boolean targetIsProfile;
6597        try {
6598            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6599        } finally {
6600            Binder.restoreCallingIdentity(ident);
6601        }
6602        String className;
6603        if (targetIsProfile) {
6604            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6605        } else {
6606            className = FORWARD_INTENT_TO_PARENT;
6607        }
6608        ComponentName forwardingActivityComponentName = new ComponentName(
6609                mAndroidApplication.packageName, className);
6610        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6611                sourceUserId);
6612        if (!targetIsProfile) {
6613            forwardingActivityInfo.showUserIcon = targetUserId;
6614            forwardingResolveInfo.noResourceId = true;
6615        }
6616        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6617        forwardingResolveInfo.priority = 0;
6618        forwardingResolveInfo.preferredOrder = 0;
6619        forwardingResolveInfo.match = 0;
6620        forwardingResolveInfo.isDefault = true;
6621        forwardingResolveInfo.filter = filter;
6622        forwardingResolveInfo.targetUserId = targetUserId;
6623        return forwardingResolveInfo;
6624    }
6625
6626    @Override
6627    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6628            Intent[] specifics, String[] specificTypes, Intent intent,
6629            String resolvedType, int flags, int userId) {
6630        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6631                specificTypes, intent, resolvedType, flags, userId));
6632    }
6633
6634    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6635            Intent[] specifics, String[] specificTypes, Intent intent,
6636            String resolvedType, int flags, int userId) {
6637        if (!sUserManager.exists(userId)) return Collections.emptyList();
6638        flags = updateFlagsForResolve(flags, userId, intent);
6639        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6640                false /* requireFullPermission */, false /* checkShell */,
6641                "query intent activity options");
6642        final String resultsAction = intent.getAction();
6643
6644        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6645                | PackageManager.GET_RESOLVED_FILTER, userId);
6646
6647        if (DEBUG_INTENT_MATCHING) {
6648            Log.v(TAG, "Query " + intent + ": " + results);
6649        }
6650
6651        int specificsPos = 0;
6652        int N;
6653
6654        // todo: note that the algorithm used here is O(N^2).  This
6655        // isn't a problem in our current environment, but if we start running
6656        // into situations where we have more than 5 or 10 matches then this
6657        // should probably be changed to something smarter...
6658
6659        // First we go through and resolve each of the specific items
6660        // that were supplied, taking care of removing any corresponding
6661        // duplicate items in the generic resolve list.
6662        if (specifics != null) {
6663            for (int i=0; i<specifics.length; i++) {
6664                final Intent sintent = specifics[i];
6665                if (sintent == null) {
6666                    continue;
6667                }
6668
6669                if (DEBUG_INTENT_MATCHING) {
6670                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6671                }
6672
6673                String action = sintent.getAction();
6674                if (resultsAction != null && resultsAction.equals(action)) {
6675                    // If this action was explicitly requested, then don't
6676                    // remove things that have it.
6677                    action = null;
6678                }
6679
6680                ResolveInfo ri = null;
6681                ActivityInfo ai = null;
6682
6683                ComponentName comp = sintent.getComponent();
6684                if (comp == null) {
6685                    ri = resolveIntent(
6686                        sintent,
6687                        specificTypes != null ? specificTypes[i] : null,
6688                            flags, userId);
6689                    if (ri == null) {
6690                        continue;
6691                    }
6692                    if (ri == mResolveInfo) {
6693                        // ACK!  Must do something better with this.
6694                    }
6695                    ai = ri.activityInfo;
6696                    comp = new ComponentName(ai.applicationInfo.packageName,
6697                            ai.name);
6698                } else {
6699                    ai = getActivityInfo(comp, flags, userId);
6700                    if (ai == null) {
6701                        continue;
6702                    }
6703                }
6704
6705                // Look for any generic query activities that are duplicates
6706                // of this specific one, and remove them from the results.
6707                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6708                N = results.size();
6709                int j;
6710                for (j=specificsPos; j<N; j++) {
6711                    ResolveInfo sri = results.get(j);
6712                    if ((sri.activityInfo.name.equals(comp.getClassName())
6713                            && sri.activityInfo.applicationInfo.packageName.equals(
6714                                    comp.getPackageName()))
6715                        || (action != null && sri.filter.matchAction(action))) {
6716                        results.remove(j);
6717                        if (DEBUG_INTENT_MATCHING) Log.v(
6718                            TAG, "Removing duplicate item from " + j
6719                            + " due to specific " + specificsPos);
6720                        if (ri == null) {
6721                            ri = sri;
6722                        }
6723                        j--;
6724                        N--;
6725                    }
6726                }
6727
6728                // Add this specific item to its proper place.
6729                if (ri == null) {
6730                    ri = new ResolveInfo();
6731                    ri.activityInfo = ai;
6732                }
6733                results.add(specificsPos, ri);
6734                ri.specificIndex = i;
6735                specificsPos++;
6736            }
6737        }
6738
6739        // Now we go through the remaining generic results and remove any
6740        // duplicate actions that are found here.
6741        N = results.size();
6742        for (int i=specificsPos; i<N-1; i++) {
6743            final ResolveInfo rii = results.get(i);
6744            if (rii.filter == null) {
6745                continue;
6746            }
6747
6748            // Iterate over all of the actions of this result's intent
6749            // filter...  typically this should be just one.
6750            final Iterator<String> it = rii.filter.actionsIterator();
6751            if (it == null) {
6752                continue;
6753            }
6754            while (it.hasNext()) {
6755                final String action = it.next();
6756                if (resultsAction != null && resultsAction.equals(action)) {
6757                    // If this action was explicitly requested, then don't
6758                    // remove things that have it.
6759                    continue;
6760                }
6761                for (int j=i+1; j<N; j++) {
6762                    final ResolveInfo rij = results.get(j);
6763                    if (rij.filter != null && rij.filter.hasAction(action)) {
6764                        results.remove(j);
6765                        if (DEBUG_INTENT_MATCHING) Log.v(
6766                            TAG, "Removing duplicate item from " + j
6767                            + " due to action " + action + " at " + i);
6768                        j--;
6769                        N--;
6770                    }
6771                }
6772            }
6773
6774            // If the caller didn't request filter information, drop it now
6775            // so we don't have to marshall/unmarshall it.
6776            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6777                rii.filter = null;
6778            }
6779        }
6780
6781        // Filter out the caller activity if so requested.
6782        if (caller != null) {
6783            N = results.size();
6784            for (int i=0; i<N; i++) {
6785                ActivityInfo ainfo = results.get(i).activityInfo;
6786                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6787                        && caller.getClassName().equals(ainfo.name)) {
6788                    results.remove(i);
6789                    break;
6790                }
6791            }
6792        }
6793
6794        // If the caller didn't request filter information,
6795        // drop them now so we don't have to
6796        // marshall/unmarshall it.
6797        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6798            N = results.size();
6799            for (int i=0; i<N; i++) {
6800                results.get(i).filter = null;
6801            }
6802        }
6803
6804        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6805        return results;
6806    }
6807
6808    @Override
6809    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6810            String resolvedType, int flags, int userId) {
6811        return new ParceledListSlice<>(
6812                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6813    }
6814
6815    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6816            String resolvedType, int flags, int userId) {
6817        if (!sUserManager.exists(userId)) return Collections.emptyList();
6818        flags = updateFlagsForResolve(flags, userId, intent);
6819        ComponentName comp = intent.getComponent();
6820        if (comp == null) {
6821            if (intent.getSelector() != null) {
6822                intent = intent.getSelector();
6823                comp = intent.getComponent();
6824            }
6825        }
6826        if (comp != null) {
6827            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6828            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6829            if (ai != null) {
6830                ResolveInfo ri = new ResolveInfo();
6831                ri.activityInfo = ai;
6832                list.add(ri);
6833            }
6834            return list;
6835        }
6836
6837        // reader
6838        synchronized (mPackages) {
6839            String pkgName = intent.getPackage();
6840            if (pkgName == null) {
6841                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6842            }
6843            final PackageParser.Package pkg = mPackages.get(pkgName);
6844            if (pkg != null) {
6845                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6846                        userId);
6847            }
6848            return Collections.emptyList();
6849        }
6850    }
6851
6852    @Override
6853    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6854        if (!sUserManager.exists(userId)) return null;
6855        flags = updateFlagsForResolve(flags, userId, intent);
6856        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6857        if (query != null) {
6858            if (query.size() >= 1) {
6859                // If there is more than one service with the same priority,
6860                // just arbitrarily pick the first one.
6861                return query.get(0);
6862            }
6863        }
6864        return null;
6865    }
6866
6867    @Override
6868    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6869            String resolvedType, int flags, int userId) {
6870        return new ParceledListSlice<>(
6871                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6872    }
6873
6874    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6875            String resolvedType, int flags, int userId) {
6876        if (!sUserManager.exists(userId)) return Collections.emptyList();
6877        flags = updateFlagsForResolve(flags, userId, intent);
6878        ComponentName comp = intent.getComponent();
6879        if (comp == null) {
6880            if (intent.getSelector() != null) {
6881                intent = intent.getSelector();
6882                comp = intent.getComponent();
6883            }
6884        }
6885        if (comp != null) {
6886            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6887            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6888            if (si != null) {
6889                final ResolveInfo ri = new ResolveInfo();
6890                ri.serviceInfo = si;
6891                list.add(ri);
6892            }
6893            return list;
6894        }
6895
6896        // reader
6897        synchronized (mPackages) {
6898            String pkgName = intent.getPackage();
6899            if (pkgName == null) {
6900                return mServices.queryIntent(intent, resolvedType, flags, userId);
6901            }
6902            final PackageParser.Package pkg = mPackages.get(pkgName);
6903            if (pkg != null) {
6904                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6905                        userId);
6906            }
6907            return Collections.emptyList();
6908        }
6909    }
6910
6911    @Override
6912    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6913            String resolvedType, int flags, int userId) {
6914        return new ParceledListSlice<>(
6915                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6916    }
6917
6918    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6919            Intent intent, String resolvedType, int flags, int userId) {
6920        if (!sUserManager.exists(userId)) return Collections.emptyList();
6921        flags = updateFlagsForResolve(flags, userId, intent);
6922        ComponentName comp = intent.getComponent();
6923        if (comp == null) {
6924            if (intent.getSelector() != null) {
6925                intent = intent.getSelector();
6926                comp = intent.getComponent();
6927            }
6928        }
6929        if (comp != null) {
6930            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6931            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6932            if (pi != null) {
6933                final ResolveInfo ri = new ResolveInfo();
6934                ri.providerInfo = pi;
6935                list.add(ri);
6936            }
6937            return list;
6938        }
6939
6940        // reader
6941        synchronized (mPackages) {
6942            String pkgName = intent.getPackage();
6943            if (pkgName == null) {
6944                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6945            }
6946            final PackageParser.Package pkg = mPackages.get(pkgName);
6947            if (pkg != null) {
6948                return mProviders.queryIntentForPackage(
6949                        intent, resolvedType, flags, pkg.providers, userId);
6950            }
6951            return Collections.emptyList();
6952        }
6953    }
6954
6955    @Override
6956    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6957        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6958        flags = updateFlagsForPackage(flags, userId, null);
6959        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6960        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6961                true /* requireFullPermission */, false /* checkShell */,
6962                "get installed packages");
6963
6964        // writer
6965        synchronized (mPackages) {
6966            ArrayList<PackageInfo> list;
6967            if (listUninstalled) {
6968                list = new ArrayList<>(mSettings.mPackages.size());
6969                for (PackageSetting ps : mSettings.mPackages.values()) {
6970                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
6971                        continue;
6972                    }
6973                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
6974                    if (pi != null) {
6975                        list.add(pi);
6976                    }
6977                }
6978            } else {
6979                list = new ArrayList<>(mPackages.size());
6980                for (PackageParser.Package p : mPackages.values()) {
6981                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
6982                            Binder.getCallingUid(), userId)) {
6983                        continue;
6984                    }
6985                    final PackageInfo pi = generatePackageInfo((PackageSetting)
6986                            p.mExtras, flags, userId);
6987                    if (pi != null) {
6988                        list.add(pi);
6989                    }
6990                }
6991            }
6992
6993            return new ParceledListSlice<>(list);
6994        }
6995    }
6996
6997    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6998            String[] permissions, boolean[] tmp, int flags, int userId) {
6999        int numMatch = 0;
7000        final PermissionsState permissionsState = ps.getPermissionsState();
7001        for (int i=0; i<permissions.length; i++) {
7002            final String permission = permissions[i];
7003            if (permissionsState.hasPermission(permission, userId)) {
7004                tmp[i] = true;
7005                numMatch++;
7006            } else {
7007                tmp[i] = false;
7008            }
7009        }
7010        if (numMatch == 0) {
7011            return;
7012        }
7013        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7014
7015        // The above might return null in cases of uninstalled apps or install-state
7016        // skew across users/profiles.
7017        if (pi != null) {
7018            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7019                if (numMatch == permissions.length) {
7020                    pi.requestedPermissions = permissions;
7021                } else {
7022                    pi.requestedPermissions = new String[numMatch];
7023                    numMatch = 0;
7024                    for (int i=0; i<permissions.length; i++) {
7025                        if (tmp[i]) {
7026                            pi.requestedPermissions[numMatch] = permissions[i];
7027                            numMatch++;
7028                        }
7029                    }
7030                }
7031            }
7032            list.add(pi);
7033        }
7034    }
7035
7036    @Override
7037    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7038            String[] permissions, int flags, int userId) {
7039        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7040        flags = updateFlagsForPackage(flags, userId, permissions);
7041        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7042                true /* requireFullPermission */, false /* checkShell */,
7043                "get packages holding permissions");
7044        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7045
7046        // writer
7047        synchronized (mPackages) {
7048            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7049            boolean[] tmpBools = new boolean[permissions.length];
7050            if (listUninstalled) {
7051                for (PackageSetting ps : mSettings.mPackages.values()) {
7052                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7053                            userId);
7054                }
7055            } else {
7056                for (PackageParser.Package pkg : mPackages.values()) {
7057                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7058                    if (ps != null) {
7059                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7060                                userId);
7061                    }
7062                }
7063            }
7064
7065            return new ParceledListSlice<PackageInfo>(list);
7066        }
7067    }
7068
7069    @Override
7070    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7071        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7072        flags = updateFlagsForApplication(flags, userId, null);
7073        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7074
7075        // writer
7076        synchronized (mPackages) {
7077            ArrayList<ApplicationInfo> list;
7078            if (listUninstalled) {
7079                list = new ArrayList<>(mSettings.mPackages.size());
7080                for (PackageSetting ps : mSettings.mPackages.values()) {
7081                    ApplicationInfo ai;
7082                    int effectiveFlags = flags;
7083                    if (ps.isSystem()) {
7084                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7085                    }
7086                    if (ps.pkg != null) {
7087                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7088                            continue;
7089                        }
7090                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7091                                ps.readUserState(userId), userId);
7092                        if (ai != null) {
7093                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7094                        }
7095                    } else {
7096                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7097                        // and already converts to externally visible package name
7098                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7099                                Binder.getCallingUid(), effectiveFlags, userId);
7100                    }
7101                    if (ai != null) {
7102                        list.add(ai);
7103                    }
7104                }
7105            } else {
7106                list = new ArrayList<>(mPackages.size());
7107                for (PackageParser.Package p : mPackages.values()) {
7108                    if (p.mExtras != null) {
7109                        PackageSetting ps = (PackageSetting) p.mExtras;
7110                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7111                            continue;
7112                        }
7113                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7114                                ps.readUserState(userId), userId);
7115                        if (ai != null) {
7116                            ai.packageName = resolveExternalPackageNameLPr(p);
7117                            list.add(ai);
7118                        }
7119                    }
7120                }
7121            }
7122
7123            return new ParceledListSlice<>(list);
7124        }
7125    }
7126
7127    @Override
7128    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7129        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7130            return null;
7131        }
7132
7133        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7134                "getEphemeralApplications");
7135        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7136                true /* requireFullPermission */, false /* checkShell */,
7137                "getEphemeralApplications");
7138        synchronized (mPackages) {
7139            List<InstantAppInfo> instantApps = mInstantAppRegistry
7140                    .getInstantAppsLPr(userId);
7141            if (instantApps != null) {
7142                return new ParceledListSlice<>(instantApps);
7143            }
7144        }
7145        return null;
7146    }
7147
7148    @Override
7149    public boolean isInstantApp(String packageName, int userId) {
7150        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7151                true /* requireFullPermission */, false /* checkShell */,
7152                "isInstantApp");
7153        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7154            return false;
7155        }
7156
7157        if (!isCallerSameApp(packageName)) {
7158            return false;
7159        }
7160        synchronized (mPackages) {
7161            final PackageSetting ps = mSettings.mPackages.get(packageName);
7162            if (ps != null) {
7163                return ps.getInstantApp(userId);
7164            }
7165        }
7166        return false;
7167    }
7168
7169    @Override
7170    public byte[] getInstantAppCookie(String packageName, int userId) {
7171        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7172            return null;
7173        }
7174
7175        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7176                true /* requireFullPermission */, false /* checkShell */,
7177                "getInstantAppCookie");
7178        if (!isCallerSameApp(packageName)) {
7179            return null;
7180        }
7181        synchronized (mPackages) {
7182            return mInstantAppRegistry.getInstantAppCookieLPw(
7183                    packageName, userId);
7184        }
7185    }
7186
7187    @Override
7188    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7189        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7190            return true;
7191        }
7192
7193        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7194                true /* requireFullPermission */, true /* checkShell */,
7195                "setInstantAppCookie");
7196        if (!isCallerSameApp(packageName)) {
7197            return false;
7198        }
7199        synchronized (mPackages) {
7200            return mInstantAppRegistry.setInstantAppCookieLPw(
7201                    packageName, cookie, userId);
7202        }
7203    }
7204
7205    @Override
7206    public Bitmap getInstantAppIcon(String packageName, int userId) {
7207        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7208            return null;
7209        }
7210
7211        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7212                "getInstantAppIcon");
7213
7214        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7215                true /* requireFullPermission */, false /* checkShell */,
7216                "getInstantAppIcon");
7217
7218        synchronized (mPackages) {
7219            return mInstantAppRegistry.getInstantAppIconLPw(
7220                    packageName, userId);
7221        }
7222    }
7223
7224    private boolean isCallerSameApp(String packageName) {
7225        PackageParser.Package pkg = mPackages.get(packageName);
7226        return pkg != null
7227                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7228    }
7229
7230    @Override
7231    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7232        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7233    }
7234
7235    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7236        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7237
7238        // reader
7239        synchronized (mPackages) {
7240            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7241            final int userId = UserHandle.getCallingUserId();
7242            while (i.hasNext()) {
7243                final PackageParser.Package p = i.next();
7244                if (p.applicationInfo == null) continue;
7245
7246                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7247                        && !p.applicationInfo.isDirectBootAware();
7248                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7249                        && p.applicationInfo.isDirectBootAware();
7250
7251                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7252                        && (!mSafeMode || isSystemApp(p))
7253                        && (matchesUnaware || matchesAware)) {
7254                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7255                    if (ps != null) {
7256                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7257                                ps.readUserState(userId), userId);
7258                        if (ai != null) {
7259                            finalList.add(ai);
7260                        }
7261                    }
7262                }
7263            }
7264        }
7265
7266        return finalList;
7267    }
7268
7269    @Override
7270    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7271        if (!sUserManager.exists(userId)) return null;
7272        flags = updateFlagsForComponent(flags, userId, name);
7273        // reader
7274        synchronized (mPackages) {
7275            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7276            PackageSetting ps = provider != null
7277                    ? mSettings.mPackages.get(provider.owner.packageName)
7278                    : null;
7279            return ps != null
7280                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7281                    ? PackageParser.generateProviderInfo(provider, flags,
7282                            ps.readUserState(userId), userId)
7283                    : null;
7284        }
7285    }
7286
7287    /**
7288     * @deprecated
7289     */
7290    @Deprecated
7291    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7292        // reader
7293        synchronized (mPackages) {
7294            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7295                    .entrySet().iterator();
7296            final int userId = UserHandle.getCallingUserId();
7297            while (i.hasNext()) {
7298                Map.Entry<String, PackageParser.Provider> entry = i.next();
7299                PackageParser.Provider p = entry.getValue();
7300                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7301
7302                if (ps != null && p.syncable
7303                        && (!mSafeMode || (p.info.applicationInfo.flags
7304                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7305                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7306                            ps.readUserState(userId), userId);
7307                    if (info != null) {
7308                        outNames.add(entry.getKey());
7309                        outInfo.add(info);
7310                    }
7311                }
7312            }
7313        }
7314    }
7315
7316    @Override
7317    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7318            int uid, int flags) {
7319        final int userId = processName != null ? UserHandle.getUserId(uid)
7320                : UserHandle.getCallingUserId();
7321        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7322        flags = updateFlagsForComponent(flags, userId, processName);
7323
7324        ArrayList<ProviderInfo> finalList = null;
7325        // reader
7326        synchronized (mPackages) {
7327            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7328            while (i.hasNext()) {
7329                final PackageParser.Provider p = i.next();
7330                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7331                if (ps != null && p.info.authority != null
7332                        && (processName == null
7333                                || (p.info.processName.equals(processName)
7334                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7335                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7336                    if (finalList == null) {
7337                        finalList = new ArrayList<ProviderInfo>(3);
7338                    }
7339                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7340                            ps.readUserState(userId), userId);
7341                    if (info != null) {
7342                        finalList.add(info);
7343                    }
7344                }
7345            }
7346        }
7347
7348        if (finalList != null) {
7349            Collections.sort(finalList, mProviderInitOrderSorter);
7350            return new ParceledListSlice<ProviderInfo>(finalList);
7351        }
7352
7353        return ParceledListSlice.emptyList();
7354    }
7355
7356    @Override
7357    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7358        // reader
7359        synchronized (mPackages) {
7360            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7361            return PackageParser.generateInstrumentationInfo(i, flags);
7362        }
7363    }
7364
7365    @Override
7366    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7367            String targetPackage, int flags) {
7368        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7369    }
7370
7371    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7372            int flags) {
7373        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7374
7375        // reader
7376        synchronized (mPackages) {
7377            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7378            while (i.hasNext()) {
7379                final PackageParser.Instrumentation p = i.next();
7380                if (targetPackage == null
7381                        || targetPackage.equals(p.info.targetPackage)) {
7382                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7383                            flags);
7384                    if (ii != null) {
7385                        finalList.add(ii);
7386                    }
7387                }
7388            }
7389        }
7390
7391        return finalList;
7392    }
7393
7394    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
7395        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
7396        if (overlays == null) {
7397            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
7398            return;
7399        }
7400        for (PackageParser.Package opkg : overlays.values()) {
7401            // Not much to do if idmap fails: we already logged the error
7402            // and we certainly don't want to abort installation of pkg simply
7403            // because an overlay didn't fit properly. For these reasons,
7404            // ignore the return value of createIdmapForPackagePairLI.
7405            createIdmapForPackagePairLI(pkg, opkg);
7406        }
7407    }
7408
7409    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
7410            PackageParser.Package opkg) {
7411        if (!opkg.mTrustedOverlay) {
7412            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
7413                    opkg.baseCodePath + ": overlay not trusted");
7414            return false;
7415        }
7416        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
7417        if (overlaySet == null) {
7418            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
7419                    opkg.baseCodePath + " but target package has no known overlays");
7420            return false;
7421        }
7422        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7423        // TODO: generate idmap for split APKs
7424        try {
7425            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
7426        } catch (InstallerException e) {
7427            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
7428                    + opkg.baseCodePath);
7429            return false;
7430        }
7431        PackageParser.Package[] overlayArray =
7432            overlaySet.values().toArray(new PackageParser.Package[0]);
7433        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
7434            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
7435                return p1.mOverlayPriority - p2.mOverlayPriority;
7436            }
7437        };
7438        Arrays.sort(overlayArray, cmp);
7439
7440        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
7441        int i = 0;
7442        for (PackageParser.Package p : overlayArray) {
7443            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
7444        }
7445        return true;
7446    }
7447
7448    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7449        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7450        try {
7451            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7452        } finally {
7453            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7454        }
7455    }
7456
7457    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7458        final File[] files = dir.listFiles();
7459        if (ArrayUtils.isEmpty(files)) {
7460            Log.d(TAG, "No files in app dir " + dir);
7461            return;
7462        }
7463
7464        if (DEBUG_PACKAGE_SCANNING) {
7465            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7466                    + " flags=0x" + Integer.toHexString(parseFlags));
7467        }
7468        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7469                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7470
7471        // Submit files for parsing in parallel
7472        int fileCount = 0;
7473        for (File file : files) {
7474            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7475                    && !PackageInstallerService.isStageName(file.getName());
7476            if (!isPackage) {
7477                // Ignore entries which are not packages
7478                continue;
7479            }
7480            parallelPackageParser.submit(file, parseFlags);
7481            fileCount++;
7482        }
7483
7484        // Process results one by one
7485        for (; fileCount > 0; fileCount--) {
7486            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7487            Throwable throwable = parseResult.throwable;
7488            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7489
7490            if (throwable == null) {
7491                // Static shared libraries have synthetic package names
7492                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7493                    renameStaticSharedLibraryPackage(parseResult.pkg);
7494                }
7495                try {
7496                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7497                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7498                                currentTime, null);
7499                    }
7500                } catch (PackageManagerException e) {
7501                    errorCode = e.error;
7502                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7503                }
7504            } else if (throwable instanceof PackageParser.PackageParserException) {
7505                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7506                        throwable;
7507                errorCode = e.error;
7508                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7509            } else {
7510                throw new IllegalStateException("Unexpected exception occurred while parsing "
7511                        + parseResult.scanFile, throwable);
7512            }
7513
7514            // Delete invalid userdata apps
7515            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7516                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7517                logCriticalInfo(Log.WARN,
7518                        "Deleting invalid package at " + parseResult.scanFile);
7519                removeCodePathLI(parseResult.scanFile);
7520            }
7521        }
7522        parallelPackageParser.close();
7523    }
7524
7525    private static File getSettingsProblemFile() {
7526        File dataDir = Environment.getDataDirectory();
7527        File systemDir = new File(dataDir, "system");
7528        File fname = new File(systemDir, "uiderrors.txt");
7529        return fname;
7530    }
7531
7532    static void reportSettingsProblem(int priority, String msg) {
7533        logCriticalInfo(priority, msg);
7534    }
7535
7536    static void logCriticalInfo(int priority, String msg) {
7537        Slog.println(priority, TAG, msg);
7538        EventLogTags.writePmCriticalInfo(msg);
7539        try {
7540            File fname = getSettingsProblemFile();
7541            FileOutputStream out = new FileOutputStream(fname, true);
7542            PrintWriter pw = new FastPrintWriter(out);
7543            SimpleDateFormat formatter = new SimpleDateFormat();
7544            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7545            pw.println(dateString + ": " + msg);
7546            pw.close();
7547            FileUtils.setPermissions(
7548                    fname.toString(),
7549                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7550                    -1, -1);
7551        } catch (java.io.IOException e) {
7552        }
7553    }
7554
7555    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7556        if (srcFile.isDirectory()) {
7557            final File baseFile = new File(pkg.baseCodePath);
7558            long maxModifiedTime = baseFile.lastModified();
7559            if (pkg.splitCodePaths != null) {
7560                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7561                    final File splitFile = new File(pkg.splitCodePaths[i]);
7562                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7563                }
7564            }
7565            return maxModifiedTime;
7566        }
7567        return srcFile.lastModified();
7568    }
7569
7570    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7571            final int policyFlags) throws PackageManagerException {
7572        // When upgrading from pre-N MR1, verify the package time stamp using the package
7573        // directory and not the APK file.
7574        final long lastModifiedTime = mIsPreNMR1Upgrade
7575                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7576        if (ps != null
7577                && ps.codePath.equals(srcFile)
7578                && ps.timeStamp == lastModifiedTime
7579                && !isCompatSignatureUpdateNeeded(pkg)
7580                && !isRecoverSignatureUpdateNeeded(pkg)) {
7581            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7582            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7583            ArraySet<PublicKey> signingKs;
7584            synchronized (mPackages) {
7585                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7586            }
7587            if (ps.signatures.mSignatures != null
7588                    && ps.signatures.mSignatures.length != 0
7589                    && signingKs != null) {
7590                // Optimization: reuse the existing cached certificates
7591                // if the package appears to be unchanged.
7592                pkg.mSignatures = ps.signatures.mSignatures;
7593                pkg.mSigningKeys = signingKs;
7594                return;
7595            }
7596
7597            Slog.w(TAG, "PackageSetting for " + ps.name
7598                    + " is missing signatures.  Collecting certs again to recover them.");
7599        } else {
7600            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7601        }
7602
7603        try {
7604            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7605            PackageParser.collectCertificates(pkg, policyFlags);
7606        } catch (PackageParserException e) {
7607            throw PackageManagerException.from(e);
7608        } finally {
7609            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7610        }
7611    }
7612
7613    /**
7614     *  Traces a package scan.
7615     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7616     */
7617    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7618            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7619        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7620        try {
7621            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7622        } finally {
7623            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7624        }
7625    }
7626
7627    /**
7628     *  Scans a package and returns the newly parsed package.
7629     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7630     */
7631    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7632            long currentTime, UserHandle user) throws PackageManagerException {
7633        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7634        PackageParser pp = new PackageParser();
7635        pp.setSeparateProcesses(mSeparateProcesses);
7636        pp.setOnlyCoreApps(mOnlyCore);
7637        pp.setDisplayMetrics(mMetrics);
7638
7639        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7640            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7641        }
7642
7643        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7644        final PackageParser.Package pkg;
7645        try {
7646            pkg = pp.parsePackage(scanFile, parseFlags);
7647        } catch (PackageParserException e) {
7648            throw PackageManagerException.from(e);
7649        } finally {
7650            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7651        }
7652
7653        // Static shared libraries have synthetic package names
7654        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7655            renameStaticSharedLibraryPackage(pkg);
7656        }
7657
7658        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7659    }
7660
7661    /**
7662     *  Scans a package and returns the newly parsed package.
7663     *  @throws PackageManagerException on a parse error.
7664     */
7665    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7666            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7667            throws PackageManagerException {
7668        // If the package has children and this is the first dive in the function
7669        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7670        // packages (parent and children) would be successfully scanned before the
7671        // actual scan since scanning mutates internal state and we want to atomically
7672        // install the package and its children.
7673        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7674            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7675                scanFlags |= SCAN_CHECK_ONLY;
7676            }
7677        } else {
7678            scanFlags &= ~SCAN_CHECK_ONLY;
7679        }
7680
7681        // Scan the parent
7682        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7683                scanFlags, currentTime, user);
7684
7685        // Scan the children
7686        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7687        for (int i = 0; i < childCount; i++) {
7688            PackageParser.Package childPackage = pkg.childPackages.get(i);
7689            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7690                    currentTime, user);
7691        }
7692
7693
7694        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7695            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7696        }
7697
7698        return scannedPkg;
7699    }
7700
7701    /**
7702     *  Scans a package and returns the newly parsed package.
7703     *  @throws PackageManagerException on a parse error.
7704     */
7705    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7706            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7707            throws PackageManagerException {
7708        PackageSetting ps = null;
7709        PackageSetting updatedPkg;
7710        // reader
7711        synchronized (mPackages) {
7712            // Look to see if we already know about this package.
7713            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7714            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7715                // This package has been renamed to its original name.  Let's
7716                // use that.
7717                ps = mSettings.getPackageLPr(oldName);
7718            }
7719            // If there was no original package, see one for the real package name.
7720            if (ps == null) {
7721                ps = mSettings.getPackageLPr(pkg.packageName);
7722            }
7723            // Check to see if this package could be hiding/updating a system
7724            // package.  Must look for it either under the original or real
7725            // package name depending on our state.
7726            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7727            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7728
7729            // If this is a package we don't know about on the system partition, we
7730            // may need to remove disabled child packages on the system partition
7731            // or may need to not add child packages if the parent apk is updated
7732            // on the data partition and no longer defines this child package.
7733            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7734                // If this is a parent package for an updated system app and this system
7735                // app got an OTA update which no longer defines some of the child packages
7736                // we have to prune them from the disabled system packages.
7737                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7738                if (disabledPs != null) {
7739                    final int scannedChildCount = (pkg.childPackages != null)
7740                            ? pkg.childPackages.size() : 0;
7741                    final int disabledChildCount = disabledPs.childPackageNames != null
7742                            ? disabledPs.childPackageNames.size() : 0;
7743                    for (int i = 0; i < disabledChildCount; i++) {
7744                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7745                        boolean disabledPackageAvailable = false;
7746                        for (int j = 0; j < scannedChildCount; j++) {
7747                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7748                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7749                                disabledPackageAvailable = true;
7750                                break;
7751                            }
7752                         }
7753                         if (!disabledPackageAvailable) {
7754                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7755                         }
7756                    }
7757                }
7758            }
7759        }
7760
7761        boolean updatedPkgBetter = false;
7762        // First check if this is a system package that may involve an update
7763        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7764            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7765            // it needs to drop FLAG_PRIVILEGED.
7766            if (locationIsPrivileged(scanFile)) {
7767                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7768            } else {
7769                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7770            }
7771
7772            if (ps != null && !ps.codePath.equals(scanFile)) {
7773                // The path has changed from what was last scanned...  check the
7774                // version of the new path against what we have stored to determine
7775                // what to do.
7776                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7777                if (pkg.mVersionCode <= ps.versionCode) {
7778                    // The system package has been updated and the code path does not match
7779                    // Ignore entry. Skip it.
7780                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7781                            + " ignored: updated version " + ps.versionCode
7782                            + " better than this " + pkg.mVersionCode);
7783                    if (!updatedPkg.codePath.equals(scanFile)) {
7784                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7785                                + ps.name + " changing from " + updatedPkg.codePathString
7786                                + " to " + scanFile);
7787                        updatedPkg.codePath = scanFile;
7788                        updatedPkg.codePathString = scanFile.toString();
7789                        updatedPkg.resourcePath = scanFile;
7790                        updatedPkg.resourcePathString = scanFile.toString();
7791                    }
7792                    updatedPkg.pkg = pkg;
7793                    updatedPkg.versionCode = pkg.mVersionCode;
7794
7795                    // Update the disabled system child packages to point to the package too.
7796                    final int childCount = updatedPkg.childPackageNames != null
7797                            ? updatedPkg.childPackageNames.size() : 0;
7798                    for (int i = 0; i < childCount; i++) {
7799                        String childPackageName = updatedPkg.childPackageNames.get(i);
7800                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7801                                childPackageName);
7802                        if (updatedChildPkg != null) {
7803                            updatedChildPkg.pkg = pkg;
7804                            updatedChildPkg.versionCode = pkg.mVersionCode;
7805                        }
7806                    }
7807
7808                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7809                            + scanFile + " ignored: updated version " + ps.versionCode
7810                            + " better than this " + pkg.mVersionCode);
7811                } else {
7812                    // The current app on the system partition is better than
7813                    // what we have updated to on the data partition; switch
7814                    // back to the system partition version.
7815                    // At this point, its safely assumed that package installation for
7816                    // apps in system partition will go through. If not there won't be a working
7817                    // version of the app
7818                    // writer
7819                    synchronized (mPackages) {
7820                        // Just remove the loaded entries from package lists.
7821                        mPackages.remove(ps.name);
7822                    }
7823
7824                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7825                            + " reverting from " + ps.codePathString
7826                            + ": new version " + pkg.mVersionCode
7827                            + " better than installed " + ps.versionCode);
7828
7829                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7830                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7831                    synchronized (mInstallLock) {
7832                        args.cleanUpResourcesLI();
7833                    }
7834                    synchronized (mPackages) {
7835                        mSettings.enableSystemPackageLPw(ps.name);
7836                    }
7837                    updatedPkgBetter = true;
7838                }
7839            }
7840        }
7841
7842        if (updatedPkg != null) {
7843            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7844            // initially
7845            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7846
7847            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7848            // flag set initially
7849            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7850                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7851            }
7852        }
7853
7854        // Verify certificates against what was last scanned
7855        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7856
7857        /*
7858         * A new system app appeared, but we already had a non-system one of the
7859         * same name installed earlier.
7860         */
7861        boolean shouldHideSystemApp = false;
7862        if (updatedPkg == null && ps != null
7863                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7864            /*
7865             * Check to make sure the signatures match first. If they don't,
7866             * wipe the installed application and its data.
7867             */
7868            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7869                    != PackageManager.SIGNATURE_MATCH) {
7870                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7871                        + " signatures don't match existing userdata copy; removing");
7872                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7873                        "scanPackageInternalLI")) {
7874                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7875                }
7876                ps = null;
7877            } else {
7878                /*
7879                 * If the newly-added system app is an older version than the
7880                 * already installed version, hide it. It will be scanned later
7881                 * and re-added like an update.
7882                 */
7883                if (pkg.mVersionCode <= ps.versionCode) {
7884                    shouldHideSystemApp = true;
7885                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7886                            + " but new version " + pkg.mVersionCode + " better than installed "
7887                            + ps.versionCode + "; hiding system");
7888                } else {
7889                    /*
7890                     * The newly found system app is a newer version that the
7891                     * one previously installed. Simply remove the
7892                     * already-installed application and replace it with our own
7893                     * while keeping the application data.
7894                     */
7895                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7896                            + " reverting from " + ps.codePathString + ": new version "
7897                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7898                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7899                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7900                    synchronized (mInstallLock) {
7901                        args.cleanUpResourcesLI();
7902                    }
7903                }
7904            }
7905        }
7906
7907        // The apk is forward locked (not public) if its code and resources
7908        // are kept in different files. (except for app in either system or
7909        // vendor path).
7910        // TODO grab this value from PackageSettings
7911        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7912            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7913                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7914            }
7915        }
7916
7917        // TODO: extend to support forward-locked splits
7918        String resourcePath = null;
7919        String baseResourcePath = null;
7920        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7921            if (ps != null && ps.resourcePathString != null) {
7922                resourcePath = ps.resourcePathString;
7923                baseResourcePath = ps.resourcePathString;
7924            } else {
7925                // Should not happen at all. Just log an error.
7926                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7927            }
7928        } else {
7929            resourcePath = pkg.codePath;
7930            baseResourcePath = pkg.baseCodePath;
7931        }
7932
7933        // Set application objects path explicitly.
7934        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7935        pkg.setApplicationInfoCodePath(pkg.codePath);
7936        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7937        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7938        pkg.setApplicationInfoResourcePath(resourcePath);
7939        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7940        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7941
7942        final int userId = ((user == null) ? 0 : user.getIdentifier());
7943        if (ps != null && ps.getInstantApp(userId)) {
7944            scanFlags |= SCAN_AS_INSTANT_APP;
7945        }
7946
7947        // Note that we invoke the following method only if we are about to unpack an application
7948        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7949                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7950
7951        /*
7952         * If the system app should be overridden by a previously installed
7953         * data, hide the system app now and let the /data/app scan pick it up
7954         * again.
7955         */
7956        if (shouldHideSystemApp) {
7957            synchronized (mPackages) {
7958                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7959            }
7960        }
7961
7962        return scannedPkg;
7963    }
7964
7965    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
7966        // Derive the new package synthetic package name
7967        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
7968                + pkg.staticSharedLibVersion);
7969    }
7970
7971    private static String fixProcessName(String defProcessName,
7972            String processName) {
7973        if (processName == null) {
7974            return defProcessName;
7975        }
7976        return processName;
7977    }
7978
7979    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7980            throws PackageManagerException {
7981        if (pkgSetting.signatures.mSignatures != null) {
7982            // Already existing package. Make sure signatures match
7983            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7984                    == PackageManager.SIGNATURE_MATCH;
7985            if (!match) {
7986                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7987                        == PackageManager.SIGNATURE_MATCH;
7988            }
7989            if (!match) {
7990                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7991                        == PackageManager.SIGNATURE_MATCH;
7992            }
7993            if (!match) {
7994                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7995                        + pkg.packageName + " signatures do not match the "
7996                        + "previously installed version; ignoring!");
7997            }
7998        }
7999
8000        // Check for shared user signatures
8001        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8002            // Already existing package. Make sure signatures match
8003            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8004                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8005            if (!match) {
8006                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8007                        == PackageManager.SIGNATURE_MATCH;
8008            }
8009            if (!match) {
8010                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8011                        == PackageManager.SIGNATURE_MATCH;
8012            }
8013            if (!match) {
8014                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8015                        "Package " + pkg.packageName
8016                        + " has no signatures that match those in shared user "
8017                        + pkgSetting.sharedUser.name + "; ignoring!");
8018            }
8019        }
8020    }
8021
8022    /**
8023     * Enforces that only the system UID or root's UID can call a method exposed
8024     * via Binder.
8025     *
8026     * @param message used as message if SecurityException is thrown
8027     * @throws SecurityException if the caller is not system or root
8028     */
8029    private static final void enforceSystemOrRoot(String message) {
8030        final int uid = Binder.getCallingUid();
8031        if (uid != Process.SYSTEM_UID && uid != 0) {
8032            throw new SecurityException(message);
8033        }
8034    }
8035
8036    @Override
8037    public void performFstrimIfNeeded() {
8038        enforceSystemOrRoot("Only the system can request fstrim");
8039
8040        // Before everything else, see whether we need to fstrim.
8041        try {
8042            IStorageManager sm = PackageHelper.getStorageManager();
8043            if (sm != null) {
8044                boolean doTrim = false;
8045                final long interval = android.provider.Settings.Global.getLong(
8046                        mContext.getContentResolver(),
8047                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8048                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8049                if (interval > 0) {
8050                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8051                    if (timeSinceLast > interval) {
8052                        doTrim = true;
8053                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8054                                + "; running immediately");
8055                    }
8056                }
8057                if (doTrim) {
8058                    final boolean dexOptDialogShown;
8059                    synchronized (mPackages) {
8060                        dexOptDialogShown = mDexOptDialogShown;
8061                    }
8062                    if (!isFirstBoot() && dexOptDialogShown) {
8063                        try {
8064                            ActivityManager.getService().showBootMessage(
8065                                    mContext.getResources().getString(
8066                                            R.string.android_upgrading_fstrim), true);
8067                        } catch (RemoteException e) {
8068                        }
8069                    }
8070                    sm.runMaintenance();
8071                }
8072            } else {
8073                Slog.e(TAG, "storageManager service unavailable!");
8074            }
8075        } catch (RemoteException e) {
8076            // Can't happen; StorageManagerService is local
8077        }
8078    }
8079
8080    @Override
8081    public void updatePackagesIfNeeded() {
8082        enforceSystemOrRoot("Only the system can request package update");
8083
8084        // We need to re-extract after an OTA.
8085        boolean causeUpgrade = isUpgrade();
8086
8087        // First boot or factory reset.
8088        // Note: we also handle devices that are upgrading to N right now as if it is their
8089        //       first boot, as they do not have profile data.
8090        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8091
8092        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8093        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8094
8095        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8096            return;
8097        }
8098
8099        List<PackageParser.Package> pkgs;
8100        synchronized (mPackages) {
8101            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8102        }
8103
8104        final long startTime = System.nanoTime();
8105        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8106                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8107
8108        final int elapsedTimeSeconds =
8109                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8110
8111        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8112        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8113        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8114        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8115        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8116    }
8117
8118    /**
8119     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8120     * containing statistics about the invocation. The array consists of three elements,
8121     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8122     * and {@code numberOfPackagesFailed}.
8123     */
8124    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8125            String compilerFilter) {
8126
8127        int numberOfPackagesVisited = 0;
8128        int numberOfPackagesOptimized = 0;
8129        int numberOfPackagesSkipped = 0;
8130        int numberOfPackagesFailed = 0;
8131        final int numberOfPackagesToDexopt = pkgs.size();
8132
8133        for (PackageParser.Package pkg : pkgs) {
8134            numberOfPackagesVisited++;
8135
8136            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8137                if (DEBUG_DEXOPT) {
8138                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8139                }
8140                numberOfPackagesSkipped++;
8141                continue;
8142            }
8143
8144            if (DEBUG_DEXOPT) {
8145                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8146                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8147            }
8148
8149            if (showDialog) {
8150                try {
8151                    ActivityManager.getService().showBootMessage(
8152                            mContext.getResources().getString(R.string.android_upgrading_apk,
8153                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8154                } catch (RemoteException e) {
8155                }
8156                synchronized (mPackages) {
8157                    mDexOptDialogShown = true;
8158                }
8159            }
8160
8161            // If the OTA updates a system app which was previously preopted to a non-preopted state
8162            // the app might end up being verified at runtime. That's because by default the apps
8163            // are verify-profile but for preopted apps there's no profile.
8164            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8165            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8166            // filter (by default interpret-only).
8167            // Note that at this stage unused apps are already filtered.
8168            if (isSystemApp(pkg) &&
8169                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8170                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8171                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8172            }
8173
8174            // checkProfiles is false to avoid merging profiles during boot which
8175            // might interfere with background compilation (b/28612421).
8176            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8177            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8178            // trade-off worth doing to save boot time work.
8179            int dexOptStatus = performDexOptTraced(pkg.packageName,
8180                    false /* checkProfiles */,
8181                    compilerFilter,
8182                    false /* force */);
8183            switch (dexOptStatus) {
8184                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8185                    numberOfPackagesOptimized++;
8186                    break;
8187                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8188                    numberOfPackagesSkipped++;
8189                    break;
8190                case PackageDexOptimizer.DEX_OPT_FAILED:
8191                    numberOfPackagesFailed++;
8192                    break;
8193                default:
8194                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8195                    break;
8196            }
8197        }
8198
8199        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8200                numberOfPackagesFailed };
8201    }
8202
8203    @Override
8204    public void notifyPackageUse(String packageName, int reason) {
8205        synchronized (mPackages) {
8206            PackageParser.Package p = mPackages.get(packageName);
8207            if (p == null) {
8208                return;
8209            }
8210            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8211        }
8212    }
8213
8214    @Override
8215    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8216        int userId = UserHandle.getCallingUserId();
8217        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8218        if (ai == null) {
8219            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8220                + loadingPackageName + ", user=" + userId);
8221            return;
8222        }
8223        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8224    }
8225
8226    // TODO: this is not used nor needed. Delete it.
8227    @Override
8228    public boolean performDexOptIfNeeded(String packageName) {
8229        int dexOptStatus = performDexOptTraced(packageName,
8230                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8231        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8232    }
8233
8234    @Override
8235    public boolean performDexOpt(String packageName,
8236            boolean checkProfiles, int compileReason, boolean force) {
8237        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8238                getCompilerFilterForReason(compileReason), force);
8239        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8240    }
8241
8242    @Override
8243    public boolean performDexOptMode(String packageName,
8244            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8245        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8246                targetCompilerFilter, force);
8247        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8248    }
8249
8250    private int performDexOptTraced(String packageName,
8251                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8252        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8253        try {
8254            return performDexOptInternal(packageName, checkProfiles,
8255                    targetCompilerFilter, force);
8256        } finally {
8257            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8258        }
8259    }
8260
8261    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8262    // if the package can now be considered up to date for the given filter.
8263    private int performDexOptInternal(String packageName,
8264                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8265        PackageParser.Package p;
8266        synchronized (mPackages) {
8267            p = mPackages.get(packageName);
8268            if (p == null) {
8269                // Package could not be found. Report failure.
8270                return PackageDexOptimizer.DEX_OPT_FAILED;
8271            }
8272            mPackageUsage.maybeWriteAsync(mPackages);
8273            mCompilerStats.maybeWriteAsync();
8274        }
8275        long callingId = Binder.clearCallingIdentity();
8276        try {
8277            synchronized (mInstallLock) {
8278                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8279                        targetCompilerFilter, force);
8280            }
8281        } finally {
8282            Binder.restoreCallingIdentity(callingId);
8283        }
8284    }
8285
8286    public ArraySet<String> getOptimizablePackages() {
8287        ArraySet<String> pkgs = new ArraySet<String>();
8288        synchronized (mPackages) {
8289            for (PackageParser.Package p : mPackages.values()) {
8290                if (PackageDexOptimizer.canOptimizePackage(p)) {
8291                    pkgs.add(p.packageName);
8292                }
8293            }
8294        }
8295        return pkgs;
8296    }
8297
8298    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8299            boolean checkProfiles, String targetCompilerFilter,
8300            boolean force) {
8301        // Select the dex optimizer based on the force parameter.
8302        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8303        //       allocate an object here.
8304        PackageDexOptimizer pdo = force
8305                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8306                : mPackageDexOptimizer;
8307
8308        // Optimize all dependencies first. Note: we ignore the return value and march on
8309        // on errors.
8310        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8311        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8312        if (!deps.isEmpty()) {
8313            for (PackageParser.Package depPackage : deps) {
8314                // TODO: Analyze and investigate if we (should) profile libraries.
8315                // Currently this will do a full compilation of the library by default.
8316                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8317                        false /* checkProfiles */,
8318                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8319                        getOrCreateCompilerPackageStats(depPackage));
8320            }
8321        }
8322        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8323                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
8324    }
8325
8326    // Performs dexopt on the used secondary dex files belonging to the given package.
8327    // Returns true if all dex files were process successfully (which could mean either dexopt or
8328    // skip). Returns false if any of the files caused errors.
8329    @Override
8330    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8331            boolean force) {
8332        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8333    }
8334
8335    /**
8336     * Reconcile the information we have about the secondary dex files belonging to
8337     * {@code packagName} and the actual dex files. For all dex files that were
8338     * deleted, update the internal records and delete the generated oat files.
8339     */
8340    @Override
8341    public void reconcileSecondaryDexFiles(String packageName) {
8342        mDexManager.reconcileSecondaryDexFiles(packageName);
8343    }
8344
8345    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8346    // a reference there.
8347    /*package*/ DexManager getDexManager() {
8348        return mDexManager;
8349    }
8350
8351    /**
8352     * Execute the background dexopt job immediately.
8353     */
8354    @Override
8355    public boolean runBackgroundDexoptJob() {
8356        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8357    }
8358
8359    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8360        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8361                || p.usesStaticLibraries != null) {
8362            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8363            Set<String> collectedNames = new HashSet<>();
8364            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8365
8366            retValue.remove(p);
8367
8368            return retValue;
8369        } else {
8370            return Collections.emptyList();
8371        }
8372    }
8373
8374    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8375            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8376        if (!collectedNames.contains(p.packageName)) {
8377            collectedNames.add(p.packageName);
8378            collected.add(p);
8379
8380            if (p.usesLibraries != null) {
8381                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8382                        null, collected, collectedNames);
8383            }
8384            if (p.usesOptionalLibraries != null) {
8385                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8386                        null, collected, collectedNames);
8387            }
8388            if (p.usesStaticLibraries != null) {
8389                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8390                        p.usesStaticLibrariesVersions, collected, collectedNames);
8391            }
8392        }
8393    }
8394
8395    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8396            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8397        final int libNameCount = libs.size();
8398        for (int i = 0; i < libNameCount; i++) {
8399            String libName = libs.get(i);
8400            int version = (versions != null && versions.length == libNameCount)
8401                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8402            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8403            if (libPkg != null) {
8404                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8405            }
8406        }
8407    }
8408
8409    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8410        synchronized (mPackages) {
8411            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8412            if (libEntry != null) {
8413                return mPackages.get(libEntry.apk);
8414            }
8415            return null;
8416        }
8417    }
8418
8419    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8420        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8421        if (versionedLib == null) {
8422            return null;
8423        }
8424        return versionedLib.get(version);
8425    }
8426
8427    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8428        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8429                pkg.staticSharedLibName);
8430        if (versionedLib == null) {
8431            return null;
8432        }
8433        int previousLibVersion = -1;
8434        final int versionCount = versionedLib.size();
8435        for (int i = 0; i < versionCount; i++) {
8436            final int libVersion = versionedLib.keyAt(i);
8437            if (libVersion < pkg.staticSharedLibVersion) {
8438                previousLibVersion = Math.max(previousLibVersion, libVersion);
8439            }
8440        }
8441        if (previousLibVersion >= 0) {
8442            return versionedLib.get(previousLibVersion);
8443        }
8444        return null;
8445    }
8446
8447    public void shutdown() {
8448        mPackageUsage.writeNow(mPackages);
8449        mCompilerStats.writeNow();
8450    }
8451
8452    @Override
8453    public void dumpProfiles(String packageName) {
8454        PackageParser.Package pkg;
8455        synchronized (mPackages) {
8456            pkg = mPackages.get(packageName);
8457            if (pkg == null) {
8458                throw new IllegalArgumentException("Unknown package: " + packageName);
8459            }
8460        }
8461        /* Only the shell, root, or the app user should be able to dump profiles. */
8462        int callingUid = Binder.getCallingUid();
8463        if (callingUid != Process.SHELL_UID &&
8464            callingUid != Process.ROOT_UID &&
8465            callingUid != pkg.applicationInfo.uid) {
8466            throw new SecurityException("dumpProfiles");
8467        }
8468
8469        synchronized (mInstallLock) {
8470            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8471            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8472            try {
8473                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8474                String codePaths = TextUtils.join(";", allCodePaths);
8475                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8476            } catch (InstallerException e) {
8477                Slog.w(TAG, "Failed to dump profiles", e);
8478            }
8479            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8480        }
8481    }
8482
8483    @Override
8484    public void forceDexOpt(String packageName) {
8485        enforceSystemOrRoot("forceDexOpt");
8486
8487        PackageParser.Package pkg;
8488        synchronized (mPackages) {
8489            pkg = mPackages.get(packageName);
8490            if (pkg == null) {
8491                throw new IllegalArgumentException("Unknown package: " + packageName);
8492            }
8493        }
8494
8495        synchronized (mInstallLock) {
8496            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8497
8498            // Whoever is calling forceDexOpt wants a fully compiled package.
8499            // Don't use profiles since that may cause compilation to be skipped.
8500            final int res = performDexOptInternalWithDependenciesLI(pkg,
8501                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8502                    true /* force */);
8503
8504            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8505            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8506                throw new IllegalStateException("Failed to dexopt: " + res);
8507            }
8508        }
8509    }
8510
8511    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8512        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8513            Slog.w(TAG, "Unable to update from " + oldPkg.name
8514                    + " to " + newPkg.packageName
8515                    + ": old package not in system partition");
8516            return false;
8517        } else if (mPackages.get(oldPkg.name) != null) {
8518            Slog.w(TAG, "Unable to update from " + oldPkg.name
8519                    + " to " + newPkg.packageName
8520                    + ": old package still exists");
8521            return false;
8522        }
8523        return true;
8524    }
8525
8526    void removeCodePathLI(File codePath) {
8527        if (codePath.isDirectory()) {
8528            try {
8529                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8530            } catch (InstallerException e) {
8531                Slog.w(TAG, "Failed to remove code path", e);
8532            }
8533        } else {
8534            codePath.delete();
8535        }
8536    }
8537
8538    private int[] resolveUserIds(int userId) {
8539        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8540    }
8541
8542    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8543        if (pkg == null) {
8544            Slog.wtf(TAG, "Package was null!", new Throwable());
8545            return;
8546        }
8547        clearAppDataLeafLIF(pkg, userId, flags);
8548        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8549        for (int i = 0; i < childCount; i++) {
8550            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8551        }
8552    }
8553
8554    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8555        final PackageSetting ps;
8556        synchronized (mPackages) {
8557            ps = mSettings.mPackages.get(pkg.packageName);
8558        }
8559        for (int realUserId : resolveUserIds(userId)) {
8560            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8561            try {
8562                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8563                        ceDataInode);
8564            } catch (InstallerException e) {
8565                Slog.w(TAG, String.valueOf(e));
8566            }
8567        }
8568    }
8569
8570    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8571        if (pkg == null) {
8572            Slog.wtf(TAG, "Package was null!", new Throwable());
8573            return;
8574        }
8575        destroyAppDataLeafLIF(pkg, userId, flags);
8576        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8577        for (int i = 0; i < childCount; i++) {
8578            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8579        }
8580    }
8581
8582    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8583        final PackageSetting ps;
8584        synchronized (mPackages) {
8585            ps = mSettings.mPackages.get(pkg.packageName);
8586        }
8587        for (int realUserId : resolveUserIds(userId)) {
8588            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8589            try {
8590                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8591                        ceDataInode);
8592            } catch (InstallerException e) {
8593                Slog.w(TAG, String.valueOf(e));
8594            }
8595        }
8596    }
8597
8598    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8599        if (pkg == null) {
8600            Slog.wtf(TAG, "Package was null!", new Throwable());
8601            return;
8602        }
8603        destroyAppProfilesLeafLIF(pkg);
8604        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8605        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8606        for (int i = 0; i < childCount; i++) {
8607            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8608            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8609                    true /* removeBaseMarker */);
8610        }
8611    }
8612
8613    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8614            boolean removeBaseMarker) {
8615        if (pkg.isForwardLocked()) {
8616            return;
8617        }
8618
8619        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8620            try {
8621                path = PackageManagerServiceUtils.realpath(new File(path));
8622            } catch (IOException e) {
8623                // TODO: Should we return early here ?
8624                Slog.w(TAG, "Failed to get canonical path", e);
8625                continue;
8626            }
8627
8628            final String useMarker = path.replace('/', '@');
8629            for (int realUserId : resolveUserIds(userId)) {
8630                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8631                if (removeBaseMarker) {
8632                    File foreignUseMark = new File(profileDir, useMarker);
8633                    if (foreignUseMark.exists()) {
8634                        if (!foreignUseMark.delete()) {
8635                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8636                                    + pkg.packageName);
8637                        }
8638                    }
8639                }
8640
8641                File[] markers = profileDir.listFiles();
8642                if (markers != null) {
8643                    final String searchString = "@" + pkg.packageName + "@";
8644                    // We also delete all markers that contain the package name we're
8645                    // uninstalling. These are associated with secondary dex-files belonging
8646                    // to the package. Reconstructing the path of these dex files is messy
8647                    // in general.
8648                    for (File marker : markers) {
8649                        if (marker.getName().indexOf(searchString) > 0) {
8650                            if (!marker.delete()) {
8651                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8652                                    + pkg.packageName);
8653                            }
8654                        }
8655                    }
8656                }
8657            }
8658        }
8659    }
8660
8661    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8662        try {
8663            mInstaller.destroyAppProfiles(pkg.packageName);
8664        } catch (InstallerException e) {
8665            Slog.w(TAG, String.valueOf(e));
8666        }
8667    }
8668
8669    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8670        if (pkg == null) {
8671            Slog.wtf(TAG, "Package was null!", new Throwable());
8672            return;
8673        }
8674        clearAppProfilesLeafLIF(pkg);
8675        // We don't remove the base foreign use marker when clearing profiles because
8676        // we will rename it when the app is updated. Unlike the actual profile contents,
8677        // the foreign use marker is good across installs.
8678        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8679        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8680        for (int i = 0; i < childCount; i++) {
8681            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8682        }
8683    }
8684
8685    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8686        try {
8687            mInstaller.clearAppProfiles(pkg.packageName);
8688        } catch (InstallerException e) {
8689            Slog.w(TAG, String.valueOf(e));
8690        }
8691    }
8692
8693    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8694            long lastUpdateTime) {
8695        // Set parent install/update time
8696        PackageSetting ps = (PackageSetting) pkg.mExtras;
8697        if (ps != null) {
8698            ps.firstInstallTime = firstInstallTime;
8699            ps.lastUpdateTime = lastUpdateTime;
8700        }
8701        // Set children install/update time
8702        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8703        for (int i = 0; i < childCount; i++) {
8704            PackageParser.Package childPkg = pkg.childPackages.get(i);
8705            ps = (PackageSetting) childPkg.mExtras;
8706            if (ps != null) {
8707                ps.firstInstallTime = firstInstallTime;
8708                ps.lastUpdateTime = lastUpdateTime;
8709            }
8710        }
8711    }
8712
8713    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8714            PackageParser.Package changingLib) {
8715        if (file.path != null) {
8716            usesLibraryFiles.add(file.path);
8717            return;
8718        }
8719        PackageParser.Package p = mPackages.get(file.apk);
8720        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8721            // If we are doing this while in the middle of updating a library apk,
8722            // then we need to make sure to use that new apk for determining the
8723            // dependencies here.  (We haven't yet finished committing the new apk
8724            // to the package manager state.)
8725            if (p == null || p.packageName.equals(changingLib.packageName)) {
8726                p = changingLib;
8727            }
8728        }
8729        if (p != null) {
8730            usesLibraryFiles.addAll(p.getAllCodePaths());
8731        }
8732    }
8733
8734    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8735            PackageParser.Package changingLib) throws PackageManagerException {
8736        if (pkg == null) {
8737            return;
8738        }
8739        ArraySet<String> usesLibraryFiles = null;
8740        if (pkg.usesLibraries != null) {
8741            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8742                    null, null, pkg.packageName, changingLib, true, null);
8743        }
8744        if (pkg.usesStaticLibraries != null) {
8745            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8746                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8747                    pkg.packageName, changingLib, true, usesLibraryFiles);
8748        }
8749        if (pkg.usesOptionalLibraries != null) {
8750            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8751                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8752        }
8753        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8754            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8755        } else {
8756            pkg.usesLibraryFiles = null;
8757        }
8758    }
8759
8760    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8761            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8762            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8763            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8764            throws PackageManagerException {
8765        final int libCount = requestedLibraries.size();
8766        for (int i = 0; i < libCount; i++) {
8767            final String libName = requestedLibraries.get(i);
8768            final int libVersion = requiredVersions != null ? requiredVersions[i]
8769                    : SharedLibraryInfo.VERSION_UNDEFINED;
8770            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8771            if (libEntry == null) {
8772                if (required) {
8773                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8774                            "Package " + packageName + " requires unavailable shared library "
8775                                    + libName + "; failing!");
8776                } else {
8777                    Slog.w(TAG, "Package " + packageName
8778                            + " desires unavailable shared library "
8779                            + libName + "; ignoring!");
8780                }
8781            } else {
8782                if (requiredVersions != null && requiredCertDigests != null) {
8783                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8784                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8785                            "Package " + packageName + " requires unavailable static shared"
8786                                    + " library " + libName + " version "
8787                                    + libEntry.info.getVersion() + "; failing!");
8788                    }
8789
8790                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8791                    if (libPkg == null) {
8792                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8793                                "Package " + packageName + " requires unavailable static shared"
8794                                        + " library; failing!");
8795                    }
8796
8797                    String expectedCertDigest = requiredCertDigests[i];
8798                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8799                                libPkg.mSignatures[0]);
8800                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8801                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8802                                "Package " + packageName + " requires differently signed" +
8803                                        " static shared library; failing!");
8804                    }
8805                }
8806
8807                if (outUsedLibraries == null) {
8808                    outUsedLibraries = new ArraySet<>();
8809                }
8810                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8811            }
8812        }
8813        return outUsedLibraries;
8814    }
8815
8816    private static boolean hasString(List<String> list, List<String> which) {
8817        if (list == null) {
8818            return false;
8819        }
8820        for (int i=list.size()-1; i>=0; i--) {
8821            for (int j=which.size()-1; j>=0; j--) {
8822                if (which.get(j).equals(list.get(i))) {
8823                    return true;
8824                }
8825            }
8826        }
8827        return false;
8828    }
8829
8830    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8831            PackageParser.Package changingPkg) {
8832        ArrayList<PackageParser.Package> res = null;
8833        for (PackageParser.Package pkg : mPackages.values()) {
8834            if (changingPkg != null
8835                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8836                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8837                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8838                            changingPkg.staticSharedLibName)) {
8839                return null;
8840            }
8841            if (res == null) {
8842                res = new ArrayList<>();
8843            }
8844            res.add(pkg);
8845            try {
8846                updateSharedLibrariesLPr(pkg, changingPkg);
8847            } catch (PackageManagerException e) {
8848                // If a system app update or an app and a required lib missing we
8849                // delete the package and for updated system apps keep the data as
8850                // it is better for the user to reinstall than to be in an limbo
8851                // state. Also libs disappearing under an app should never happen
8852                // - just in case.
8853                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8854                    final int flags = pkg.isUpdatedSystemApp()
8855                            ? PackageManager.DELETE_KEEP_DATA : 0;
8856                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8857                            flags , null, true, null);
8858                }
8859                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8860            }
8861        }
8862        return res;
8863    }
8864
8865    /**
8866     * Derive the value of the {@code cpuAbiOverride} based on the provided
8867     * value and an optional stored value from the package settings.
8868     */
8869    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8870        String cpuAbiOverride = null;
8871
8872        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8873            cpuAbiOverride = null;
8874        } else if (abiOverride != null) {
8875            cpuAbiOverride = abiOverride;
8876        } else if (settings != null) {
8877            cpuAbiOverride = settings.cpuAbiOverrideString;
8878        }
8879
8880        return cpuAbiOverride;
8881    }
8882
8883    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8884            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8885                    throws PackageManagerException {
8886        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8887        // If the package has children and this is the first dive in the function
8888        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8889        // whether all packages (parent and children) would be successfully scanned
8890        // before the actual scan since scanning mutates internal state and we want
8891        // to atomically install the package and its children.
8892        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8893            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8894                scanFlags |= SCAN_CHECK_ONLY;
8895            }
8896        } else {
8897            scanFlags &= ~SCAN_CHECK_ONLY;
8898        }
8899
8900        final PackageParser.Package scannedPkg;
8901        try {
8902            // Scan the parent
8903            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8904            // Scan the children
8905            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8906            for (int i = 0; i < childCount; i++) {
8907                PackageParser.Package childPkg = pkg.childPackages.get(i);
8908                scanPackageLI(childPkg, policyFlags,
8909                        scanFlags, currentTime, user);
8910            }
8911        } finally {
8912            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8913        }
8914
8915        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8916            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8917        }
8918
8919        return scannedPkg;
8920    }
8921
8922    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8923            int scanFlags, long currentTime, @Nullable UserHandle user)
8924                    throws PackageManagerException {
8925        boolean success = false;
8926        try {
8927            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8928                    currentTime, user);
8929            success = true;
8930            return res;
8931        } finally {
8932            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8933                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8934                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8935                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8936                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8937            }
8938        }
8939    }
8940
8941    /**
8942     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8943     */
8944    private static boolean apkHasCode(String fileName) {
8945        StrictJarFile jarFile = null;
8946        try {
8947            jarFile = new StrictJarFile(fileName,
8948                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8949            return jarFile.findEntry("classes.dex") != null;
8950        } catch (IOException ignore) {
8951        } finally {
8952            try {
8953                if (jarFile != null) {
8954                    jarFile.close();
8955                }
8956            } catch (IOException ignore) {}
8957        }
8958        return false;
8959    }
8960
8961    /**
8962     * Enforces code policy for the package. This ensures that if an APK has
8963     * declared hasCode="true" in its manifest that the APK actually contains
8964     * code.
8965     *
8966     * @throws PackageManagerException If bytecode could not be found when it should exist
8967     */
8968    private static void assertCodePolicy(PackageParser.Package pkg)
8969            throws PackageManagerException {
8970        final boolean shouldHaveCode =
8971                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8972        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8973            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8974                    "Package " + pkg.baseCodePath + " code is missing");
8975        }
8976
8977        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8978            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8979                final boolean splitShouldHaveCode =
8980                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8981                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8982                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8983                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8984                }
8985            }
8986        }
8987    }
8988
8989    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8990            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
8991                    throws PackageManagerException {
8992        if (DEBUG_PACKAGE_SCANNING) {
8993            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8994                Log.d(TAG, "Scanning package " + pkg.packageName);
8995        }
8996
8997        applyPolicy(pkg, policyFlags);
8998
8999        assertPackageIsValid(pkg, policyFlags, scanFlags);
9000
9001        // Initialize package source and resource directories
9002        final File scanFile = new File(pkg.codePath);
9003        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9004        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9005
9006        SharedUserSetting suid = null;
9007        PackageSetting pkgSetting = null;
9008
9009        // Getting the package setting may have a side-effect, so if we
9010        // are only checking if scan would succeed, stash a copy of the
9011        // old setting to restore at the end.
9012        PackageSetting nonMutatedPs = null;
9013
9014        // We keep references to the derived CPU Abis from settings in oder to reuse
9015        // them in the case where we're not upgrading or booting for the first time.
9016        String primaryCpuAbiFromSettings = null;
9017        String secondaryCpuAbiFromSettings = null;
9018
9019        // writer
9020        synchronized (mPackages) {
9021            if (pkg.mSharedUserId != null) {
9022                // SIDE EFFECTS; may potentially allocate a new shared user
9023                suid = mSettings.getSharedUserLPw(
9024                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9025                if (DEBUG_PACKAGE_SCANNING) {
9026                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9027                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9028                                + "): packages=" + suid.packages);
9029                }
9030            }
9031
9032            // Check if we are renaming from an original package name.
9033            PackageSetting origPackage = null;
9034            String realName = null;
9035            if (pkg.mOriginalPackages != null) {
9036                // This package may need to be renamed to a previously
9037                // installed name.  Let's check on that...
9038                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9039                if (pkg.mOriginalPackages.contains(renamed)) {
9040                    // This package had originally been installed as the
9041                    // original name, and we have already taken care of
9042                    // transitioning to the new one.  Just update the new
9043                    // one to continue using the old name.
9044                    realName = pkg.mRealPackage;
9045                    if (!pkg.packageName.equals(renamed)) {
9046                        // Callers into this function may have already taken
9047                        // care of renaming the package; only do it here if
9048                        // it is not already done.
9049                        pkg.setPackageName(renamed);
9050                    }
9051                } else {
9052                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9053                        if ((origPackage = mSettings.getPackageLPr(
9054                                pkg.mOriginalPackages.get(i))) != null) {
9055                            // We do have the package already installed under its
9056                            // original name...  should we use it?
9057                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9058                                // New package is not compatible with original.
9059                                origPackage = null;
9060                                continue;
9061                            } else if (origPackage.sharedUser != null) {
9062                                // Make sure uid is compatible between packages.
9063                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9064                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9065                                            + " to " + pkg.packageName + ": old uid "
9066                                            + origPackage.sharedUser.name
9067                                            + " differs from " + pkg.mSharedUserId);
9068                                    origPackage = null;
9069                                    continue;
9070                                }
9071                                // TODO: Add case when shared user id is added [b/28144775]
9072                            } else {
9073                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9074                                        + pkg.packageName + " to old name " + origPackage.name);
9075                            }
9076                            break;
9077                        }
9078                    }
9079                }
9080            }
9081
9082            if (mTransferedPackages.contains(pkg.packageName)) {
9083                Slog.w(TAG, "Package " + pkg.packageName
9084                        + " was transferred to another, but its .apk remains");
9085            }
9086
9087            // See comments in nonMutatedPs declaration
9088            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9089                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9090                if (foundPs != null) {
9091                    nonMutatedPs = new PackageSetting(foundPs);
9092                }
9093            }
9094
9095            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9096                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9097                if (foundPs != null) {
9098                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9099                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9100                }
9101            }
9102
9103            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9104            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9105                PackageManagerService.reportSettingsProblem(Log.WARN,
9106                        "Package " + pkg.packageName + " shared user changed from "
9107                                + (pkgSetting.sharedUser != null
9108                                        ? pkgSetting.sharedUser.name : "<nothing>")
9109                                + " to "
9110                                + (suid != null ? suid.name : "<nothing>")
9111                                + "; replacing with new");
9112                pkgSetting = null;
9113            }
9114            final PackageSetting oldPkgSetting =
9115                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9116            final PackageSetting disabledPkgSetting =
9117                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9118
9119            String[] usesStaticLibraries = null;
9120            if (pkg.usesStaticLibraries != null) {
9121                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9122                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9123            }
9124
9125            if (pkgSetting == null) {
9126                final String parentPackageName = (pkg.parentPackage != null)
9127                        ? pkg.parentPackage.packageName : null;
9128                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9129                // REMOVE SharedUserSetting from method; update in a separate call
9130                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9131                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9132                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9133                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9134                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9135                        true /*allowInstall*/, instantApp, parentPackageName,
9136                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9137                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9138                // SIDE EFFECTS; updates system state; move elsewhere
9139                if (origPackage != null) {
9140                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9141                }
9142                mSettings.addUserToSettingLPw(pkgSetting);
9143            } else {
9144                // REMOVE SharedUserSetting from method; update in a separate call.
9145                //
9146                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9147                // secondaryCpuAbi are not known at this point so we always update them
9148                // to null here, only to reset them at a later point.
9149                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9150                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9151                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9152                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9153                        UserManagerService.getInstance(), usesStaticLibraries,
9154                        pkg.usesStaticLibrariesVersions);
9155            }
9156            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9157            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9158
9159            // SIDE EFFECTS; modifies system state; move elsewhere
9160            if (pkgSetting.origPackage != null) {
9161                // If we are first transitioning from an original package,
9162                // fix up the new package's name now.  We need to do this after
9163                // looking up the package under its new name, so getPackageLP
9164                // can take care of fiddling things correctly.
9165                pkg.setPackageName(origPackage.name);
9166
9167                // File a report about this.
9168                String msg = "New package " + pkgSetting.realName
9169                        + " renamed to replace old package " + pkgSetting.name;
9170                reportSettingsProblem(Log.WARN, msg);
9171
9172                // Make a note of it.
9173                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9174                    mTransferedPackages.add(origPackage.name);
9175                }
9176
9177                // No longer need to retain this.
9178                pkgSetting.origPackage = null;
9179            }
9180
9181            // SIDE EFFECTS; modifies system state; move elsewhere
9182            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9183                // Make a note of it.
9184                mTransferedPackages.add(pkg.packageName);
9185            }
9186
9187            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9188                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9189            }
9190
9191            if ((scanFlags & SCAN_BOOTING) == 0
9192                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9193                // Check all shared libraries and map to their actual file path.
9194                // We only do this here for apps not on a system dir, because those
9195                // are the only ones that can fail an install due to this.  We
9196                // will take care of the system apps by updating all of their
9197                // library paths after the scan is done. Also during the initial
9198                // scan don't update any libs as we do this wholesale after all
9199                // apps are scanned to avoid dependency based scanning.
9200                updateSharedLibrariesLPr(pkg, null);
9201            }
9202
9203            if (mFoundPolicyFile) {
9204                SELinuxMMAC.assignSeInfoValue(pkg);
9205            }
9206            pkg.applicationInfo.uid = pkgSetting.appId;
9207            pkg.mExtras = pkgSetting;
9208
9209
9210            // Static shared libs have same package with different versions where
9211            // we internally use a synthetic package name to allow multiple versions
9212            // of the same package, therefore we need to compare signatures against
9213            // the package setting for the latest library version.
9214            PackageSetting signatureCheckPs = pkgSetting;
9215            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9216                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9217                if (libraryEntry != null) {
9218                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9219                }
9220            }
9221
9222            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9223                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9224                    // We just determined the app is signed correctly, so bring
9225                    // over the latest parsed certs.
9226                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9227                } else {
9228                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9229                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9230                                "Package " + pkg.packageName + " upgrade keys do not match the "
9231                                + "previously installed version");
9232                    } else {
9233                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9234                        String msg = "System package " + pkg.packageName
9235                                + " signature changed; retaining data.";
9236                        reportSettingsProblem(Log.WARN, msg);
9237                    }
9238                }
9239            } else {
9240                try {
9241                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9242                    verifySignaturesLP(signatureCheckPs, pkg);
9243                    // We just determined the app is signed correctly, so bring
9244                    // over the latest parsed certs.
9245                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9246                } catch (PackageManagerException e) {
9247                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9248                        throw e;
9249                    }
9250                    // The signature has changed, but this package is in the system
9251                    // image...  let's recover!
9252                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9253                    // However...  if this package is part of a shared user, but it
9254                    // doesn't match the signature of the shared user, let's fail.
9255                    // What this means is that you can't change the signatures
9256                    // associated with an overall shared user, which doesn't seem all
9257                    // that unreasonable.
9258                    if (signatureCheckPs.sharedUser != null) {
9259                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9260                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9261                            throw new PackageManagerException(
9262                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9263                                    "Signature mismatch for shared user: "
9264                                            + pkgSetting.sharedUser);
9265                        }
9266                    }
9267                    // File a report about this.
9268                    String msg = "System package " + pkg.packageName
9269                            + " signature changed; retaining data.";
9270                    reportSettingsProblem(Log.WARN, msg);
9271                }
9272            }
9273
9274            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9275                // This package wants to adopt ownership of permissions from
9276                // another package.
9277                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9278                    final String origName = pkg.mAdoptPermissions.get(i);
9279                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9280                    if (orig != null) {
9281                        if (verifyPackageUpdateLPr(orig, pkg)) {
9282                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9283                                    + pkg.packageName);
9284                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9285                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9286                        }
9287                    }
9288                }
9289            }
9290        }
9291
9292        pkg.applicationInfo.processName = fixProcessName(
9293                pkg.applicationInfo.packageName,
9294                pkg.applicationInfo.processName);
9295
9296        if (pkg != mPlatformPackage) {
9297            // Get all of our default paths setup
9298            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9299        }
9300
9301        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9302
9303        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9304            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9305                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9306                derivePackageAbi(
9307                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9308                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9309
9310                // Some system apps still use directory structure for native libraries
9311                // in which case we might end up not detecting abi solely based on apk
9312                // structure. Try to detect abi based on directory structure.
9313                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9314                        pkg.applicationInfo.primaryCpuAbi == null) {
9315                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9316                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9317                }
9318            } else {
9319                // This is not a first boot or an upgrade, don't bother deriving the
9320                // ABI during the scan. Instead, trust the value that was stored in the
9321                // package setting.
9322                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9323                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9324
9325                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9326
9327                if (DEBUG_ABI_SELECTION) {
9328                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9329                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9330                        pkg.applicationInfo.secondaryCpuAbi);
9331                }
9332            }
9333        } else {
9334            if ((scanFlags & SCAN_MOVE) != 0) {
9335                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9336                // but we already have this packages package info in the PackageSetting. We just
9337                // use that and derive the native library path based on the new codepath.
9338                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9339                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9340            }
9341
9342            // Set native library paths again. For moves, the path will be updated based on the
9343            // ABIs we've determined above. For non-moves, the path will be updated based on the
9344            // ABIs we determined during compilation, but the path will depend on the final
9345            // package path (after the rename away from the stage path).
9346            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9347        }
9348
9349        // This is a special case for the "system" package, where the ABI is
9350        // dictated by the zygote configuration (and init.rc). We should keep track
9351        // of this ABI so that we can deal with "normal" applications that run under
9352        // the same UID correctly.
9353        if (mPlatformPackage == pkg) {
9354            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9355                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9356        }
9357
9358        // If there's a mismatch between the abi-override in the package setting
9359        // and the abiOverride specified for the install. Warn about this because we
9360        // would've already compiled the app without taking the package setting into
9361        // account.
9362        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9363            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9364                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9365                        " for package " + pkg.packageName);
9366            }
9367        }
9368
9369        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9370        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9371        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9372
9373        // Copy the derived override back to the parsed package, so that we can
9374        // update the package settings accordingly.
9375        pkg.cpuAbiOverride = cpuAbiOverride;
9376
9377        if (DEBUG_ABI_SELECTION) {
9378            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9379                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9380                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9381        }
9382
9383        // Push the derived path down into PackageSettings so we know what to
9384        // clean up at uninstall time.
9385        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9386
9387        if (DEBUG_ABI_SELECTION) {
9388            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9389                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9390                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9391        }
9392
9393        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9394        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9395            // We don't do this here during boot because we can do it all
9396            // at once after scanning all existing packages.
9397            //
9398            // We also do this *before* we perform dexopt on this package, so that
9399            // we can avoid redundant dexopts, and also to make sure we've got the
9400            // code and package path correct.
9401            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9402        }
9403
9404        if (mFactoryTest && pkg.requestedPermissions.contains(
9405                android.Manifest.permission.FACTORY_TEST)) {
9406            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9407        }
9408
9409        if (isSystemApp(pkg)) {
9410            pkgSetting.isOrphaned = true;
9411        }
9412
9413        // Take care of first install / last update times.
9414        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9415        if (currentTime != 0) {
9416            if (pkgSetting.firstInstallTime == 0) {
9417                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9418            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9419                pkgSetting.lastUpdateTime = currentTime;
9420            }
9421        } else if (pkgSetting.firstInstallTime == 0) {
9422            // We need *something*.  Take time time stamp of the file.
9423            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9424        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9425            if (scanFileTime != pkgSetting.timeStamp) {
9426                // A package on the system image has changed; consider this
9427                // to be an update.
9428                pkgSetting.lastUpdateTime = scanFileTime;
9429            }
9430        }
9431        pkgSetting.setTimeStamp(scanFileTime);
9432
9433        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9434            if (nonMutatedPs != null) {
9435                synchronized (mPackages) {
9436                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9437                }
9438            }
9439        } else {
9440            final int userId = user == null ? 0 : user.getIdentifier();
9441            // Modify state for the given package setting
9442            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9443                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9444            if (pkgSetting.getInstantApp(userId)) {
9445                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9446            }
9447        }
9448        return pkg;
9449    }
9450
9451    /**
9452     * Applies policy to the parsed package based upon the given policy flags.
9453     * Ensures the package is in a good state.
9454     * <p>
9455     * Implementation detail: This method must NOT have any side effect. It would
9456     * ideally be static, but, it requires locks to read system state.
9457     */
9458    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9459        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9460            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9461            if (pkg.applicationInfo.isDirectBootAware()) {
9462                // we're direct boot aware; set for all components
9463                for (PackageParser.Service s : pkg.services) {
9464                    s.info.encryptionAware = s.info.directBootAware = true;
9465                }
9466                for (PackageParser.Provider p : pkg.providers) {
9467                    p.info.encryptionAware = p.info.directBootAware = true;
9468                }
9469                for (PackageParser.Activity a : pkg.activities) {
9470                    a.info.encryptionAware = a.info.directBootAware = true;
9471                }
9472                for (PackageParser.Activity r : pkg.receivers) {
9473                    r.info.encryptionAware = r.info.directBootAware = true;
9474                }
9475            }
9476        } else {
9477            // Only allow system apps to be flagged as core apps.
9478            pkg.coreApp = false;
9479            // clear flags not applicable to regular apps
9480            pkg.applicationInfo.privateFlags &=
9481                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9482            pkg.applicationInfo.privateFlags &=
9483                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9484        }
9485        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9486
9487        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9488            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9489        }
9490
9491        if (!isSystemApp(pkg)) {
9492            // Only system apps can use these features.
9493            pkg.mOriginalPackages = null;
9494            pkg.mRealPackage = null;
9495            pkg.mAdoptPermissions = null;
9496        }
9497    }
9498
9499    /**
9500     * Asserts the parsed package is valid according to the given policy. If the
9501     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
9502     * <p>
9503     * Implementation detail: This method must NOT have any side effects. It would
9504     * ideally be static, but, it requires locks to read system state.
9505     *
9506     * @throws PackageManagerException If the package fails any of the validation checks
9507     */
9508    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9509            throws PackageManagerException {
9510        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9511            assertCodePolicy(pkg);
9512        }
9513
9514        if (pkg.applicationInfo.getCodePath() == null ||
9515                pkg.applicationInfo.getResourcePath() == null) {
9516            // Bail out. The resource and code paths haven't been set.
9517            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9518                    "Code and resource paths haven't been set correctly");
9519        }
9520
9521        // Make sure we're not adding any bogus keyset info
9522        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9523        ksms.assertScannedPackageValid(pkg);
9524
9525        synchronized (mPackages) {
9526            // The special "android" package can only be defined once
9527            if (pkg.packageName.equals("android")) {
9528                if (mAndroidApplication != null) {
9529                    Slog.w(TAG, "*************************************************");
9530                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9531                    Slog.w(TAG, " codePath=" + pkg.codePath);
9532                    Slog.w(TAG, "*************************************************");
9533                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9534                            "Core android package being redefined.  Skipping.");
9535                }
9536            }
9537
9538            // A package name must be unique; don't allow duplicates
9539            if (mPackages.containsKey(pkg.packageName)) {
9540                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9541                        "Application package " + pkg.packageName
9542                        + " already installed.  Skipping duplicate.");
9543            }
9544
9545            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9546                // Static libs have a synthetic package name containing the version
9547                // but we still want the base name to be unique.
9548                if (mPackages.containsKey(pkg.manifestPackageName)) {
9549                    throw new PackageManagerException(
9550                            "Duplicate static shared lib provider package");
9551                }
9552
9553                // Static shared libraries should have at least O target SDK
9554                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9555                    throw new PackageManagerException(
9556                            "Packages declaring static-shared libs must target O SDK or higher");
9557                }
9558
9559                // Package declaring static a shared lib cannot be instant apps
9560                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9561                    throw new PackageManagerException(
9562                            "Packages declaring static-shared libs cannot be instant apps");
9563                }
9564
9565                // Package declaring static a shared lib cannot be renamed since the package
9566                // name is synthetic and apps can't code around package manager internals.
9567                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9568                    throw new PackageManagerException(
9569                            "Packages declaring static-shared libs cannot be renamed");
9570                }
9571
9572                // Package declaring static a shared lib cannot declare child packages
9573                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9574                    throw new PackageManagerException(
9575                            "Packages declaring static-shared libs cannot have child packages");
9576                }
9577
9578                // Package declaring static a shared lib cannot declare dynamic libs
9579                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9580                    throw new PackageManagerException(
9581                            "Packages declaring static-shared libs cannot declare dynamic libs");
9582                }
9583
9584                // Package declaring static a shared lib cannot declare shared users
9585                if (pkg.mSharedUserId != null) {
9586                    throw new PackageManagerException(
9587                            "Packages declaring static-shared libs cannot declare shared users");
9588                }
9589
9590                // Static shared libs cannot declare activities
9591                if (!pkg.activities.isEmpty()) {
9592                    throw new PackageManagerException(
9593                            "Static shared libs cannot declare activities");
9594                }
9595
9596                // Static shared libs cannot declare services
9597                if (!pkg.services.isEmpty()) {
9598                    throw new PackageManagerException(
9599                            "Static shared libs cannot declare services");
9600                }
9601
9602                // Static shared libs cannot declare providers
9603                if (!pkg.providers.isEmpty()) {
9604                    throw new PackageManagerException(
9605                            "Static shared libs cannot declare content providers");
9606                }
9607
9608                // Static shared libs cannot declare receivers
9609                if (!pkg.receivers.isEmpty()) {
9610                    throw new PackageManagerException(
9611                            "Static shared libs cannot declare broadcast receivers");
9612                }
9613
9614                // Static shared libs cannot declare permission groups
9615                if (!pkg.permissionGroups.isEmpty()) {
9616                    throw new PackageManagerException(
9617                            "Static shared libs cannot declare permission groups");
9618                }
9619
9620                // Static shared libs cannot declare permissions
9621                if (!pkg.permissions.isEmpty()) {
9622                    throw new PackageManagerException(
9623                            "Static shared libs cannot declare permissions");
9624                }
9625
9626                // Static shared libs cannot declare protected broadcasts
9627                if (pkg.protectedBroadcasts != null) {
9628                    throw new PackageManagerException(
9629                            "Static shared libs cannot declare protected broadcasts");
9630                }
9631
9632                // Static shared libs cannot be overlay targets
9633                if (pkg.mOverlayTarget != null) {
9634                    throw new PackageManagerException(
9635                            "Static shared libs cannot be overlay targets");
9636                }
9637
9638                // The version codes must be ordered as lib versions
9639                int minVersionCode = Integer.MIN_VALUE;
9640                int maxVersionCode = Integer.MAX_VALUE;
9641
9642                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9643                        pkg.staticSharedLibName);
9644                if (versionedLib != null) {
9645                    final int versionCount = versionedLib.size();
9646                    for (int i = 0; i < versionCount; i++) {
9647                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9648                        // TODO: We will change version code to long, so in the new API it is long
9649                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9650                                .getVersionCode();
9651                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9652                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9653                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9654                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9655                        } else {
9656                            minVersionCode = maxVersionCode = libVersionCode;
9657                            break;
9658                        }
9659                    }
9660                }
9661                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9662                    throw new PackageManagerException("Static shared"
9663                            + " lib version codes must be ordered as lib versions");
9664                }
9665            }
9666
9667            // Only privileged apps and updated privileged apps can add child packages.
9668            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9669                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9670                    throw new PackageManagerException("Only privileged apps can add child "
9671                            + "packages. Ignoring package " + pkg.packageName);
9672                }
9673                final int childCount = pkg.childPackages.size();
9674                for (int i = 0; i < childCount; i++) {
9675                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9676                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9677                            childPkg.packageName)) {
9678                        throw new PackageManagerException("Can't override child of "
9679                                + "another disabled app. Ignoring package " + pkg.packageName);
9680                    }
9681                }
9682            }
9683
9684            // If we're only installing presumed-existing packages, require that the
9685            // scanned APK is both already known and at the path previously established
9686            // for it.  Previously unknown packages we pick up normally, but if we have an
9687            // a priori expectation about this package's install presence, enforce it.
9688            // With a singular exception for new system packages. When an OTA contains
9689            // a new system package, we allow the codepath to change from a system location
9690            // to the user-installed location. If we don't allow this change, any newer,
9691            // user-installed version of the application will be ignored.
9692            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9693                if (mExpectingBetter.containsKey(pkg.packageName)) {
9694                    logCriticalInfo(Log.WARN,
9695                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9696                } else {
9697                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9698                    if (known != null) {
9699                        if (DEBUG_PACKAGE_SCANNING) {
9700                            Log.d(TAG, "Examining " + pkg.codePath
9701                                    + " and requiring known paths " + known.codePathString
9702                                    + " & " + known.resourcePathString);
9703                        }
9704                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9705                                || !pkg.applicationInfo.getResourcePath().equals(
9706                                        known.resourcePathString)) {
9707                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9708                                    "Application package " + pkg.packageName
9709                                    + " found at " + pkg.applicationInfo.getCodePath()
9710                                    + " but expected at " + known.codePathString
9711                                    + "; ignoring.");
9712                        }
9713                    }
9714                }
9715            }
9716
9717            // Verify that this new package doesn't have any content providers
9718            // that conflict with existing packages.  Only do this if the
9719            // package isn't already installed, since we don't want to break
9720            // things that are installed.
9721            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9722                final int N = pkg.providers.size();
9723                int i;
9724                for (i=0; i<N; i++) {
9725                    PackageParser.Provider p = pkg.providers.get(i);
9726                    if (p.info.authority != null) {
9727                        String names[] = p.info.authority.split(";");
9728                        for (int j = 0; j < names.length; j++) {
9729                            if (mProvidersByAuthority.containsKey(names[j])) {
9730                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9731                                final String otherPackageName =
9732                                        ((other != null && other.getComponentName() != null) ?
9733                                                other.getComponentName().getPackageName() : "?");
9734                                throw new PackageManagerException(
9735                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9736                                        "Can't install because provider name " + names[j]
9737                                                + " (in package " + pkg.applicationInfo.packageName
9738                                                + ") is already used by " + otherPackageName);
9739                            }
9740                        }
9741                    }
9742                }
9743            }
9744        }
9745    }
9746
9747    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9748            int type, String declaringPackageName, int declaringVersionCode) {
9749        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9750        if (versionedLib == null) {
9751            versionedLib = new SparseArray<>();
9752            mSharedLibraries.put(name, versionedLib);
9753            if (type == SharedLibraryInfo.TYPE_STATIC) {
9754                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9755            }
9756        } else if (versionedLib.indexOfKey(version) >= 0) {
9757            return false;
9758        }
9759        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9760                version, type, declaringPackageName, declaringVersionCode);
9761        versionedLib.put(version, libEntry);
9762        return true;
9763    }
9764
9765    private boolean removeSharedLibraryLPw(String name, int version) {
9766        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9767        if (versionedLib == null) {
9768            return false;
9769        }
9770        final int libIdx = versionedLib.indexOfKey(version);
9771        if (libIdx < 0) {
9772            return false;
9773        }
9774        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9775        versionedLib.remove(version);
9776        if (versionedLib.size() <= 0) {
9777            mSharedLibraries.remove(name);
9778            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9779                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9780                        .getPackageName());
9781            }
9782        }
9783        return true;
9784    }
9785
9786    /**
9787     * Adds a scanned package to the system. When this method is finished, the package will
9788     * be available for query, resolution, etc...
9789     */
9790    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9791            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9792        final String pkgName = pkg.packageName;
9793        if (mCustomResolverComponentName != null &&
9794                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9795            setUpCustomResolverActivity(pkg);
9796        }
9797
9798        if (pkg.packageName.equals("android")) {
9799            synchronized (mPackages) {
9800                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9801                    // Set up information for our fall-back user intent resolution activity.
9802                    mPlatformPackage = pkg;
9803                    pkg.mVersionCode = mSdkVersion;
9804                    mAndroidApplication = pkg.applicationInfo;
9805                    if (!mResolverReplaced) {
9806                        mResolveActivity.applicationInfo = mAndroidApplication;
9807                        mResolveActivity.name = ResolverActivity.class.getName();
9808                        mResolveActivity.packageName = mAndroidApplication.packageName;
9809                        mResolveActivity.processName = "system:ui";
9810                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9811                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9812                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9813                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9814                        mResolveActivity.exported = true;
9815                        mResolveActivity.enabled = true;
9816                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9817                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9818                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9819                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9820                                | ActivityInfo.CONFIG_ORIENTATION
9821                                | ActivityInfo.CONFIG_KEYBOARD
9822                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9823                        mResolveInfo.activityInfo = mResolveActivity;
9824                        mResolveInfo.priority = 0;
9825                        mResolveInfo.preferredOrder = 0;
9826                        mResolveInfo.match = 0;
9827                        mResolveComponentName = new ComponentName(
9828                                mAndroidApplication.packageName, mResolveActivity.name);
9829                    }
9830                }
9831            }
9832        }
9833
9834        ArrayList<PackageParser.Package> clientLibPkgs = null;
9835        // writer
9836        synchronized (mPackages) {
9837            boolean hasStaticSharedLibs = false;
9838
9839            // Any app can add new static shared libraries
9840            if (pkg.staticSharedLibName != null) {
9841                // Static shared libs don't allow renaming as they have synthetic package
9842                // names to allow install of multiple versions, so use name from manifest.
9843                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9844                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9845                        pkg.manifestPackageName, pkg.mVersionCode)) {
9846                    hasStaticSharedLibs = true;
9847                } else {
9848                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9849                                + pkg.staticSharedLibName + " already exists; skipping");
9850                }
9851                // Static shared libs cannot be updated once installed since they
9852                // use synthetic package name which includes the version code, so
9853                // not need to update other packages's shared lib dependencies.
9854            }
9855
9856            if (!hasStaticSharedLibs
9857                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9858                // Only system apps can add new dynamic shared libraries.
9859                if (pkg.libraryNames != null) {
9860                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9861                        String name = pkg.libraryNames.get(i);
9862                        boolean allowed = false;
9863                        if (pkg.isUpdatedSystemApp()) {
9864                            // New library entries can only be added through the
9865                            // system image.  This is important to get rid of a lot
9866                            // of nasty edge cases: for example if we allowed a non-
9867                            // system update of the app to add a library, then uninstalling
9868                            // the update would make the library go away, and assumptions
9869                            // we made such as through app install filtering would now
9870                            // have allowed apps on the device which aren't compatible
9871                            // with it.  Better to just have the restriction here, be
9872                            // conservative, and create many fewer cases that can negatively
9873                            // impact the user experience.
9874                            final PackageSetting sysPs = mSettings
9875                                    .getDisabledSystemPkgLPr(pkg.packageName);
9876                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9877                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9878                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9879                                        allowed = true;
9880                                        break;
9881                                    }
9882                                }
9883                            }
9884                        } else {
9885                            allowed = true;
9886                        }
9887                        if (allowed) {
9888                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9889                                    SharedLibraryInfo.VERSION_UNDEFINED,
9890                                    SharedLibraryInfo.TYPE_DYNAMIC,
9891                                    pkg.packageName, pkg.mVersionCode)) {
9892                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9893                                        + name + " already exists; skipping");
9894                            }
9895                        } else {
9896                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9897                                    + name + " that is not declared on system image; skipping");
9898                        }
9899                    }
9900
9901                    if ((scanFlags & SCAN_BOOTING) == 0) {
9902                        // If we are not booting, we need to update any applications
9903                        // that are clients of our shared library.  If we are booting,
9904                        // this will all be done once the scan is complete.
9905                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9906                    }
9907                }
9908            }
9909        }
9910
9911        if ((scanFlags & SCAN_BOOTING) != 0) {
9912            // No apps can run during boot scan, so they don't need to be frozen
9913        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9914            // Caller asked to not kill app, so it's probably not frozen
9915        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9916            // Caller asked us to ignore frozen check for some reason; they
9917            // probably didn't know the package name
9918        } else {
9919            // We're doing major surgery on this package, so it better be frozen
9920            // right now to keep it from launching
9921            checkPackageFrozen(pkgName);
9922        }
9923
9924        // Also need to kill any apps that are dependent on the library.
9925        if (clientLibPkgs != null) {
9926            for (int i=0; i<clientLibPkgs.size(); i++) {
9927                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9928                killApplication(clientPkg.applicationInfo.packageName,
9929                        clientPkg.applicationInfo.uid, "update lib");
9930            }
9931        }
9932
9933        // writer
9934        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9935
9936        boolean createIdmapFailed = false;
9937        synchronized (mPackages) {
9938            // We don't expect installation to fail beyond this point
9939
9940            if (pkgSetting.pkg != null) {
9941                // Note that |user| might be null during the initial boot scan. If a codePath
9942                // for an app has changed during a boot scan, it's due to an app update that's
9943                // part of the system partition and marker changes must be applied to all users.
9944                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9945                final int[] userIds = resolveUserIds(userId);
9946                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9947            }
9948
9949            // Add the new setting to mSettings
9950            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9951            // Add the new setting to mPackages
9952            mPackages.put(pkg.applicationInfo.packageName, pkg);
9953            // Make sure we don't accidentally delete its data.
9954            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9955            while (iter.hasNext()) {
9956                PackageCleanItem item = iter.next();
9957                if (pkgName.equals(item.packageName)) {
9958                    iter.remove();
9959                }
9960            }
9961
9962            // Add the package's KeySets to the global KeySetManagerService
9963            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9964            ksms.addScannedPackageLPw(pkg);
9965
9966            int N = pkg.providers.size();
9967            StringBuilder r = null;
9968            int i;
9969            for (i=0; i<N; i++) {
9970                PackageParser.Provider p = pkg.providers.get(i);
9971                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9972                        p.info.processName);
9973                mProviders.addProvider(p);
9974                p.syncable = p.info.isSyncable;
9975                if (p.info.authority != null) {
9976                    String names[] = p.info.authority.split(";");
9977                    p.info.authority = null;
9978                    for (int j = 0; j < names.length; j++) {
9979                        if (j == 1 && p.syncable) {
9980                            // We only want the first authority for a provider to possibly be
9981                            // syncable, so if we already added this provider using a different
9982                            // authority clear the syncable flag. We copy the provider before
9983                            // changing it because the mProviders object contains a reference
9984                            // to a provider that we don't want to change.
9985                            // Only do this for the second authority since the resulting provider
9986                            // object can be the same for all future authorities for this provider.
9987                            p = new PackageParser.Provider(p);
9988                            p.syncable = false;
9989                        }
9990                        if (!mProvidersByAuthority.containsKey(names[j])) {
9991                            mProvidersByAuthority.put(names[j], p);
9992                            if (p.info.authority == null) {
9993                                p.info.authority = names[j];
9994                            } else {
9995                                p.info.authority = p.info.authority + ";" + names[j];
9996                            }
9997                            if (DEBUG_PACKAGE_SCANNING) {
9998                                if (chatty)
9999                                    Log.d(TAG, "Registered content provider: " + names[j]
10000                                            + ", className = " + p.info.name + ", isSyncable = "
10001                                            + p.info.isSyncable);
10002                            }
10003                        } else {
10004                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10005                            Slog.w(TAG, "Skipping provider name " + names[j] +
10006                                    " (in package " + pkg.applicationInfo.packageName +
10007                                    "): name already used by "
10008                                    + ((other != null && other.getComponentName() != null)
10009                                            ? other.getComponentName().getPackageName() : "?"));
10010                        }
10011                    }
10012                }
10013                if (chatty) {
10014                    if (r == null) {
10015                        r = new StringBuilder(256);
10016                    } else {
10017                        r.append(' ');
10018                    }
10019                    r.append(p.info.name);
10020                }
10021            }
10022            if (r != null) {
10023                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10024            }
10025
10026            N = pkg.services.size();
10027            r = null;
10028            for (i=0; i<N; i++) {
10029                PackageParser.Service s = pkg.services.get(i);
10030                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10031                        s.info.processName);
10032                mServices.addService(s);
10033                if (chatty) {
10034                    if (r == null) {
10035                        r = new StringBuilder(256);
10036                    } else {
10037                        r.append(' ');
10038                    }
10039                    r.append(s.info.name);
10040                }
10041            }
10042            if (r != null) {
10043                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10044            }
10045
10046            N = pkg.receivers.size();
10047            r = null;
10048            for (i=0; i<N; i++) {
10049                PackageParser.Activity a = pkg.receivers.get(i);
10050                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10051                        a.info.processName);
10052                mReceivers.addActivity(a, "receiver");
10053                if (chatty) {
10054                    if (r == null) {
10055                        r = new StringBuilder(256);
10056                    } else {
10057                        r.append(' ');
10058                    }
10059                    r.append(a.info.name);
10060                }
10061            }
10062            if (r != null) {
10063                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10064            }
10065
10066            N = pkg.activities.size();
10067            r = null;
10068            for (i=0; i<N; i++) {
10069                PackageParser.Activity a = pkg.activities.get(i);
10070                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10071                        a.info.processName);
10072                mActivities.addActivity(a, "activity");
10073                if (chatty) {
10074                    if (r == null) {
10075                        r = new StringBuilder(256);
10076                    } else {
10077                        r.append(' ');
10078                    }
10079                    r.append(a.info.name);
10080                }
10081            }
10082            if (r != null) {
10083                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10084            }
10085
10086            N = pkg.permissionGroups.size();
10087            r = null;
10088            for (i=0; i<N; i++) {
10089                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10090                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10091                final String curPackageName = cur == null ? null : cur.info.packageName;
10092                // Dont allow ephemeral apps to define new permission groups.
10093                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10094                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10095                            + pg.info.packageName
10096                            + " ignored: instant apps cannot define new permission groups.");
10097                    continue;
10098                }
10099                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10100                if (cur == null || isPackageUpdate) {
10101                    mPermissionGroups.put(pg.info.name, pg);
10102                    if (chatty) {
10103                        if (r == null) {
10104                            r = new StringBuilder(256);
10105                        } else {
10106                            r.append(' ');
10107                        }
10108                        if (isPackageUpdate) {
10109                            r.append("UPD:");
10110                        }
10111                        r.append(pg.info.name);
10112                    }
10113                } else {
10114                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10115                            + pg.info.packageName + " ignored: original from "
10116                            + cur.info.packageName);
10117                    if (chatty) {
10118                        if (r == null) {
10119                            r = new StringBuilder(256);
10120                        } else {
10121                            r.append(' ');
10122                        }
10123                        r.append("DUP:");
10124                        r.append(pg.info.name);
10125                    }
10126                }
10127            }
10128            if (r != null) {
10129                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10130            }
10131
10132            N = pkg.permissions.size();
10133            r = null;
10134            for (i=0; i<N; i++) {
10135                PackageParser.Permission p = pkg.permissions.get(i);
10136
10137                // Dont allow ephemeral apps to define new permissions.
10138                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10139                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10140                            + p.info.packageName
10141                            + " ignored: instant apps cannot define new permissions.");
10142                    continue;
10143                }
10144
10145                // Assume by default that we did not install this permission into the system.
10146                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10147
10148                // Now that permission groups have a special meaning, we ignore permission
10149                // groups for legacy apps to prevent unexpected behavior. In particular,
10150                // permissions for one app being granted to someone just becase they happen
10151                // to be in a group defined by another app (before this had no implications).
10152                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10153                    p.group = mPermissionGroups.get(p.info.group);
10154                    // Warn for a permission in an unknown group.
10155                    if (p.info.group != null && p.group == null) {
10156                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10157                                + p.info.packageName + " in an unknown group " + p.info.group);
10158                    }
10159                }
10160
10161                ArrayMap<String, BasePermission> permissionMap =
10162                        p.tree ? mSettings.mPermissionTrees
10163                                : mSettings.mPermissions;
10164                BasePermission bp = permissionMap.get(p.info.name);
10165
10166                // Allow system apps to redefine non-system permissions
10167                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10168                    final boolean currentOwnerIsSystem = (bp.perm != null
10169                            && isSystemApp(bp.perm.owner));
10170                    if (isSystemApp(p.owner)) {
10171                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10172                            // It's a built-in permission and no owner, take ownership now
10173                            bp.packageSetting = pkgSetting;
10174                            bp.perm = p;
10175                            bp.uid = pkg.applicationInfo.uid;
10176                            bp.sourcePackage = p.info.packageName;
10177                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10178                        } else if (!currentOwnerIsSystem) {
10179                            String msg = "New decl " + p.owner + " of permission  "
10180                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10181                            reportSettingsProblem(Log.WARN, msg);
10182                            bp = null;
10183                        }
10184                    }
10185                }
10186
10187                if (bp == null) {
10188                    bp = new BasePermission(p.info.name, p.info.packageName,
10189                            BasePermission.TYPE_NORMAL);
10190                    permissionMap.put(p.info.name, bp);
10191                }
10192
10193                if (bp.perm == null) {
10194                    if (bp.sourcePackage == null
10195                            || bp.sourcePackage.equals(p.info.packageName)) {
10196                        BasePermission tree = findPermissionTreeLP(p.info.name);
10197                        if (tree == null
10198                                || tree.sourcePackage.equals(p.info.packageName)) {
10199                            bp.packageSetting = pkgSetting;
10200                            bp.perm = p;
10201                            bp.uid = pkg.applicationInfo.uid;
10202                            bp.sourcePackage = p.info.packageName;
10203                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10204                            if (chatty) {
10205                                if (r == null) {
10206                                    r = new StringBuilder(256);
10207                                } else {
10208                                    r.append(' ');
10209                                }
10210                                r.append(p.info.name);
10211                            }
10212                        } else {
10213                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10214                                    + p.info.packageName + " ignored: base tree "
10215                                    + tree.name + " is from package "
10216                                    + tree.sourcePackage);
10217                        }
10218                    } else {
10219                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10220                                + p.info.packageName + " ignored: original from "
10221                                + bp.sourcePackage);
10222                    }
10223                } else if (chatty) {
10224                    if (r == null) {
10225                        r = new StringBuilder(256);
10226                    } else {
10227                        r.append(' ');
10228                    }
10229                    r.append("DUP:");
10230                    r.append(p.info.name);
10231                }
10232                if (bp.perm == p) {
10233                    bp.protectionLevel = p.info.protectionLevel;
10234                }
10235            }
10236
10237            if (r != null) {
10238                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10239            }
10240
10241            N = pkg.instrumentation.size();
10242            r = null;
10243            for (i=0; i<N; i++) {
10244                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10245                a.info.packageName = pkg.applicationInfo.packageName;
10246                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10247                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10248                a.info.splitNames = pkg.splitNames;
10249                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10250                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10251                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10252                a.info.dataDir = pkg.applicationInfo.dataDir;
10253                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10254                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10255                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10256                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10257                mInstrumentation.put(a.getComponentName(), a);
10258                if (chatty) {
10259                    if (r == null) {
10260                        r = new StringBuilder(256);
10261                    } else {
10262                        r.append(' ');
10263                    }
10264                    r.append(a.info.name);
10265                }
10266            }
10267            if (r != null) {
10268                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10269            }
10270
10271            if (pkg.protectedBroadcasts != null) {
10272                N = pkg.protectedBroadcasts.size();
10273                for (i=0; i<N; i++) {
10274                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10275                }
10276            }
10277
10278            // Create idmap files for pairs of (packages, overlay packages).
10279            // Note: "android", ie framework-res.apk, is handled by native layers.
10280            if (pkg.mOverlayTarget != null) {
10281                // This is an overlay package.
10282                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
10283                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
10284                        mOverlays.put(pkg.mOverlayTarget,
10285                                new ArrayMap<String, PackageParser.Package>());
10286                    }
10287                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
10288                    map.put(pkg.packageName, pkg);
10289                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
10290                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
10291                        createIdmapFailed = true;
10292                    }
10293                }
10294            } else if (mOverlays.containsKey(pkg.packageName) &&
10295                    !pkg.packageName.equals("android")) {
10296                // This is a regular package, with one or more known overlay packages.
10297                createIdmapsForPackageLI(pkg);
10298            }
10299        }
10300
10301        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10302
10303        if (createIdmapFailed) {
10304            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10305                    "scanPackageLI failed to createIdmap");
10306        }
10307    }
10308
10309    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
10310            PackageParser.Package update, int[] userIds) {
10311        if (existing.applicationInfo == null || update.applicationInfo == null) {
10312            // This isn't due to an app installation.
10313            return;
10314        }
10315
10316        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
10317        final File newCodePath = new File(update.applicationInfo.getCodePath());
10318
10319        // The codePath hasn't changed, so there's nothing for us to do.
10320        if (Objects.equals(oldCodePath, newCodePath)) {
10321            return;
10322        }
10323
10324        File canonicalNewCodePath;
10325        try {
10326            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
10327        } catch (IOException e) {
10328            Slog.w(TAG, "Failed to get canonical path.", e);
10329            return;
10330        }
10331
10332        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
10333        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
10334        // that the last component of the path (i.e, the name) doesn't need canonicalization
10335        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
10336        // but may change in the future. Hopefully this function won't exist at that point.
10337        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
10338                oldCodePath.getName());
10339
10340        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
10341        // with "@".
10342        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
10343        if (!oldMarkerPrefix.endsWith("@")) {
10344            oldMarkerPrefix += "@";
10345        }
10346        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
10347        if (!newMarkerPrefix.endsWith("@")) {
10348            newMarkerPrefix += "@";
10349        }
10350
10351        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
10352        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
10353        for (String updatedPath : updatedPaths) {
10354            String updatedPathName = new File(updatedPath).getName();
10355            markerSuffixes.add(updatedPathName.replace('/', '@'));
10356        }
10357
10358        for (int userId : userIds) {
10359            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
10360
10361            for (String markerSuffix : markerSuffixes) {
10362                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
10363                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
10364                if (oldForeignUseMark.exists()) {
10365                    try {
10366                        Os.rename(oldForeignUseMark.getAbsolutePath(),
10367                                newForeignUseMark.getAbsolutePath());
10368                    } catch (ErrnoException e) {
10369                        Slog.w(TAG, "Failed to rename foreign use marker", e);
10370                        oldForeignUseMark.delete();
10371                    }
10372                }
10373            }
10374        }
10375    }
10376
10377    /**
10378     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10379     * is derived purely on the basis of the contents of {@code scanFile} and
10380     * {@code cpuAbiOverride}.
10381     *
10382     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10383     */
10384    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10385                                 String cpuAbiOverride, boolean extractLibs,
10386                                 File appLib32InstallDir)
10387            throws PackageManagerException {
10388        // Give ourselves some initial paths; we'll come back for another
10389        // pass once we've determined ABI below.
10390        setNativeLibraryPaths(pkg, appLib32InstallDir);
10391
10392        // We would never need to extract libs for forward-locked and external packages,
10393        // since the container service will do it for us. We shouldn't attempt to
10394        // extract libs from system app when it was not updated.
10395        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10396                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10397            extractLibs = false;
10398        }
10399
10400        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10401        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10402
10403        NativeLibraryHelper.Handle handle = null;
10404        try {
10405            handle = NativeLibraryHelper.Handle.create(pkg);
10406            // TODO(multiArch): This can be null for apps that didn't go through the
10407            // usual installation process. We can calculate it again, like we
10408            // do during install time.
10409            //
10410            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10411            // unnecessary.
10412            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10413
10414            // Null out the abis so that they can be recalculated.
10415            pkg.applicationInfo.primaryCpuAbi = null;
10416            pkg.applicationInfo.secondaryCpuAbi = null;
10417            if (isMultiArch(pkg.applicationInfo)) {
10418                // Warn if we've set an abiOverride for multi-lib packages..
10419                // By definition, we need to copy both 32 and 64 bit libraries for
10420                // such packages.
10421                if (pkg.cpuAbiOverride != null
10422                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10423                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10424                }
10425
10426                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10427                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10428                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10429                    if (extractLibs) {
10430                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10431                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10432                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10433                                useIsaSpecificSubdirs);
10434                    } else {
10435                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10436                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10437                    }
10438                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10439                }
10440
10441                maybeThrowExceptionForMultiArchCopy(
10442                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10443
10444                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10445                    if (extractLibs) {
10446                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10447                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10448                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10449                                useIsaSpecificSubdirs);
10450                    } else {
10451                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10452                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10453                    }
10454                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10455                }
10456
10457                maybeThrowExceptionForMultiArchCopy(
10458                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10459
10460                if (abi64 >= 0) {
10461                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10462                }
10463
10464                if (abi32 >= 0) {
10465                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10466                    if (abi64 >= 0) {
10467                        if (pkg.use32bitAbi) {
10468                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10469                            pkg.applicationInfo.primaryCpuAbi = abi;
10470                        } else {
10471                            pkg.applicationInfo.secondaryCpuAbi = abi;
10472                        }
10473                    } else {
10474                        pkg.applicationInfo.primaryCpuAbi = abi;
10475                    }
10476                }
10477
10478            } else {
10479                String[] abiList = (cpuAbiOverride != null) ?
10480                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10481
10482                // Enable gross and lame hacks for apps that are built with old
10483                // SDK tools. We must scan their APKs for renderscript bitcode and
10484                // not launch them if it's present. Don't bother checking on devices
10485                // that don't have 64 bit support.
10486                boolean needsRenderScriptOverride = false;
10487                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10488                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10489                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10490                    needsRenderScriptOverride = true;
10491                }
10492
10493                final int copyRet;
10494                if (extractLibs) {
10495                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10496                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10497                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10498                } else {
10499                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10500                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10501                }
10502                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10503
10504                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10505                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10506                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10507                }
10508
10509                if (copyRet >= 0) {
10510                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10511                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10512                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10513                } else if (needsRenderScriptOverride) {
10514                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10515                }
10516            }
10517        } catch (IOException ioe) {
10518            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10519        } finally {
10520            IoUtils.closeQuietly(handle);
10521        }
10522
10523        // Now that we've calculated the ABIs and determined if it's an internal app,
10524        // we will go ahead and populate the nativeLibraryPath.
10525        setNativeLibraryPaths(pkg, appLib32InstallDir);
10526    }
10527
10528    /**
10529     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10530     * i.e, so that all packages can be run inside a single process if required.
10531     *
10532     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10533     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10534     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10535     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10536     * updating a package that belongs to a shared user.
10537     *
10538     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10539     * adds unnecessary complexity.
10540     */
10541    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10542            PackageParser.Package scannedPackage) {
10543        String requiredInstructionSet = null;
10544        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10545            requiredInstructionSet = VMRuntime.getInstructionSet(
10546                     scannedPackage.applicationInfo.primaryCpuAbi);
10547        }
10548
10549        PackageSetting requirer = null;
10550        for (PackageSetting ps : packagesForUser) {
10551            // If packagesForUser contains scannedPackage, we skip it. This will happen
10552            // when scannedPackage is an update of an existing package. Without this check,
10553            // we will never be able to change the ABI of any package belonging to a shared
10554            // user, even if it's compatible with other packages.
10555            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10556                if (ps.primaryCpuAbiString == null) {
10557                    continue;
10558                }
10559
10560                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10561                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10562                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10563                    // this but there's not much we can do.
10564                    String errorMessage = "Instruction set mismatch, "
10565                            + ((requirer == null) ? "[caller]" : requirer)
10566                            + " requires " + requiredInstructionSet + " whereas " + ps
10567                            + " requires " + instructionSet;
10568                    Slog.w(TAG, errorMessage);
10569                }
10570
10571                if (requiredInstructionSet == null) {
10572                    requiredInstructionSet = instructionSet;
10573                    requirer = ps;
10574                }
10575            }
10576        }
10577
10578        if (requiredInstructionSet != null) {
10579            String adjustedAbi;
10580            if (requirer != null) {
10581                // requirer != null implies that either scannedPackage was null or that scannedPackage
10582                // did not require an ABI, in which case we have to adjust scannedPackage to match
10583                // the ABI of the set (which is the same as requirer's ABI)
10584                adjustedAbi = requirer.primaryCpuAbiString;
10585                if (scannedPackage != null) {
10586                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10587                }
10588            } else {
10589                // requirer == null implies that we're updating all ABIs in the set to
10590                // match scannedPackage.
10591                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10592            }
10593
10594            for (PackageSetting ps : packagesForUser) {
10595                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10596                    if (ps.primaryCpuAbiString != null) {
10597                        continue;
10598                    }
10599
10600                    ps.primaryCpuAbiString = adjustedAbi;
10601                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10602                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10603                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10604                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10605                                + " (requirer="
10606                                + (requirer == null ? "null" : requirer.pkg.packageName)
10607                                + ", scannedPackage="
10608                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10609                                + ")");
10610                        try {
10611                            mInstaller.rmdex(ps.codePathString,
10612                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10613                        } catch (InstallerException ignored) {
10614                        }
10615                    }
10616                }
10617            }
10618        }
10619    }
10620
10621    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10622        synchronized (mPackages) {
10623            mResolverReplaced = true;
10624            // Set up information for custom user intent resolution activity.
10625            mResolveActivity.applicationInfo = pkg.applicationInfo;
10626            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10627            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10628            mResolveActivity.processName = pkg.applicationInfo.packageName;
10629            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10630            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10631                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10632            mResolveActivity.theme = 0;
10633            mResolveActivity.exported = true;
10634            mResolveActivity.enabled = true;
10635            mResolveInfo.activityInfo = mResolveActivity;
10636            mResolveInfo.priority = 0;
10637            mResolveInfo.preferredOrder = 0;
10638            mResolveInfo.match = 0;
10639            mResolveComponentName = mCustomResolverComponentName;
10640            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10641                    mResolveComponentName);
10642        }
10643    }
10644
10645    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
10646        if (installerComponent == null) {
10647            if (DEBUG_EPHEMERAL) {
10648                Slog.d(TAG, "Clear ephemeral installer activity");
10649            }
10650            mEphemeralInstallerActivity.applicationInfo = null;
10651            return;
10652        }
10653
10654        if (DEBUG_EPHEMERAL) {
10655            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10656        }
10657        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10658        // Set up information for ephemeral installer activity
10659        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
10660        mEphemeralInstallerActivity.name = installerComponent.getClassName();
10661        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
10662        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
10663        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10664        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10665                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10666        mEphemeralInstallerActivity.theme = 0;
10667        mEphemeralInstallerActivity.exported = true;
10668        mEphemeralInstallerActivity.enabled = true;
10669        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
10670        mEphemeralInstallerInfo.priority = 0;
10671        mEphemeralInstallerInfo.preferredOrder = 1;
10672        mEphemeralInstallerInfo.isDefault = true;
10673        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10674                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10675    }
10676
10677    private static String calculateBundledApkRoot(final String codePathString) {
10678        final File codePath = new File(codePathString);
10679        final File codeRoot;
10680        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10681            codeRoot = Environment.getRootDirectory();
10682        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10683            codeRoot = Environment.getOemDirectory();
10684        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10685            codeRoot = Environment.getVendorDirectory();
10686        } else {
10687            // Unrecognized code path; take its top real segment as the apk root:
10688            // e.g. /something/app/blah.apk => /something
10689            try {
10690                File f = codePath.getCanonicalFile();
10691                File parent = f.getParentFile();    // non-null because codePath is a file
10692                File tmp;
10693                while ((tmp = parent.getParentFile()) != null) {
10694                    f = parent;
10695                    parent = tmp;
10696                }
10697                codeRoot = f;
10698                Slog.w(TAG, "Unrecognized code path "
10699                        + codePath + " - using " + codeRoot);
10700            } catch (IOException e) {
10701                // Can't canonicalize the code path -- shenanigans?
10702                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10703                return Environment.getRootDirectory().getPath();
10704            }
10705        }
10706        return codeRoot.getPath();
10707    }
10708
10709    /**
10710     * Derive and set the location of native libraries for the given package,
10711     * which varies depending on where and how the package was installed.
10712     */
10713    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10714        final ApplicationInfo info = pkg.applicationInfo;
10715        final String codePath = pkg.codePath;
10716        final File codeFile = new File(codePath);
10717        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10718        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10719
10720        info.nativeLibraryRootDir = null;
10721        info.nativeLibraryRootRequiresIsa = false;
10722        info.nativeLibraryDir = null;
10723        info.secondaryNativeLibraryDir = null;
10724
10725        if (isApkFile(codeFile)) {
10726            // Monolithic install
10727            if (bundledApp) {
10728                // If "/system/lib64/apkname" exists, assume that is the per-package
10729                // native library directory to use; otherwise use "/system/lib/apkname".
10730                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10731                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10732                        getPrimaryInstructionSet(info));
10733
10734                // This is a bundled system app so choose the path based on the ABI.
10735                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10736                // is just the default path.
10737                final String apkName = deriveCodePathName(codePath);
10738                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10739                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10740                        apkName).getAbsolutePath();
10741
10742                if (info.secondaryCpuAbi != null) {
10743                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10744                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10745                            secondaryLibDir, apkName).getAbsolutePath();
10746                }
10747            } else if (asecApp) {
10748                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10749                        .getAbsolutePath();
10750            } else {
10751                final String apkName = deriveCodePathName(codePath);
10752                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10753                        .getAbsolutePath();
10754            }
10755
10756            info.nativeLibraryRootRequiresIsa = false;
10757            info.nativeLibraryDir = info.nativeLibraryRootDir;
10758        } else {
10759            // Cluster install
10760            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10761            info.nativeLibraryRootRequiresIsa = true;
10762
10763            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10764                    getPrimaryInstructionSet(info)).getAbsolutePath();
10765
10766            if (info.secondaryCpuAbi != null) {
10767                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10768                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10769            }
10770        }
10771    }
10772
10773    /**
10774     * Calculate the abis and roots for a bundled app. These can uniquely
10775     * be determined from the contents of the system partition, i.e whether
10776     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10777     * of this information, and instead assume that the system was built
10778     * sensibly.
10779     */
10780    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10781                                           PackageSetting pkgSetting) {
10782        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10783
10784        // If "/system/lib64/apkname" exists, assume that is the per-package
10785        // native library directory to use; otherwise use "/system/lib/apkname".
10786        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10787        setBundledAppAbi(pkg, apkRoot, apkName);
10788        // pkgSetting might be null during rescan following uninstall of updates
10789        // to a bundled app, so accommodate that possibility.  The settings in
10790        // that case will be established later from the parsed package.
10791        //
10792        // If the settings aren't null, sync them up with what we've just derived.
10793        // note that apkRoot isn't stored in the package settings.
10794        if (pkgSetting != null) {
10795            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10796            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10797        }
10798    }
10799
10800    /**
10801     * Deduces the ABI of a bundled app and sets the relevant fields on the
10802     * parsed pkg object.
10803     *
10804     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10805     *        under which system libraries are installed.
10806     * @param apkName the name of the installed package.
10807     */
10808    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10809        final File codeFile = new File(pkg.codePath);
10810
10811        final boolean has64BitLibs;
10812        final boolean has32BitLibs;
10813        if (isApkFile(codeFile)) {
10814            // Monolithic install
10815            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10816            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10817        } else {
10818            // Cluster install
10819            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10820            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10821                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10822                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10823                has64BitLibs = (new File(rootDir, isa)).exists();
10824            } else {
10825                has64BitLibs = false;
10826            }
10827            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10828                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10829                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10830                has32BitLibs = (new File(rootDir, isa)).exists();
10831            } else {
10832                has32BitLibs = false;
10833            }
10834        }
10835
10836        if (has64BitLibs && !has32BitLibs) {
10837            // The package has 64 bit libs, but not 32 bit libs. Its primary
10838            // ABI should be 64 bit. We can safely assume here that the bundled
10839            // native libraries correspond to the most preferred ABI in the list.
10840
10841            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10842            pkg.applicationInfo.secondaryCpuAbi = null;
10843        } else if (has32BitLibs && !has64BitLibs) {
10844            // The package has 32 bit libs but not 64 bit libs. Its primary
10845            // ABI should be 32 bit.
10846
10847            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10848            pkg.applicationInfo.secondaryCpuAbi = null;
10849        } else if (has32BitLibs && has64BitLibs) {
10850            // The application has both 64 and 32 bit bundled libraries. We check
10851            // here that the app declares multiArch support, and warn if it doesn't.
10852            //
10853            // We will be lenient here and record both ABIs. The primary will be the
10854            // ABI that's higher on the list, i.e, a device that's configured to prefer
10855            // 64 bit apps will see a 64 bit primary ABI,
10856
10857            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10858                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10859            }
10860
10861            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10862                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10863                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10864            } else {
10865                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10866                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10867            }
10868        } else {
10869            pkg.applicationInfo.primaryCpuAbi = null;
10870            pkg.applicationInfo.secondaryCpuAbi = null;
10871        }
10872    }
10873
10874    private void killApplication(String pkgName, int appId, String reason) {
10875        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10876    }
10877
10878    private void killApplication(String pkgName, int appId, int userId, String reason) {
10879        // Request the ActivityManager to kill the process(only for existing packages)
10880        // so that we do not end up in a confused state while the user is still using the older
10881        // version of the application while the new one gets installed.
10882        final long token = Binder.clearCallingIdentity();
10883        try {
10884            IActivityManager am = ActivityManager.getService();
10885            if (am != null) {
10886                try {
10887                    am.killApplication(pkgName, appId, userId, reason);
10888                } catch (RemoteException e) {
10889                }
10890            }
10891        } finally {
10892            Binder.restoreCallingIdentity(token);
10893        }
10894    }
10895
10896    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10897        // Remove the parent package setting
10898        PackageSetting ps = (PackageSetting) pkg.mExtras;
10899        if (ps != null) {
10900            removePackageLI(ps, chatty);
10901        }
10902        // Remove the child package setting
10903        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10904        for (int i = 0; i < childCount; i++) {
10905            PackageParser.Package childPkg = pkg.childPackages.get(i);
10906            ps = (PackageSetting) childPkg.mExtras;
10907            if (ps != null) {
10908                removePackageLI(ps, chatty);
10909            }
10910        }
10911    }
10912
10913    void removePackageLI(PackageSetting ps, boolean chatty) {
10914        if (DEBUG_INSTALL) {
10915            if (chatty)
10916                Log.d(TAG, "Removing package " + ps.name);
10917        }
10918
10919        // writer
10920        synchronized (mPackages) {
10921            mPackages.remove(ps.name);
10922            final PackageParser.Package pkg = ps.pkg;
10923            if (pkg != null) {
10924                cleanPackageDataStructuresLILPw(pkg, chatty);
10925            }
10926        }
10927    }
10928
10929    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10930        if (DEBUG_INSTALL) {
10931            if (chatty)
10932                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10933        }
10934
10935        // writer
10936        synchronized (mPackages) {
10937            // Remove the parent package
10938            mPackages.remove(pkg.applicationInfo.packageName);
10939            cleanPackageDataStructuresLILPw(pkg, chatty);
10940
10941            // Remove the child packages
10942            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10943            for (int i = 0; i < childCount; i++) {
10944                PackageParser.Package childPkg = pkg.childPackages.get(i);
10945                mPackages.remove(childPkg.applicationInfo.packageName);
10946                cleanPackageDataStructuresLILPw(childPkg, chatty);
10947            }
10948        }
10949    }
10950
10951    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10952        int N = pkg.providers.size();
10953        StringBuilder r = null;
10954        int i;
10955        for (i=0; i<N; i++) {
10956            PackageParser.Provider p = pkg.providers.get(i);
10957            mProviders.removeProvider(p);
10958            if (p.info.authority == null) {
10959
10960                /* There was another ContentProvider with this authority when
10961                 * this app was installed so this authority is null,
10962                 * Ignore it as we don't have to unregister the provider.
10963                 */
10964                continue;
10965            }
10966            String names[] = p.info.authority.split(";");
10967            for (int j = 0; j < names.length; j++) {
10968                if (mProvidersByAuthority.get(names[j]) == p) {
10969                    mProvidersByAuthority.remove(names[j]);
10970                    if (DEBUG_REMOVE) {
10971                        if (chatty)
10972                            Log.d(TAG, "Unregistered content provider: " + names[j]
10973                                    + ", className = " + p.info.name + ", isSyncable = "
10974                                    + p.info.isSyncable);
10975                    }
10976                }
10977            }
10978            if (DEBUG_REMOVE && chatty) {
10979                if (r == null) {
10980                    r = new StringBuilder(256);
10981                } else {
10982                    r.append(' ');
10983                }
10984                r.append(p.info.name);
10985            }
10986        }
10987        if (r != null) {
10988            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10989        }
10990
10991        N = pkg.services.size();
10992        r = null;
10993        for (i=0; i<N; i++) {
10994            PackageParser.Service s = pkg.services.get(i);
10995            mServices.removeService(s);
10996            if (chatty) {
10997                if (r == null) {
10998                    r = new StringBuilder(256);
10999                } else {
11000                    r.append(' ');
11001                }
11002                r.append(s.info.name);
11003            }
11004        }
11005        if (r != null) {
11006            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11007        }
11008
11009        N = pkg.receivers.size();
11010        r = null;
11011        for (i=0; i<N; i++) {
11012            PackageParser.Activity a = pkg.receivers.get(i);
11013            mReceivers.removeActivity(a, "receiver");
11014            if (DEBUG_REMOVE && chatty) {
11015                if (r == null) {
11016                    r = new StringBuilder(256);
11017                } else {
11018                    r.append(' ');
11019                }
11020                r.append(a.info.name);
11021            }
11022        }
11023        if (r != null) {
11024            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11025        }
11026
11027        N = pkg.activities.size();
11028        r = null;
11029        for (i=0; i<N; i++) {
11030            PackageParser.Activity a = pkg.activities.get(i);
11031            mActivities.removeActivity(a, "activity");
11032            if (DEBUG_REMOVE && chatty) {
11033                if (r == null) {
11034                    r = new StringBuilder(256);
11035                } else {
11036                    r.append(' ');
11037                }
11038                r.append(a.info.name);
11039            }
11040        }
11041        if (r != null) {
11042            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11043        }
11044
11045        N = pkg.permissions.size();
11046        r = null;
11047        for (i=0; i<N; i++) {
11048            PackageParser.Permission p = pkg.permissions.get(i);
11049            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11050            if (bp == null) {
11051                bp = mSettings.mPermissionTrees.get(p.info.name);
11052            }
11053            if (bp != null && bp.perm == p) {
11054                bp.perm = null;
11055                if (DEBUG_REMOVE && chatty) {
11056                    if (r == null) {
11057                        r = new StringBuilder(256);
11058                    } else {
11059                        r.append(' ');
11060                    }
11061                    r.append(p.info.name);
11062                }
11063            }
11064            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11065                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11066                if (appOpPkgs != null) {
11067                    appOpPkgs.remove(pkg.packageName);
11068                }
11069            }
11070        }
11071        if (r != null) {
11072            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11073        }
11074
11075        N = pkg.requestedPermissions.size();
11076        r = null;
11077        for (i=0; i<N; i++) {
11078            String perm = pkg.requestedPermissions.get(i);
11079            BasePermission bp = mSettings.mPermissions.get(perm);
11080            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11081                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11082                if (appOpPkgs != null) {
11083                    appOpPkgs.remove(pkg.packageName);
11084                    if (appOpPkgs.isEmpty()) {
11085                        mAppOpPermissionPackages.remove(perm);
11086                    }
11087                }
11088            }
11089        }
11090        if (r != null) {
11091            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11092        }
11093
11094        N = pkg.instrumentation.size();
11095        r = null;
11096        for (i=0; i<N; i++) {
11097            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11098            mInstrumentation.remove(a.getComponentName());
11099            if (DEBUG_REMOVE && chatty) {
11100                if (r == null) {
11101                    r = new StringBuilder(256);
11102                } else {
11103                    r.append(' ');
11104                }
11105                r.append(a.info.name);
11106            }
11107        }
11108        if (r != null) {
11109            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11110        }
11111
11112        r = null;
11113        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11114            // Only system apps can hold shared libraries.
11115            if (pkg.libraryNames != null) {
11116                for (i = 0; i < pkg.libraryNames.size(); i++) {
11117                    String name = pkg.libraryNames.get(i);
11118                    if (removeSharedLibraryLPw(name, 0)) {
11119                        if (DEBUG_REMOVE && chatty) {
11120                            if (r == null) {
11121                                r = new StringBuilder(256);
11122                            } else {
11123                                r.append(' ');
11124                            }
11125                            r.append(name);
11126                        }
11127                    }
11128                }
11129            }
11130        }
11131
11132        r = null;
11133
11134        // Any package can hold static shared libraries.
11135        if (pkg.staticSharedLibName != null) {
11136            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11137                if (DEBUG_REMOVE && chatty) {
11138                    if (r == null) {
11139                        r = new StringBuilder(256);
11140                    } else {
11141                        r.append(' ');
11142                    }
11143                    r.append(pkg.staticSharedLibName);
11144                }
11145            }
11146        }
11147
11148        if (r != null) {
11149            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11150        }
11151    }
11152
11153    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11154        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11155            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11156                return true;
11157            }
11158        }
11159        return false;
11160    }
11161
11162    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11163    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11164    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11165
11166    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11167        // Update the parent permissions
11168        updatePermissionsLPw(pkg.packageName, pkg, flags);
11169        // Update the child permissions
11170        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11171        for (int i = 0; i < childCount; i++) {
11172            PackageParser.Package childPkg = pkg.childPackages.get(i);
11173            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11174        }
11175    }
11176
11177    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11178            int flags) {
11179        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11180        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11181    }
11182
11183    private void updatePermissionsLPw(String changingPkg,
11184            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11185        // Make sure there are no dangling permission trees.
11186        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11187        while (it.hasNext()) {
11188            final BasePermission bp = it.next();
11189            if (bp.packageSetting == null) {
11190                // We may not yet have parsed the package, so just see if
11191                // we still know about its settings.
11192                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11193            }
11194            if (bp.packageSetting == null) {
11195                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11196                        + " from package " + bp.sourcePackage);
11197                it.remove();
11198            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11199                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11200                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11201                            + " from package " + bp.sourcePackage);
11202                    flags |= UPDATE_PERMISSIONS_ALL;
11203                    it.remove();
11204                }
11205            }
11206        }
11207
11208        // Make sure all dynamic permissions have been assigned to a package,
11209        // and make sure there are no dangling permissions.
11210        it = mSettings.mPermissions.values().iterator();
11211        while (it.hasNext()) {
11212            final BasePermission bp = it.next();
11213            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11214                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11215                        + bp.name + " pkg=" + bp.sourcePackage
11216                        + " info=" + bp.pendingInfo);
11217                if (bp.packageSetting == null && bp.pendingInfo != null) {
11218                    final BasePermission tree = findPermissionTreeLP(bp.name);
11219                    if (tree != null && tree.perm != null) {
11220                        bp.packageSetting = tree.packageSetting;
11221                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11222                                new PermissionInfo(bp.pendingInfo));
11223                        bp.perm.info.packageName = tree.perm.info.packageName;
11224                        bp.perm.info.name = bp.name;
11225                        bp.uid = tree.uid;
11226                    }
11227                }
11228            }
11229            if (bp.packageSetting == null) {
11230                // We may not yet have parsed the package, so just see if
11231                // we still know about its settings.
11232                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11233            }
11234            if (bp.packageSetting == null) {
11235                Slog.w(TAG, "Removing dangling permission: " + bp.name
11236                        + " from package " + bp.sourcePackage);
11237                it.remove();
11238            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11239                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11240                    Slog.i(TAG, "Removing old permission: " + bp.name
11241                            + " from package " + bp.sourcePackage);
11242                    flags |= UPDATE_PERMISSIONS_ALL;
11243                    it.remove();
11244                }
11245            }
11246        }
11247
11248        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11249        // Now update the permissions for all packages, in particular
11250        // replace the granted permissions of the system packages.
11251        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11252            for (PackageParser.Package pkg : mPackages.values()) {
11253                if (pkg != pkgInfo) {
11254                    // Only replace for packages on requested volume
11255                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11256                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11257                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11258                    grantPermissionsLPw(pkg, replace, changingPkg);
11259                }
11260            }
11261        }
11262
11263        if (pkgInfo != null) {
11264            // Only replace for packages on requested volume
11265            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11266            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11267                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11268            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11269        }
11270        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11271    }
11272
11273    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11274            String packageOfInterest) {
11275        // IMPORTANT: There are two types of permissions: install and runtime.
11276        // Install time permissions are granted when the app is installed to
11277        // all device users and users added in the future. Runtime permissions
11278        // are granted at runtime explicitly to specific users. Normal and signature
11279        // protected permissions are install time permissions. Dangerous permissions
11280        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11281        // otherwise they are runtime permissions. This function does not manage
11282        // runtime permissions except for the case an app targeting Lollipop MR1
11283        // being upgraded to target a newer SDK, in which case dangerous permissions
11284        // are transformed from install time to runtime ones.
11285
11286        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11287        if (ps == null) {
11288            return;
11289        }
11290
11291        PermissionsState permissionsState = ps.getPermissionsState();
11292        PermissionsState origPermissions = permissionsState;
11293
11294        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11295
11296        boolean runtimePermissionsRevoked = false;
11297        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11298
11299        boolean changedInstallPermission = false;
11300
11301        if (replace) {
11302            ps.installPermissionsFixed = false;
11303            if (!ps.isSharedUser()) {
11304                origPermissions = new PermissionsState(permissionsState);
11305                permissionsState.reset();
11306            } else {
11307                // We need to know only about runtime permission changes since the
11308                // calling code always writes the install permissions state but
11309                // the runtime ones are written only if changed. The only cases of
11310                // changed runtime permissions here are promotion of an install to
11311                // runtime and revocation of a runtime from a shared user.
11312                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11313                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11314                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11315                    runtimePermissionsRevoked = true;
11316                }
11317            }
11318        }
11319
11320        permissionsState.setGlobalGids(mGlobalGids);
11321
11322        final int N = pkg.requestedPermissions.size();
11323        for (int i=0; i<N; i++) {
11324            final String name = pkg.requestedPermissions.get(i);
11325            final BasePermission bp = mSettings.mPermissions.get(name);
11326
11327            if (DEBUG_INSTALL) {
11328                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11329            }
11330
11331            if (bp == null || bp.packageSetting == null) {
11332                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11333                    Slog.w(TAG, "Unknown permission " + name
11334                            + " in package " + pkg.packageName);
11335                }
11336                continue;
11337            }
11338
11339
11340            // Limit ephemeral apps to ephemeral allowed permissions.
11341            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11342                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11343                        + pkg.packageName);
11344                continue;
11345            }
11346
11347            final String perm = bp.name;
11348            boolean allowedSig = false;
11349            int grant = GRANT_DENIED;
11350
11351            // Keep track of app op permissions.
11352            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11353                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11354                if (pkgs == null) {
11355                    pkgs = new ArraySet<>();
11356                    mAppOpPermissionPackages.put(bp.name, pkgs);
11357                }
11358                pkgs.add(pkg.packageName);
11359            }
11360
11361            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11362            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11363                    >= Build.VERSION_CODES.M;
11364            switch (level) {
11365                case PermissionInfo.PROTECTION_NORMAL: {
11366                    // For all apps normal permissions are install time ones.
11367                    grant = GRANT_INSTALL;
11368                } break;
11369
11370                case PermissionInfo.PROTECTION_DANGEROUS: {
11371                    // If a permission review is required for legacy apps we represent
11372                    // their permissions as always granted runtime ones since we need
11373                    // to keep the review required permission flag per user while an
11374                    // install permission's state is shared across all users.
11375                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11376                        // For legacy apps dangerous permissions are install time ones.
11377                        grant = GRANT_INSTALL;
11378                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11379                        // For legacy apps that became modern, install becomes runtime.
11380                        grant = GRANT_UPGRADE;
11381                    } else if (mPromoteSystemApps
11382                            && isSystemApp(ps)
11383                            && mExistingSystemPackages.contains(ps.name)) {
11384                        // For legacy system apps, install becomes runtime.
11385                        // We cannot check hasInstallPermission() for system apps since those
11386                        // permissions were granted implicitly and not persisted pre-M.
11387                        grant = GRANT_UPGRADE;
11388                    } else {
11389                        // For modern apps keep runtime permissions unchanged.
11390                        grant = GRANT_RUNTIME;
11391                    }
11392                } break;
11393
11394                case PermissionInfo.PROTECTION_SIGNATURE: {
11395                    // For all apps signature permissions are install time ones.
11396                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11397                    if (allowedSig) {
11398                        grant = GRANT_INSTALL;
11399                    }
11400                } break;
11401            }
11402
11403            if (DEBUG_INSTALL) {
11404                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11405            }
11406
11407            if (grant != GRANT_DENIED) {
11408                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11409                    // If this is an existing, non-system package, then
11410                    // we can't add any new permissions to it.
11411                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11412                        // Except...  if this is a permission that was added
11413                        // to the platform (note: need to only do this when
11414                        // updating the platform).
11415                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11416                            grant = GRANT_DENIED;
11417                        }
11418                    }
11419                }
11420
11421                switch (grant) {
11422                    case GRANT_INSTALL: {
11423                        // Revoke this as runtime permission to handle the case of
11424                        // a runtime permission being downgraded to an install one.
11425                        // Also in permission review mode we keep dangerous permissions
11426                        // for legacy apps
11427                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11428                            if (origPermissions.getRuntimePermissionState(
11429                                    bp.name, userId) != null) {
11430                                // Revoke the runtime permission and clear the flags.
11431                                origPermissions.revokeRuntimePermission(bp, userId);
11432                                origPermissions.updatePermissionFlags(bp, userId,
11433                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11434                                // If we revoked a permission permission, we have to write.
11435                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11436                                        changedRuntimePermissionUserIds, userId);
11437                            }
11438                        }
11439                        // Grant an install permission.
11440                        if (permissionsState.grantInstallPermission(bp) !=
11441                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11442                            changedInstallPermission = true;
11443                        }
11444                    } break;
11445
11446                    case GRANT_RUNTIME: {
11447                        // Grant previously granted runtime permissions.
11448                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11449                            PermissionState permissionState = origPermissions
11450                                    .getRuntimePermissionState(bp.name, userId);
11451                            int flags = permissionState != null
11452                                    ? permissionState.getFlags() : 0;
11453                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11454                                // Don't propagate the permission in a permission review mode if
11455                                // the former was revoked, i.e. marked to not propagate on upgrade.
11456                                // Note that in a permission review mode install permissions are
11457                                // represented as constantly granted runtime ones since we need to
11458                                // keep a per user state associated with the permission. Also the
11459                                // revoke on upgrade flag is no longer applicable and is reset.
11460                                final boolean revokeOnUpgrade = (flags & PackageManager
11461                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11462                                if (revokeOnUpgrade) {
11463                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11464                                    // Since we changed the flags, we have to write.
11465                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11466                                            changedRuntimePermissionUserIds, userId);
11467                                }
11468                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11469                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11470                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11471                                        // If we cannot put the permission as it was,
11472                                        // we have to write.
11473                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11474                                                changedRuntimePermissionUserIds, userId);
11475                                    }
11476                                }
11477
11478                                // If the app supports runtime permissions no need for a review.
11479                                if (mPermissionReviewRequired
11480                                        && appSupportsRuntimePermissions
11481                                        && (flags & PackageManager
11482                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11483                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11484                                    // Since we changed the flags, we have to write.
11485                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11486                                            changedRuntimePermissionUserIds, userId);
11487                                }
11488                            } else if (mPermissionReviewRequired
11489                                    && !appSupportsRuntimePermissions) {
11490                                // For legacy apps that need a permission review, every new
11491                                // runtime permission is granted but it is pending a review.
11492                                // We also need to review only platform defined runtime
11493                                // permissions as these are the only ones the platform knows
11494                                // how to disable the API to simulate revocation as legacy
11495                                // apps don't expect to run with revoked permissions.
11496                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11497                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11498                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11499                                        // We changed the flags, hence have to write.
11500                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11501                                                changedRuntimePermissionUserIds, userId);
11502                                    }
11503                                }
11504                                if (permissionsState.grantRuntimePermission(bp, userId)
11505                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11506                                    // We changed the permission, hence have to write.
11507                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11508                                            changedRuntimePermissionUserIds, userId);
11509                                }
11510                            }
11511                            // Propagate the permission flags.
11512                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11513                        }
11514                    } break;
11515
11516                    case GRANT_UPGRADE: {
11517                        // Grant runtime permissions for a previously held install permission.
11518                        PermissionState permissionState = origPermissions
11519                                .getInstallPermissionState(bp.name);
11520                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11521
11522                        if (origPermissions.revokeInstallPermission(bp)
11523                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11524                            // We will be transferring the permission flags, so clear them.
11525                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11526                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11527                            changedInstallPermission = true;
11528                        }
11529
11530                        // If the permission is not to be promoted to runtime we ignore it and
11531                        // also its other flags as they are not applicable to install permissions.
11532                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11533                            for (int userId : currentUserIds) {
11534                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11535                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11536                                    // Transfer the permission flags.
11537                                    permissionsState.updatePermissionFlags(bp, userId,
11538                                            flags, flags);
11539                                    // If we granted the permission, we have to write.
11540                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11541                                            changedRuntimePermissionUserIds, userId);
11542                                }
11543                            }
11544                        }
11545                    } break;
11546
11547                    default: {
11548                        if (packageOfInterest == null
11549                                || packageOfInterest.equals(pkg.packageName)) {
11550                            Slog.w(TAG, "Not granting permission " + perm
11551                                    + " to package " + pkg.packageName
11552                                    + " because it was previously installed without");
11553                        }
11554                    } break;
11555                }
11556            } else {
11557                if (permissionsState.revokeInstallPermission(bp) !=
11558                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11559                    // Also drop the permission flags.
11560                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11561                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11562                    changedInstallPermission = true;
11563                    Slog.i(TAG, "Un-granting permission " + perm
11564                            + " from package " + pkg.packageName
11565                            + " (protectionLevel=" + bp.protectionLevel
11566                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11567                            + ")");
11568                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11569                    // Don't print warning for app op permissions, since it is fine for them
11570                    // not to be granted, there is a UI for the user to decide.
11571                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11572                        Slog.w(TAG, "Not granting permission " + perm
11573                                + " to package " + pkg.packageName
11574                                + " (protectionLevel=" + bp.protectionLevel
11575                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11576                                + ")");
11577                    }
11578                }
11579            }
11580        }
11581
11582        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11583                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11584            // This is the first that we have heard about this package, so the
11585            // permissions we have now selected are fixed until explicitly
11586            // changed.
11587            ps.installPermissionsFixed = true;
11588        }
11589
11590        // Persist the runtime permissions state for users with changes. If permissions
11591        // were revoked because no app in the shared user declares them we have to
11592        // write synchronously to avoid losing runtime permissions state.
11593        for (int userId : changedRuntimePermissionUserIds) {
11594            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11595        }
11596    }
11597
11598    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11599        boolean allowed = false;
11600        final int NP = PackageParser.NEW_PERMISSIONS.length;
11601        for (int ip=0; ip<NP; ip++) {
11602            final PackageParser.NewPermissionInfo npi
11603                    = PackageParser.NEW_PERMISSIONS[ip];
11604            if (npi.name.equals(perm)
11605                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11606                allowed = true;
11607                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11608                        + pkg.packageName);
11609                break;
11610            }
11611        }
11612        return allowed;
11613    }
11614
11615    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11616            BasePermission bp, PermissionsState origPermissions) {
11617        boolean privilegedPermission = (bp.protectionLevel
11618                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11619        boolean privappPermissionsDisable =
11620                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11621        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11622        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11623        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11624                && !platformPackage && platformPermission) {
11625            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11626                    .getPrivAppPermissions(pkg.packageName);
11627            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11628            if (!whitelisted) {
11629                Slog.w(TAG, "Privileged permission " + perm + " for package "
11630                        + pkg.packageName + " - not in privapp-permissions whitelist");
11631                if (!mSystemReady) {
11632                    if (mPrivappPermissionsViolations == null) {
11633                        mPrivappPermissionsViolations = new ArraySet<>();
11634                    }
11635                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11636                }
11637                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11638                    return false;
11639                }
11640            }
11641        }
11642        boolean allowed = (compareSignatures(
11643                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11644                        == PackageManager.SIGNATURE_MATCH)
11645                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11646                        == PackageManager.SIGNATURE_MATCH);
11647        if (!allowed && privilegedPermission) {
11648            if (isSystemApp(pkg)) {
11649                // For updated system applications, a system permission
11650                // is granted only if it had been defined by the original application.
11651                if (pkg.isUpdatedSystemApp()) {
11652                    final PackageSetting sysPs = mSettings
11653                            .getDisabledSystemPkgLPr(pkg.packageName);
11654                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11655                        // If the original was granted this permission, we take
11656                        // that grant decision as read and propagate it to the
11657                        // update.
11658                        if (sysPs.isPrivileged()) {
11659                            allowed = true;
11660                        }
11661                    } else {
11662                        // The system apk may have been updated with an older
11663                        // version of the one on the data partition, but which
11664                        // granted a new system permission that it didn't have
11665                        // before.  In this case we do want to allow the app to
11666                        // now get the new permission if the ancestral apk is
11667                        // privileged to get it.
11668                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11669                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11670                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11671                                    allowed = true;
11672                                    break;
11673                                }
11674                            }
11675                        }
11676                        // Also if a privileged parent package on the system image or any of
11677                        // its children requested a privileged permission, the updated child
11678                        // packages can also get the permission.
11679                        if (pkg.parentPackage != null) {
11680                            final PackageSetting disabledSysParentPs = mSettings
11681                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11682                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11683                                    && disabledSysParentPs.isPrivileged()) {
11684                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11685                                    allowed = true;
11686                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11687                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11688                                    for (int i = 0; i < count; i++) {
11689                                        PackageParser.Package disabledSysChildPkg =
11690                                                disabledSysParentPs.pkg.childPackages.get(i);
11691                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11692                                                perm)) {
11693                                            allowed = true;
11694                                            break;
11695                                        }
11696                                    }
11697                                }
11698                            }
11699                        }
11700                    }
11701                } else {
11702                    allowed = isPrivilegedApp(pkg);
11703                }
11704            }
11705        }
11706        if (!allowed) {
11707            if (!allowed && (bp.protectionLevel
11708                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11709                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11710                // If this was a previously normal/dangerous permission that got moved
11711                // to a system permission as part of the runtime permission redesign, then
11712                // we still want to blindly grant it to old apps.
11713                allowed = true;
11714            }
11715            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11716                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11717                // If this permission is to be granted to the system installer and
11718                // this app is an installer, then it gets the permission.
11719                allowed = true;
11720            }
11721            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11722                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11723                // If this permission is to be granted to the system verifier and
11724                // this app is a verifier, then it gets the permission.
11725                allowed = true;
11726            }
11727            if (!allowed && (bp.protectionLevel
11728                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11729                    && isSystemApp(pkg)) {
11730                // Any pre-installed system app is allowed to get this permission.
11731                allowed = true;
11732            }
11733            if (!allowed && (bp.protectionLevel
11734                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11735                // For development permissions, a development permission
11736                // is granted only if it was already granted.
11737                allowed = origPermissions.hasInstallPermission(perm);
11738            }
11739            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11740                    && pkg.packageName.equals(mSetupWizardPackage)) {
11741                // If this permission is to be granted to the system setup wizard and
11742                // this app is a setup wizard, then it gets the permission.
11743                allowed = true;
11744            }
11745        }
11746        return allowed;
11747    }
11748
11749    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11750        final int permCount = pkg.requestedPermissions.size();
11751        for (int j = 0; j < permCount; j++) {
11752            String requestedPermission = pkg.requestedPermissions.get(j);
11753            if (permission.equals(requestedPermission)) {
11754                return true;
11755            }
11756        }
11757        return false;
11758    }
11759
11760    final class ActivityIntentResolver
11761            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11762        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11763                boolean defaultOnly, int userId) {
11764            if (!sUserManager.exists(userId)) return null;
11765            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11766            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11767        }
11768
11769        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11770                int userId) {
11771            if (!sUserManager.exists(userId)) return null;
11772            mFlags = flags;
11773            return super.queryIntent(intent, resolvedType,
11774                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11775                    userId);
11776        }
11777
11778        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11779                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11780            if (!sUserManager.exists(userId)) return null;
11781            if (packageActivities == null) {
11782                return null;
11783            }
11784            mFlags = flags;
11785            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11786            final int N = packageActivities.size();
11787            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11788                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11789
11790            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11791            for (int i = 0; i < N; ++i) {
11792                intentFilters = packageActivities.get(i).intents;
11793                if (intentFilters != null && intentFilters.size() > 0) {
11794                    PackageParser.ActivityIntentInfo[] array =
11795                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11796                    intentFilters.toArray(array);
11797                    listCut.add(array);
11798                }
11799            }
11800            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11801        }
11802
11803        /**
11804         * Finds a privileged activity that matches the specified activity names.
11805         */
11806        private PackageParser.Activity findMatchingActivity(
11807                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11808            for (PackageParser.Activity sysActivity : activityList) {
11809                if (sysActivity.info.name.equals(activityInfo.name)) {
11810                    return sysActivity;
11811                }
11812                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11813                    return sysActivity;
11814                }
11815                if (sysActivity.info.targetActivity != null) {
11816                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11817                        return sysActivity;
11818                    }
11819                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11820                        return sysActivity;
11821                    }
11822                }
11823            }
11824            return null;
11825        }
11826
11827        public class IterGenerator<E> {
11828            public Iterator<E> generate(ActivityIntentInfo info) {
11829                return null;
11830            }
11831        }
11832
11833        public class ActionIterGenerator extends IterGenerator<String> {
11834            @Override
11835            public Iterator<String> generate(ActivityIntentInfo info) {
11836                return info.actionsIterator();
11837            }
11838        }
11839
11840        public class CategoriesIterGenerator extends IterGenerator<String> {
11841            @Override
11842            public Iterator<String> generate(ActivityIntentInfo info) {
11843                return info.categoriesIterator();
11844            }
11845        }
11846
11847        public class SchemesIterGenerator extends IterGenerator<String> {
11848            @Override
11849            public Iterator<String> generate(ActivityIntentInfo info) {
11850                return info.schemesIterator();
11851            }
11852        }
11853
11854        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11855            @Override
11856            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11857                return info.authoritiesIterator();
11858            }
11859        }
11860
11861        /**
11862         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11863         * MODIFIED. Do not pass in a list that should not be changed.
11864         */
11865        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11866                IterGenerator<T> generator, Iterator<T> searchIterator) {
11867            // loop through the set of actions; every one must be found in the intent filter
11868            while (searchIterator.hasNext()) {
11869                // we must have at least one filter in the list to consider a match
11870                if (intentList.size() == 0) {
11871                    break;
11872                }
11873
11874                final T searchAction = searchIterator.next();
11875
11876                // loop through the set of intent filters
11877                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11878                while (intentIter.hasNext()) {
11879                    final ActivityIntentInfo intentInfo = intentIter.next();
11880                    boolean selectionFound = false;
11881
11882                    // loop through the intent filter's selection criteria; at least one
11883                    // of them must match the searched criteria
11884                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11885                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11886                        final T intentSelection = intentSelectionIter.next();
11887                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11888                            selectionFound = true;
11889                            break;
11890                        }
11891                    }
11892
11893                    // the selection criteria wasn't found in this filter's set; this filter
11894                    // is not a potential match
11895                    if (!selectionFound) {
11896                        intentIter.remove();
11897                    }
11898                }
11899            }
11900        }
11901
11902        private boolean isProtectedAction(ActivityIntentInfo filter) {
11903            final Iterator<String> actionsIter = filter.actionsIterator();
11904            while (actionsIter != null && actionsIter.hasNext()) {
11905                final String filterAction = actionsIter.next();
11906                if (PROTECTED_ACTIONS.contains(filterAction)) {
11907                    return true;
11908                }
11909            }
11910            return false;
11911        }
11912
11913        /**
11914         * Adjusts the priority of the given intent filter according to policy.
11915         * <p>
11916         * <ul>
11917         * <li>The priority for non privileged applications is capped to '0'</li>
11918         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11919         * <li>The priority for unbundled updates to privileged applications is capped to the
11920         *      priority defined on the system partition</li>
11921         * </ul>
11922         * <p>
11923         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11924         * allowed to obtain any priority on any action.
11925         */
11926        private void adjustPriority(
11927                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11928            // nothing to do; priority is fine as-is
11929            if (intent.getPriority() <= 0) {
11930                return;
11931            }
11932
11933            final ActivityInfo activityInfo = intent.activity.info;
11934            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11935
11936            final boolean privilegedApp =
11937                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11938            if (!privilegedApp) {
11939                // non-privileged applications can never define a priority >0
11940                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11941                        + " package: " + applicationInfo.packageName
11942                        + " activity: " + intent.activity.className
11943                        + " origPrio: " + intent.getPriority());
11944                intent.setPriority(0);
11945                return;
11946            }
11947
11948            if (systemActivities == null) {
11949                // the system package is not disabled; we're parsing the system partition
11950                if (isProtectedAction(intent)) {
11951                    if (mDeferProtectedFilters) {
11952                        // We can't deal with these just yet. No component should ever obtain a
11953                        // >0 priority for a protected actions, with ONE exception -- the setup
11954                        // wizard. The setup wizard, however, cannot be known until we're able to
11955                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11956                        // until all intent filters have been processed. Chicken, meet egg.
11957                        // Let the filter temporarily have a high priority and rectify the
11958                        // priorities after all system packages have been scanned.
11959                        mProtectedFilters.add(intent);
11960                        if (DEBUG_FILTERS) {
11961                            Slog.i(TAG, "Protected action; save for later;"
11962                                    + " package: " + applicationInfo.packageName
11963                                    + " activity: " + intent.activity.className
11964                                    + " origPrio: " + intent.getPriority());
11965                        }
11966                        return;
11967                    } else {
11968                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11969                            Slog.i(TAG, "No setup wizard;"
11970                                + " All protected intents capped to priority 0");
11971                        }
11972                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11973                            if (DEBUG_FILTERS) {
11974                                Slog.i(TAG, "Found setup wizard;"
11975                                    + " allow priority " + intent.getPriority() + ";"
11976                                    + " package: " + intent.activity.info.packageName
11977                                    + " activity: " + intent.activity.className
11978                                    + " priority: " + intent.getPriority());
11979                            }
11980                            // setup wizard gets whatever it wants
11981                            return;
11982                        }
11983                        Slog.w(TAG, "Protected action; cap priority to 0;"
11984                                + " package: " + intent.activity.info.packageName
11985                                + " activity: " + intent.activity.className
11986                                + " origPrio: " + intent.getPriority());
11987                        intent.setPriority(0);
11988                        return;
11989                    }
11990                }
11991                // privileged apps on the system image get whatever priority they request
11992                return;
11993            }
11994
11995            // privileged app unbundled update ... try to find the same activity
11996            final PackageParser.Activity foundActivity =
11997                    findMatchingActivity(systemActivities, activityInfo);
11998            if (foundActivity == null) {
11999                // this is a new activity; it cannot obtain >0 priority
12000                if (DEBUG_FILTERS) {
12001                    Slog.i(TAG, "New activity; cap priority to 0;"
12002                            + " package: " + applicationInfo.packageName
12003                            + " activity: " + intent.activity.className
12004                            + " origPrio: " + intent.getPriority());
12005                }
12006                intent.setPriority(0);
12007                return;
12008            }
12009
12010            // found activity, now check for filter equivalence
12011
12012            // a shallow copy is enough; we modify the list, not its contents
12013            final List<ActivityIntentInfo> intentListCopy =
12014                    new ArrayList<>(foundActivity.intents);
12015            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12016
12017            // find matching action subsets
12018            final Iterator<String> actionsIterator = intent.actionsIterator();
12019            if (actionsIterator != null) {
12020                getIntentListSubset(
12021                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12022                if (intentListCopy.size() == 0) {
12023                    // no more intents to match; we're not equivalent
12024                    if (DEBUG_FILTERS) {
12025                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12026                                + " package: " + applicationInfo.packageName
12027                                + " activity: " + intent.activity.className
12028                                + " origPrio: " + intent.getPriority());
12029                    }
12030                    intent.setPriority(0);
12031                    return;
12032                }
12033            }
12034
12035            // find matching category subsets
12036            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12037            if (categoriesIterator != null) {
12038                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12039                        categoriesIterator);
12040                if (intentListCopy.size() == 0) {
12041                    // no more intents to match; we're not equivalent
12042                    if (DEBUG_FILTERS) {
12043                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12044                                + " package: " + applicationInfo.packageName
12045                                + " activity: " + intent.activity.className
12046                                + " origPrio: " + intent.getPriority());
12047                    }
12048                    intent.setPriority(0);
12049                    return;
12050                }
12051            }
12052
12053            // find matching schemes subsets
12054            final Iterator<String> schemesIterator = intent.schemesIterator();
12055            if (schemesIterator != null) {
12056                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12057                        schemesIterator);
12058                if (intentListCopy.size() == 0) {
12059                    // no more intents to match; we're not equivalent
12060                    if (DEBUG_FILTERS) {
12061                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12062                                + " package: " + applicationInfo.packageName
12063                                + " activity: " + intent.activity.className
12064                                + " origPrio: " + intent.getPriority());
12065                    }
12066                    intent.setPriority(0);
12067                    return;
12068                }
12069            }
12070
12071            // find matching authorities subsets
12072            final Iterator<IntentFilter.AuthorityEntry>
12073                    authoritiesIterator = intent.authoritiesIterator();
12074            if (authoritiesIterator != null) {
12075                getIntentListSubset(intentListCopy,
12076                        new AuthoritiesIterGenerator(),
12077                        authoritiesIterator);
12078                if (intentListCopy.size() == 0) {
12079                    // no more intents to match; we're not equivalent
12080                    if (DEBUG_FILTERS) {
12081                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12082                                + " package: " + applicationInfo.packageName
12083                                + " activity: " + intent.activity.className
12084                                + " origPrio: " + intent.getPriority());
12085                    }
12086                    intent.setPriority(0);
12087                    return;
12088                }
12089            }
12090
12091            // we found matching filter(s); app gets the max priority of all intents
12092            int cappedPriority = 0;
12093            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12094                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12095            }
12096            if (intent.getPriority() > cappedPriority) {
12097                if (DEBUG_FILTERS) {
12098                    Slog.i(TAG, "Found matching filter(s);"
12099                            + " cap priority to " + cappedPriority + ";"
12100                            + " package: " + applicationInfo.packageName
12101                            + " activity: " + intent.activity.className
12102                            + " origPrio: " + intent.getPriority());
12103                }
12104                intent.setPriority(cappedPriority);
12105                return;
12106            }
12107            // all this for nothing; the requested priority was <= what was on the system
12108        }
12109
12110        public final void addActivity(PackageParser.Activity a, String type) {
12111            mActivities.put(a.getComponentName(), a);
12112            if (DEBUG_SHOW_INFO)
12113                Log.v(
12114                TAG, "  " + type + " " +
12115                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12116            if (DEBUG_SHOW_INFO)
12117                Log.v(TAG, "    Class=" + a.info.name);
12118            final int NI = a.intents.size();
12119            for (int j=0; j<NI; j++) {
12120                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12121                if ("activity".equals(type)) {
12122                    final PackageSetting ps =
12123                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12124                    final List<PackageParser.Activity> systemActivities =
12125                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12126                    adjustPriority(systemActivities, intent);
12127                }
12128                if (DEBUG_SHOW_INFO) {
12129                    Log.v(TAG, "    IntentFilter:");
12130                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12131                }
12132                if (!intent.debugCheck()) {
12133                    Log.w(TAG, "==> For Activity " + a.info.name);
12134                }
12135                addFilter(intent);
12136            }
12137        }
12138
12139        public final void removeActivity(PackageParser.Activity a, String type) {
12140            mActivities.remove(a.getComponentName());
12141            if (DEBUG_SHOW_INFO) {
12142                Log.v(TAG, "  " + type + " "
12143                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12144                                : a.info.name) + ":");
12145                Log.v(TAG, "    Class=" + a.info.name);
12146            }
12147            final int NI = a.intents.size();
12148            for (int j=0; j<NI; j++) {
12149                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12150                if (DEBUG_SHOW_INFO) {
12151                    Log.v(TAG, "    IntentFilter:");
12152                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12153                }
12154                removeFilter(intent);
12155            }
12156        }
12157
12158        @Override
12159        protected boolean allowFilterResult(
12160                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12161            ActivityInfo filterAi = filter.activity.info;
12162            for (int i=dest.size()-1; i>=0; i--) {
12163                ActivityInfo destAi = dest.get(i).activityInfo;
12164                if (destAi.name == filterAi.name
12165                        && destAi.packageName == filterAi.packageName) {
12166                    return false;
12167                }
12168            }
12169            return true;
12170        }
12171
12172        @Override
12173        protected ActivityIntentInfo[] newArray(int size) {
12174            return new ActivityIntentInfo[size];
12175        }
12176
12177        @Override
12178        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12179            if (!sUserManager.exists(userId)) return true;
12180            PackageParser.Package p = filter.activity.owner;
12181            if (p != null) {
12182                PackageSetting ps = (PackageSetting)p.mExtras;
12183                if (ps != null) {
12184                    // System apps are never considered stopped for purposes of
12185                    // filtering, because there may be no way for the user to
12186                    // actually re-launch them.
12187                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12188                            && ps.getStopped(userId);
12189                }
12190            }
12191            return false;
12192        }
12193
12194        @Override
12195        protected boolean isPackageForFilter(String packageName,
12196                PackageParser.ActivityIntentInfo info) {
12197            return packageName.equals(info.activity.owner.packageName);
12198        }
12199
12200        @Override
12201        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12202                int match, int userId) {
12203            if (!sUserManager.exists(userId)) return null;
12204            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12205                return null;
12206            }
12207            final PackageParser.Activity activity = info.activity;
12208            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12209            if (ps == null) {
12210                return null;
12211            }
12212            final PackageUserState userState = ps.readUserState(userId);
12213            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12214                    userState, userId);
12215            if (ai == null) {
12216                return null;
12217            }
12218            final boolean matchVisibleToInstantApp =
12219                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12220            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12221            // throw out filters that aren't visible to ephemeral apps
12222            if (matchVisibleToInstantApp
12223                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12224                return null;
12225            }
12226            // throw out ephemeral filters if we're not explicitly requesting them
12227            if (!isInstantApp && userState.instantApp) {
12228                return null;
12229            }
12230            final ResolveInfo res = new ResolveInfo();
12231            res.activityInfo = ai;
12232            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12233                res.filter = info;
12234            }
12235            if (info != null) {
12236                res.handleAllWebDataURI = info.handleAllWebDataURI();
12237            }
12238            res.priority = info.getPriority();
12239            res.preferredOrder = activity.owner.mPreferredOrder;
12240            //System.out.println("Result: " + res.activityInfo.className +
12241            //                   " = " + res.priority);
12242            res.match = match;
12243            res.isDefault = info.hasDefault;
12244            res.labelRes = info.labelRes;
12245            res.nonLocalizedLabel = info.nonLocalizedLabel;
12246            if (userNeedsBadging(userId)) {
12247                res.noResourceId = true;
12248            } else {
12249                res.icon = info.icon;
12250            }
12251            res.iconResourceId = info.icon;
12252            res.system = res.activityInfo.applicationInfo.isSystemApp();
12253            return res;
12254        }
12255
12256        @Override
12257        protected void sortResults(List<ResolveInfo> results) {
12258            Collections.sort(results, mResolvePrioritySorter);
12259        }
12260
12261        @Override
12262        protected void dumpFilter(PrintWriter out, String prefix,
12263                PackageParser.ActivityIntentInfo filter) {
12264            out.print(prefix); out.print(
12265                    Integer.toHexString(System.identityHashCode(filter.activity)));
12266                    out.print(' ');
12267                    filter.activity.printComponentShortName(out);
12268                    out.print(" filter ");
12269                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12270        }
12271
12272        @Override
12273        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12274            return filter.activity;
12275        }
12276
12277        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12278            PackageParser.Activity activity = (PackageParser.Activity)label;
12279            out.print(prefix); out.print(
12280                    Integer.toHexString(System.identityHashCode(activity)));
12281                    out.print(' ');
12282                    activity.printComponentShortName(out);
12283            if (count > 1) {
12284                out.print(" ("); out.print(count); out.print(" filters)");
12285            }
12286            out.println();
12287        }
12288
12289        // Keys are String (activity class name), values are Activity.
12290        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12291                = new ArrayMap<ComponentName, PackageParser.Activity>();
12292        private int mFlags;
12293    }
12294
12295    private final class ServiceIntentResolver
12296            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12297        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12298                boolean defaultOnly, int userId) {
12299            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12300            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12301        }
12302
12303        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12304                int userId) {
12305            if (!sUserManager.exists(userId)) return null;
12306            mFlags = flags;
12307            return super.queryIntent(intent, resolvedType,
12308                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12309                    userId);
12310        }
12311
12312        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12313                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12314            if (!sUserManager.exists(userId)) return null;
12315            if (packageServices == null) {
12316                return null;
12317            }
12318            mFlags = flags;
12319            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12320            final int N = packageServices.size();
12321            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12322                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12323
12324            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12325            for (int i = 0; i < N; ++i) {
12326                intentFilters = packageServices.get(i).intents;
12327                if (intentFilters != null && intentFilters.size() > 0) {
12328                    PackageParser.ServiceIntentInfo[] array =
12329                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12330                    intentFilters.toArray(array);
12331                    listCut.add(array);
12332                }
12333            }
12334            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12335        }
12336
12337        public final void addService(PackageParser.Service s) {
12338            mServices.put(s.getComponentName(), s);
12339            if (DEBUG_SHOW_INFO) {
12340                Log.v(TAG, "  "
12341                        + (s.info.nonLocalizedLabel != null
12342                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12343                Log.v(TAG, "    Class=" + s.info.name);
12344            }
12345            final int NI = s.intents.size();
12346            int j;
12347            for (j=0; j<NI; j++) {
12348                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12349                if (DEBUG_SHOW_INFO) {
12350                    Log.v(TAG, "    IntentFilter:");
12351                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12352                }
12353                if (!intent.debugCheck()) {
12354                    Log.w(TAG, "==> For Service " + s.info.name);
12355                }
12356                addFilter(intent);
12357            }
12358        }
12359
12360        public final void removeService(PackageParser.Service s) {
12361            mServices.remove(s.getComponentName());
12362            if (DEBUG_SHOW_INFO) {
12363                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12364                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12365                Log.v(TAG, "    Class=" + s.info.name);
12366            }
12367            final int NI = s.intents.size();
12368            int j;
12369            for (j=0; j<NI; j++) {
12370                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12371                if (DEBUG_SHOW_INFO) {
12372                    Log.v(TAG, "    IntentFilter:");
12373                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12374                }
12375                removeFilter(intent);
12376            }
12377        }
12378
12379        @Override
12380        protected boolean allowFilterResult(
12381                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12382            ServiceInfo filterSi = filter.service.info;
12383            for (int i=dest.size()-1; i>=0; i--) {
12384                ServiceInfo destAi = dest.get(i).serviceInfo;
12385                if (destAi.name == filterSi.name
12386                        && destAi.packageName == filterSi.packageName) {
12387                    return false;
12388                }
12389            }
12390            return true;
12391        }
12392
12393        @Override
12394        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12395            return new PackageParser.ServiceIntentInfo[size];
12396        }
12397
12398        @Override
12399        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12400            if (!sUserManager.exists(userId)) return true;
12401            PackageParser.Package p = filter.service.owner;
12402            if (p != null) {
12403                PackageSetting ps = (PackageSetting)p.mExtras;
12404                if (ps != null) {
12405                    // System apps are never considered stopped for purposes of
12406                    // filtering, because there may be no way for the user to
12407                    // actually re-launch them.
12408                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12409                            && ps.getStopped(userId);
12410                }
12411            }
12412            return false;
12413        }
12414
12415        @Override
12416        protected boolean isPackageForFilter(String packageName,
12417                PackageParser.ServiceIntentInfo info) {
12418            return packageName.equals(info.service.owner.packageName);
12419        }
12420
12421        @Override
12422        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12423                int match, int userId) {
12424            if (!sUserManager.exists(userId)) return null;
12425            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12426            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12427                return null;
12428            }
12429            final PackageParser.Service service = info.service;
12430            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12431            if (ps == null) {
12432                return null;
12433            }
12434            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12435                    ps.readUserState(userId), userId);
12436            if (si == null) {
12437                return null;
12438            }
12439            final ResolveInfo res = new ResolveInfo();
12440            res.serviceInfo = si;
12441            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12442                res.filter = filter;
12443            }
12444            res.priority = info.getPriority();
12445            res.preferredOrder = service.owner.mPreferredOrder;
12446            res.match = match;
12447            res.isDefault = info.hasDefault;
12448            res.labelRes = info.labelRes;
12449            res.nonLocalizedLabel = info.nonLocalizedLabel;
12450            res.icon = info.icon;
12451            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12452            return res;
12453        }
12454
12455        @Override
12456        protected void sortResults(List<ResolveInfo> results) {
12457            Collections.sort(results, mResolvePrioritySorter);
12458        }
12459
12460        @Override
12461        protected void dumpFilter(PrintWriter out, String prefix,
12462                PackageParser.ServiceIntentInfo filter) {
12463            out.print(prefix); out.print(
12464                    Integer.toHexString(System.identityHashCode(filter.service)));
12465                    out.print(' ');
12466                    filter.service.printComponentShortName(out);
12467                    out.print(" filter ");
12468                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12469        }
12470
12471        @Override
12472        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12473            return filter.service;
12474        }
12475
12476        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12477            PackageParser.Service service = (PackageParser.Service)label;
12478            out.print(prefix); out.print(
12479                    Integer.toHexString(System.identityHashCode(service)));
12480                    out.print(' ');
12481                    service.printComponentShortName(out);
12482            if (count > 1) {
12483                out.print(" ("); out.print(count); out.print(" filters)");
12484            }
12485            out.println();
12486        }
12487
12488//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12489//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12490//            final List<ResolveInfo> retList = Lists.newArrayList();
12491//            while (i.hasNext()) {
12492//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12493//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12494//                    retList.add(resolveInfo);
12495//                }
12496//            }
12497//            return retList;
12498//        }
12499
12500        // Keys are String (activity class name), values are Activity.
12501        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12502                = new ArrayMap<ComponentName, PackageParser.Service>();
12503        private int mFlags;
12504    }
12505
12506    private final class ProviderIntentResolver
12507            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12508        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12509                boolean defaultOnly, int userId) {
12510            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12511            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12512        }
12513
12514        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12515                int userId) {
12516            if (!sUserManager.exists(userId))
12517                return null;
12518            mFlags = flags;
12519            return super.queryIntent(intent, resolvedType,
12520                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12521                    userId);
12522        }
12523
12524        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12525                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12526            if (!sUserManager.exists(userId))
12527                return null;
12528            if (packageProviders == null) {
12529                return null;
12530            }
12531            mFlags = flags;
12532            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12533            final int N = packageProviders.size();
12534            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12535                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12536
12537            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12538            for (int i = 0; i < N; ++i) {
12539                intentFilters = packageProviders.get(i).intents;
12540                if (intentFilters != null && intentFilters.size() > 0) {
12541                    PackageParser.ProviderIntentInfo[] array =
12542                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12543                    intentFilters.toArray(array);
12544                    listCut.add(array);
12545                }
12546            }
12547            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12548        }
12549
12550        public final void addProvider(PackageParser.Provider p) {
12551            if (mProviders.containsKey(p.getComponentName())) {
12552                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12553                return;
12554            }
12555
12556            mProviders.put(p.getComponentName(), p);
12557            if (DEBUG_SHOW_INFO) {
12558                Log.v(TAG, "  "
12559                        + (p.info.nonLocalizedLabel != null
12560                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12561                Log.v(TAG, "    Class=" + p.info.name);
12562            }
12563            final int NI = p.intents.size();
12564            int j;
12565            for (j = 0; j < NI; j++) {
12566                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12567                if (DEBUG_SHOW_INFO) {
12568                    Log.v(TAG, "    IntentFilter:");
12569                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12570                }
12571                if (!intent.debugCheck()) {
12572                    Log.w(TAG, "==> For Provider " + p.info.name);
12573                }
12574                addFilter(intent);
12575            }
12576        }
12577
12578        public final void removeProvider(PackageParser.Provider p) {
12579            mProviders.remove(p.getComponentName());
12580            if (DEBUG_SHOW_INFO) {
12581                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12582                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12583                Log.v(TAG, "    Class=" + p.info.name);
12584            }
12585            final int NI = p.intents.size();
12586            int j;
12587            for (j = 0; j < NI; j++) {
12588                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12589                if (DEBUG_SHOW_INFO) {
12590                    Log.v(TAG, "    IntentFilter:");
12591                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12592                }
12593                removeFilter(intent);
12594            }
12595        }
12596
12597        @Override
12598        protected boolean allowFilterResult(
12599                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12600            ProviderInfo filterPi = filter.provider.info;
12601            for (int i = dest.size() - 1; i >= 0; i--) {
12602                ProviderInfo destPi = dest.get(i).providerInfo;
12603                if (destPi.name == filterPi.name
12604                        && destPi.packageName == filterPi.packageName) {
12605                    return false;
12606                }
12607            }
12608            return true;
12609        }
12610
12611        @Override
12612        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12613            return new PackageParser.ProviderIntentInfo[size];
12614        }
12615
12616        @Override
12617        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12618            if (!sUserManager.exists(userId))
12619                return true;
12620            PackageParser.Package p = filter.provider.owner;
12621            if (p != null) {
12622                PackageSetting ps = (PackageSetting) p.mExtras;
12623                if (ps != null) {
12624                    // System apps are never considered stopped for purposes of
12625                    // filtering, because there may be no way for the user to
12626                    // actually re-launch them.
12627                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12628                            && ps.getStopped(userId);
12629                }
12630            }
12631            return false;
12632        }
12633
12634        @Override
12635        protected boolean isPackageForFilter(String packageName,
12636                PackageParser.ProviderIntentInfo info) {
12637            return packageName.equals(info.provider.owner.packageName);
12638        }
12639
12640        @Override
12641        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12642                int match, int userId) {
12643            if (!sUserManager.exists(userId))
12644                return null;
12645            final PackageParser.ProviderIntentInfo info = filter;
12646            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12647                return null;
12648            }
12649            final PackageParser.Provider provider = info.provider;
12650            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12651            if (ps == null) {
12652                return null;
12653            }
12654            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12655                    ps.readUserState(userId), userId);
12656            if (pi == null) {
12657                return null;
12658            }
12659            final ResolveInfo res = new ResolveInfo();
12660            res.providerInfo = pi;
12661            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12662                res.filter = filter;
12663            }
12664            res.priority = info.getPriority();
12665            res.preferredOrder = provider.owner.mPreferredOrder;
12666            res.match = match;
12667            res.isDefault = info.hasDefault;
12668            res.labelRes = info.labelRes;
12669            res.nonLocalizedLabel = info.nonLocalizedLabel;
12670            res.icon = info.icon;
12671            res.system = res.providerInfo.applicationInfo.isSystemApp();
12672            return res;
12673        }
12674
12675        @Override
12676        protected void sortResults(List<ResolveInfo> results) {
12677            Collections.sort(results, mResolvePrioritySorter);
12678        }
12679
12680        @Override
12681        protected void dumpFilter(PrintWriter out, String prefix,
12682                PackageParser.ProviderIntentInfo filter) {
12683            out.print(prefix);
12684            out.print(
12685                    Integer.toHexString(System.identityHashCode(filter.provider)));
12686            out.print(' ');
12687            filter.provider.printComponentShortName(out);
12688            out.print(" filter ");
12689            out.println(Integer.toHexString(System.identityHashCode(filter)));
12690        }
12691
12692        @Override
12693        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12694            return filter.provider;
12695        }
12696
12697        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12698            PackageParser.Provider provider = (PackageParser.Provider)label;
12699            out.print(prefix); out.print(
12700                    Integer.toHexString(System.identityHashCode(provider)));
12701                    out.print(' ');
12702                    provider.printComponentShortName(out);
12703            if (count > 1) {
12704                out.print(" ("); out.print(count); out.print(" filters)");
12705            }
12706            out.println();
12707        }
12708
12709        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12710                = new ArrayMap<ComponentName, PackageParser.Provider>();
12711        private int mFlags;
12712    }
12713
12714    static final class EphemeralIntentResolver
12715            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
12716        /**
12717         * The result that has the highest defined order. Ordering applies on a
12718         * per-package basis. Mapping is from package name to Pair of order and
12719         * EphemeralResolveInfo.
12720         * <p>
12721         * NOTE: This is implemented as a field variable for convenience and efficiency.
12722         * By having a field variable, we're able to track filter ordering as soon as
12723         * a non-zero order is defined. Otherwise, multiple loops across the result set
12724         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12725         * this needs to be contained entirely within {@link #filterResults()}.
12726         */
12727        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
12728
12729        @Override
12730        protected EphemeralResponse[] newArray(int size) {
12731            return new EphemeralResponse[size];
12732        }
12733
12734        @Override
12735        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
12736            return true;
12737        }
12738
12739        @Override
12740        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
12741                int userId) {
12742            if (!sUserManager.exists(userId)) {
12743                return null;
12744            }
12745            final String packageName = responseObj.resolveInfo.getPackageName();
12746            final Integer order = responseObj.getOrder();
12747            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
12748                    mOrderResult.get(packageName);
12749            // ordering is enabled and this item's order isn't high enough
12750            if (lastOrderResult != null && lastOrderResult.first >= order) {
12751                return null;
12752            }
12753            final EphemeralResolveInfo res = responseObj.resolveInfo;
12754            if (order > 0) {
12755                // non-zero order, enable ordering
12756                mOrderResult.put(packageName, new Pair<>(order, res));
12757            }
12758            return responseObj;
12759        }
12760
12761        @Override
12762        protected void filterResults(List<EphemeralResponse> results) {
12763            // only do work if ordering is enabled [most of the time it won't be]
12764            if (mOrderResult.size() == 0) {
12765                return;
12766            }
12767            int resultSize = results.size();
12768            for (int i = 0; i < resultSize; i++) {
12769                final EphemeralResolveInfo info = results.get(i).resolveInfo;
12770                final String packageName = info.getPackageName();
12771                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
12772                if (savedInfo == null) {
12773                    // package doesn't having ordering
12774                    continue;
12775                }
12776                if (savedInfo.second == info) {
12777                    // circled back to the highest ordered item; remove from order list
12778                    mOrderResult.remove(savedInfo);
12779                    if (mOrderResult.size() == 0) {
12780                        // no more ordered items
12781                        break;
12782                    }
12783                    continue;
12784                }
12785                // item has a worse order, remove it from the result list
12786                results.remove(i);
12787                resultSize--;
12788                i--;
12789            }
12790        }
12791    }
12792
12793    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12794            new Comparator<ResolveInfo>() {
12795        public int compare(ResolveInfo r1, ResolveInfo r2) {
12796            int v1 = r1.priority;
12797            int v2 = r2.priority;
12798            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12799            if (v1 != v2) {
12800                return (v1 > v2) ? -1 : 1;
12801            }
12802            v1 = r1.preferredOrder;
12803            v2 = r2.preferredOrder;
12804            if (v1 != v2) {
12805                return (v1 > v2) ? -1 : 1;
12806            }
12807            if (r1.isDefault != r2.isDefault) {
12808                return r1.isDefault ? -1 : 1;
12809            }
12810            v1 = r1.match;
12811            v2 = r2.match;
12812            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12813            if (v1 != v2) {
12814                return (v1 > v2) ? -1 : 1;
12815            }
12816            if (r1.system != r2.system) {
12817                return r1.system ? -1 : 1;
12818            }
12819            if (r1.activityInfo != null) {
12820                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12821            }
12822            if (r1.serviceInfo != null) {
12823                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12824            }
12825            if (r1.providerInfo != null) {
12826                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12827            }
12828            return 0;
12829        }
12830    };
12831
12832    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12833            new Comparator<ProviderInfo>() {
12834        public int compare(ProviderInfo p1, ProviderInfo p2) {
12835            final int v1 = p1.initOrder;
12836            final int v2 = p2.initOrder;
12837            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12838        }
12839    };
12840
12841    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12842            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12843            final int[] userIds) {
12844        mHandler.post(new Runnable() {
12845            @Override
12846            public void run() {
12847                try {
12848                    final IActivityManager am = ActivityManager.getService();
12849                    if (am == null) return;
12850                    final int[] resolvedUserIds;
12851                    if (userIds == null) {
12852                        resolvedUserIds = am.getRunningUserIds();
12853                    } else {
12854                        resolvedUserIds = userIds;
12855                    }
12856                    for (int id : resolvedUserIds) {
12857                        final Intent intent = new Intent(action,
12858                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12859                        if (extras != null) {
12860                            intent.putExtras(extras);
12861                        }
12862                        if (targetPkg != null) {
12863                            intent.setPackage(targetPkg);
12864                        }
12865                        // Modify the UID when posting to other users
12866                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12867                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12868                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12869                            intent.putExtra(Intent.EXTRA_UID, uid);
12870                        }
12871                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12872                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12873                        if (DEBUG_BROADCASTS) {
12874                            RuntimeException here = new RuntimeException("here");
12875                            here.fillInStackTrace();
12876                            Slog.d(TAG, "Sending to user " + id + ": "
12877                                    + intent.toShortString(false, true, false, false)
12878                                    + " " + intent.getExtras(), here);
12879                        }
12880                        am.broadcastIntent(null, intent, null, finishedReceiver,
12881                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12882                                null, finishedReceiver != null, false, id);
12883                    }
12884                } catch (RemoteException ex) {
12885                }
12886            }
12887        });
12888    }
12889
12890    /**
12891     * Check if the external storage media is available. This is true if there
12892     * is a mounted external storage medium or if the external storage is
12893     * emulated.
12894     */
12895    private boolean isExternalMediaAvailable() {
12896        return mMediaMounted || Environment.isExternalStorageEmulated();
12897    }
12898
12899    @Override
12900    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12901        // writer
12902        synchronized (mPackages) {
12903            if (!isExternalMediaAvailable()) {
12904                // If the external storage is no longer mounted at this point,
12905                // the caller may not have been able to delete all of this
12906                // packages files and can not delete any more.  Bail.
12907                return null;
12908            }
12909            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12910            if (lastPackage != null) {
12911                pkgs.remove(lastPackage);
12912            }
12913            if (pkgs.size() > 0) {
12914                return pkgs.get(0);
12915            }
12916        }
12917        return null;
12918    }
12919
12920    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12921        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12922                userId, andCode ? 1 : 0, packageName);
12923        if (mSystemReady) {
12924            msg.sendToTarget();
12925        } else {
12926            if (mPostSystemReadyMessages == null) {
12927                mPostSystemReadyMessages = new ArrayList<>();
12928            }
12929            mPostSystemReadyMessages.add(msg);
12930        }
12931    }
12932
12933    void startCleaningPackages() {
12934        // reader
12935        if (!isExternalMediaAvailable()) {
12936            return;
12937        }
12938        synchronized (mPackages) {
12939            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12940                return;
12941            }
12942        }
12943        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12944        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12945        IActivityManager am = ActivityManager.getService();
12946        if (am != null) {
12947            try {
12948                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12949                        UserHandle.USER_SYSTEM);
12950            } catch (RemoteException e) {
12951            }
12952        }
12953    }
12954
12955    @Override
12956    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12957            int installFlags, String installerPackageName, int userId) {
12958        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12959
12960        final int callingUid = Binder.getCallingUid();
12961        enforceCrossUserPermission(callingUid, userId,
12962                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12963
12964        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12965            try {
12966                if (observer != null) {
12967                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12968                }
12969            } catch (RemoteException re) {
12970            }
12971            return;
12972        }
12973
12974        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12975            installFlags |= PackageManager.INSTALL_FROM_ADB;
12976
12977        } else {
12978            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12979            // about installerPackageName.
12980
12981            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12982            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12983        }
12984
12985        UserHandle user;
12986        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12987            user = UserHandle.ALL;
12988        } else {
12989            user = new UserHandle(userId);
12990        }
12991
12992        // Only system components can circumvent runtime permissions when installing.
12993        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12994                && mContext.checkCallingOrSelfPermission(Manifest.permission
12995                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12996            throw new SecurityException("You need the "
12997                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12998                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12999        }
13000
13001        final File originFile = new File(originPath);
13002        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13003
13004        final Message msg = mHandler.obtainMessage(INIT_COPY);
13005        final VerificationInfo verificationInfo = new VerificationInfo(
13006                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13007        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13008                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13009                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13010                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13011        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13012        msg.obj = params;
13013
13014        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13015                System.identityHashCode(msg.obj));
13016        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13017                System.identityHashCode(msg.obj));
13018
13019        mHandler.sendMessage(msg);
13020    }
13021
13022
13023    /**
13024     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13025     * it is acting on behalf on an enterprise or the user).
13026     *
13027     * Note that the ordering of the conditionals in this method is important. The checks we perform
13028     * are as follows, in this order:
13029     *
13030     * 1) If the install is being performed by a system app, we can trust the app to have set the
13031     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13032     *    what it is.
13033     * 2) If the install is being performed by a device or profile owner app, the install reason
13034     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13035     *    set the install reason correctly. If the app targets an older SDK version where install
13036     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13037     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13038     * 3) In all other cases, the install is being performed by a regular app that is neither part
13039     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13040     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13041     *    set to enterprise policy and if so, change it to unknown instead.
13042     */
13043    private int fixUpInstallReason(String installerPackageName, int installerUid,
13044            int installReason) {
13045        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13046                == PERMISSION_GRANTED) {
13047            // If the install is being performed by a system app, we trust that app to have set the
13048            // install reason correctly.
13049            return installReason;
13050        }
13051
13052        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13053            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13054        if (dpm != null) {
13055            ComponentName owner = null;
13056            try {
13057                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13058                if (owner == null) {
13059                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13060                }
13061            } catch (RemoteException e) {
13062            }
13063            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13064                // If the install is being performed by a device or profile owner, the install
13065                // reason should be enterprise policy.
13066                return PackageManager.INSTALL_REASON_POLICY;
13067            }
13068        }
13069
13070        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13071            // If the install is being performed by a regular app (i.e. neither system app nor
13072            // device or profile owner), we have no reason to believe that the app is acting on
13073            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13074            // change it to unknown instead.
13075            return PackageManager.INSTALL_REASON_UNKNOWN;
13076        }
13077
13078        // If the install is being performed by a regular app and the install reason was set to any
13079        // value but enterprise policy, leave the install reason unchanged.
13080        return installReason;
13081    }
13082
13083    void installStage(String packageName, File stagedDir, String stagedCid,
13084            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13085            String installerPackageName, int installerUid, UserHandle user,
13086            Certificate[][] certificates) {
13087        if (DEBUG_EPHEMERAL) {
13088            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13089                Slog.d(TAG, "Ephemeral install of " + packageName);
13090            }
13091        }
13092        final VerificationInfo verificationInfo = new VerificationInfo(
13093                sessionParams.originatingUri, sessionParams.referrerUri,
13094                sessionParams.originatingUid, installerUid);
13095
13096        final OriginInfo origin;
13097        if (stagedDir != null) {
13098            origin = OriginInfo.fromStagedFile(stagedDir);
13099        } else {
13100            origin = OriginInfo.fromStagedContainer(stagedCid);
13101        }
13102
13103        final Message msg = mHandler.obtainMessage(INIT_COPY);
13104        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13105                sessionParams.installReason);
13106        final InstallParams params = new InstallParams(origin, null, observer,
13107                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13108                verificationInfo, user, sessionParams.abiOverride,
13109                sessionParams.grantedRuntimePermissions, certificates, installReason);
13110        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13111        msg.obj = params;
13112
13113        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13114                System.identityHashCode(msg.obj));
13115        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13116                System.identityHashCode(msg.obj));
13117
13118        mHandler.sendMessage(msg);
13119    }
13120
13121    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13122            int userId) {
13123        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13124        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13125    }
13126
13127    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13128            int appId, int... userIds) {
13129        if (ArrayUtils.isEmpty(userIds)) {
13130            return;
13131        }
13132        Bundle extras = new Bundle(1);
13133        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13134        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13135
13136        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13137                packageName, extras, 0, null, null, userIds);
13138        if (isSystem) {
13139            mHandler.post(() -> {
13140                        for (int userId : userIds) {
13141                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13142                        }
13143                    }
13144            );
13145        }
13146    }
13147
13148    /**
13149     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13150     * automatically without needing an explicit launch.
13151     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13152     */
13153    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13154        // If user is not running, the app didn't miss any broadcast
13155        if (!mUserManagerInternal.isUserRunning(userId)) {
13156            return;
13157        }
13158        final IActivityManager am = ActivityManager.getService();
13159        try {
13160            // Deliver LOCKED_BOOT_COMPLETED first
13161            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13162                    .setPackage(packageName);
13163            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13164            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13165                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13166
13167            // Deliver BOOT_COMPLETED only if user is unlocked
13168            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13169                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13170                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13171                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13172            }
13173        } catch (RemoteException e) {
13174            throw e.rethrowFromSystemServer();
13175        }
13176    }
13177
13178    @Override
13179    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13180            int userId) {
13181        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13182        PackageSetting pkgSetting;
13183        final int uid = Binder.getCallingUid();
13184        enforceCrossUserPermission(uid, userId,
13185                true /* requireFullPermission */, true /* checkShell */,
13186                "setApplicationHiddenSetting for user " + userId);
13187
13188        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13189            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13190            return false;
13191        }
13192
13193        long callingId = Binder.clearCallingIdentity();
13194        try {
13195            boolean sendAdded = false;
13196            boolean sendRemoved = false;
13197            // writer
13198            synchronized (mPackages) {
13199                pkgSetting = mSettings.mPackages.get(packageName);
13200                if (pkgSetting == null) {
13201                    return false;
13202                }
13203                // Do not allow "android" is being disabled
13204                if ("android".equals(packageName)) {
13205                    Slog.w(TAG, "Cannot hide package: android");
13206                    return false;
13207                }
13208                // Cannot hide static shared libs as they are considered
13209                // a part of the using app (emulating static linking). Also
13210                // static libs are installed always on internal storage.
13211                PackageParser.Package pkg = mPackages.get(packageName);
13212                if (pkg != null && pkg.staticSharedLibName != null) {
13213                    Slog.w(TAG, "Cannot hide package: " + packageName
13214                            + " providing static shared library: "
13215                            + pkg.staticSharedLibName);
13216                    return false;
13217                }
13218                // Only allow protected packages to hide themselves.
13219                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13220                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13221                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13222                    return false;
13223                }
13224
13225                if (pkgSetting.getHidden(userId) != hidden) {
13226                    pkgSetting.setHidden(hidden, userId);
13227                    mSettings.writePackageRestrictionsLPr(userId);
13228                    if (hidden) {
13229                        sendRemoved = true;
13230                    } else {
13231                        sendAdded = true;
13232                    }
13233                }
13234            }
13235            if (sendAdded) {
13236                sendPackageAddedForUser(packageName, pkgSetting, userId);
13237                return true;
13238            }
13239            if (sendRemoved) {
13240                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13241                        "hiding pkg");
13242                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13243                return true;
13244            }
13245        } finally {
13246            Binder.restoreCallingIdentity(callingId);
13247        }
13248        return false;
13249    }
13250
13251    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13252            int userId) {
13253        final PackageRemovedInfo info = new PackageRemovedInfo();
13254        info.removedPackage = packageName;
13255        info.removedUsers = new int[] {userId};
13256        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13257        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13258    }
13259
13260    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13261        if (pkgList.length > 0) {
13262            Bundle extras = new Bundle(1);
13263            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13264
13265            sendPackageBroadcast(
13266                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13267                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13268                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13269                    new int[] {userId});
13270        }
13271    }
13272
13273    /**
13274     * Returns true if application is not found or there was an error. Otherwise it returns
13275     * the hidden state of the package for the given user.
13276     */
13277    @Override
13278    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13279        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13280        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13281                true /* requireFullPermission */, false /* checkShell */,
13282                "getApplicationHidden for user " + userId);
13283        PackageSetting pkgSetting;
13284        long callingId = Binder.clearCallingIdentity();
13285        try {
13286            // writer
13287            synchronized (mPackages) {
13288                pkgSetting = mSettings.mPackages.get(packageName);
13289                if (pkgSetting == null) {
13290                    return true;
13291                }
13292                return pkgSetting.getHidden(userId);
13293            }
13294        } finally {
13295            Binder.restoreCallingIdentity(callingId);
13296        }
13297    }
13298
13299    /**
13300     * @hide
13301     */
13302    @Override
13303    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13304            int installReason) {
13305        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13306                null);
13307        PackageSetting pkgSetting;
13308        final int uid = Binder.getCallingUid();
13309        enforceCrossUserPermission(uid, userId,
13310                true /* requireFullPermission */, true /* checkShell */,
13311                "installExistingPackage for user " + userId);
13312        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13313            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13314        }
13315
13316        long callingId = Binder.clearCallingIdentity();
13317        try {
13318            boolean installed = false;
13319            final boolean instantApp =
13320                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13321            final boolean fullApp =
13322                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13323
13324            // writer
13325            synchronized (mPackages) {
13326                pkgSetting = mSettings.mPackages.get(packageName);
13327                if (pkgSetting == null) {
13328                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13329                }
13330                if (!pkgSetting.getInstalled(userId)) {
13331                    pkgSetting.setInstalled(true, userId);
13332                    pkgSetting.setHidden(false, userId);
13333                    pkgSetting.setInstallReason(installReason, userId);
13334                    mSettings.writePackageRestrictionsLPr(userId);
13335                    mSettings.writeKernelMappingLPr(pkgSetting);
13336                    installed = true;
13337                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13338                    // upgrade app from instant to full; we don't allow app downgrade
13339                    installed = true;
13340                }
13341                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13342            }
13343
13344            if (installed) {
13345                if (pkgSetting.pkg != null) {
13346                    synchronized (mInstallLock) {
13347                        // We don't need to freeze for a brand new install
13348                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13349                    }
13350                }
13351                sendPackageAddedForUser(packageName, pkgSetting, userId);
13352                synchronized (mPackages) {
13353                    updateSequenceNumberLP(packageName, new int[]{ userId });
13354                }
13355            }
13356        } finally {
13357            Binder.restoreCallingIdentity(callingId);
13358        }
13359
13360        return PackageManager.INSTALL_SUCCEEDED;
13361    }
13362
13363    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13364            boolean instantApp, boolean fullApp) {
13365        // no state specified; do nothing
13366        if (!instantApp && !fullApp) {
13367            return;
13368        }
13369        if (userId != UserHandle.USER_ALL) {
13370            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13371                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13372            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13373                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13374            }
13375        } else {
13376            for (int currentUserId : sUserManager.getUserIds()) {
13377                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13378                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13379                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13380                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13381                }
13382            }
13383        }
13384    }
13385
13386    boolean isUserRestricted(int userId, String restrictionKey) {
13387        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13388        if (restrictions.getBoolean(restrictionKey, false)) {
13389            Log.w(TAG, "User is restricted: " + restrictionKey);
13390            return true;
13391        }
13392        return false;
13393    }
13394
13395    @Override
13396    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13397            int userId) {
13398        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13399        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13400                true /* requireFullPermission */, true /* checkShell */,
13401                "setPackagesSuspended for user " + userId);
13402
13403        if (ArrayUtils.isEmpty(packageNames)) {
13404            return packageNames;
13405        }
13406
13407        // List of package names for whom the suspended state has changed.
13408        List<String> changedPackages = new ArrayList<>(packageNames.length);
13409        // List of package names for whom the suspended state is not set as requested in this
13410        // method.
13411        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13412        long callingId = Binder.clearCallingIdentity();
13413        try {
13414            for (int i = 0; i < packageNames.length; i++) {
13415                String packageName = packageNames[i];
13416                boolean changed = false;
13417                final int appId;
13418                synchronized (mPackages) {
13419                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13420                    if (pkgSetting == null) {
13421                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13422                                + "\". Skipping suspending/un-suspending.");
13423                        unactionedPackages.add(packageName);
13424                        continue;
13425                    }
13426                    appId = pkgSetting.appId;
13427                    if (pkgSetting.getSuspended(userId) != suspended) {
13428                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13429                            unactionedPackages.add(packageName);
13430                            continue;
13431                        }
13432                        pkgSetting.setSuspended(suspended, userId);
13433                        mSettings.writePackageRestrictionsLPr(userId);
13434                        changed = true;
13435                        changedPackages.add(packageName);
13436                    }
13437                }
13438
13439                if (changed && suspended) {
13440                    killApplication(packageName, UserHandle.getUid(userId, appId),
13441                            "suspending package");
13442                }
13443            }
13444        } finally {
13445            Binder.restoreCallingIdentity(callingId);
13446        }
13447
13448        if (!changedPackages.isEmpty()) {
13449            sendPackagesSuspendedForUser(changedPackages.toArray(
13450                    new String[changedPackages.size()]), userId, suspended);
13451        }
13452
13453        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13454    }
13455
13456    @Override
13457    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13458        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13459                true /* requireFullPermission */, false /* checkShell */,
13460                "isPackageSuspendedForUser for user " + userId);
13461        synchronized (mPackages) {
13462            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13463            if (pkgSetting == null) {
13464                throw new IllegalArgumentException("Unknown target package: " + packageName);
13465            }
13466            return pkgSetting.getSuspended(userId);
13467        }
13468    }
13469
13470    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13471        if (isPackageDeviceAdmin(packageName, userId)) {
13472            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13473                    + "\": has an active device admin");
13474            return false;
13475        }
13476
13477        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13478        if (packageName.equals(activeLauncherPackageName)) {
13479            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13480                    + "\": contains the active launcher");
13481            return false;
13482        }
13483
13484        if (packageName.equals(mRequiredInstallerPackage)) {
13485            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13486                    + "\": required for package installation");
13487            return false;
13488        }
13489
13490        if (packageName.equals(mRequiredUninstallerPackage)) {
13491            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13492                    + "\": required for package uninstallation");
13493            return false;
13494        }
13495
13496        if (packageName.equals(mRequiredVerifierPackage)) {
13497            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13498                    + "\": required for package verification");
13499            return false;
13500        }
13501
13502        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13503            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13504                    + "\": is the default dialer");
13505            return false;
13506        }
13507
13508        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13509            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13510                    + "\": protected package");
13511            return false;
13512        }
13513
13514        // Cannot suspend static shared libs as they are considered
13515        // a part of the using app (emulating static linking). Also
13516        // static libs are installed always on internal storage.
13517        PackageParser.Package pkg = mPackages.get(packageName);
13518        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13519            Slog.w(TAG, "Cannot suspend package: " + packageName
13520                    + " providing static shared library: "
13521                    + pkg.staticSharedLibName);
13522            return false;
13523        }
13524
13525        return true;
13526    }
13527
13528    private String getActiveLauncherPackageName(int userId) {
13529        Intent intent = new Intent(Intent.ACTION_MAIN);
13530        intent.addCategory(Intent.CATEGORY_HOME);
13531        ResolveInfo resolveInfo = resolveIntent(
13532                intent,
13533                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13534                PackageManager.MATCH_DEFAULT_ONLY,
13535                userId);
13536
13537        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13538    }
13539
13540    private String getDefaultDialerPackageName(int userId) {
13541        synchronized (mPackages) {
13542            return mSettings.getDefaultDialerPackageNameLPw(userId);
13543        }
13544    }
13545
13546    @Override
13547    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13548        mContext.enforceCallingOrSelfPermission(
13549                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13550                "Only package verification agents can verify applications");
13551
13552        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13553        final PackageVerificationResponse response = new PackageVerificationResponse(
13554                verificationCode, Binder.getCallingUid());
13555        msg.arg1 = id;
13556        msg.obj = response;
13557        mHandler.sendMessage(msg);
13558    }
13559
13560    @Override
13561    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13562            long millisecondsToDelay) {
13563        mContext.enforceCallingOrSelfPermission(
13564                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13565                "Only package verification agents can extend verification timeouts");
13566
13567        final PackageVerificationState state = mPendingVerification.get(id);
13568        final PackageVerificationResponse response = new PackageVerificationResponse(
13569                verificationCodeAtTimeout, Binder.getCallingUid());
13570
13571        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13572            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13573        }
13574        if (millisecondsToDelay < 0) {
13575            millisecondsToDelay = 0;
13576        }
13577        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13578                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13579            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13580        }
13581
13582        if ((state != null) && !state.timeoutExtended()) {
13583            state.extendTimeout();
13584
13585            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13586            msg.arg1 = id;
13587            msg.obj = response;
13588            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13589        }
13590    }
13591
13592    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13593            int verificationCode, UserHandle user) {
13594        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13595        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13596        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13597        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13598        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13599
13600        mContext.sendBroadcastAsUser(intent, user,
13601                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13602    }
13603
13604    private ComponentName matchComponentForVerifier(String packageName,
13605            List<ResolveInfo> receivers) {
13606        ActivityInfo targetReceiver = null;
13607
13608        final int NR = receivers.size();
13609        for (int i = 0; i < NR; i++) {
13610            final ResolveInfo info = receivers.get(i);
13611            if (info.activityInfo == null) {
13612                continue;
13613            }
13614
13615            if (packageName.equals(info.activityInfo.packageName)) {
13616                targetReceiver = info.activityInfo;
13617                break;
13618            }
13619        }
13620
13621        if (targetReceiver == null) {
13622            return null;
13623        }
13624
13625        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13626    }
13627
13628    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13629            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13630        if (pkgInfo.verifiers.length == 0) {
13631            return null;
13632        }
13633
13634        final int N = pkgInfo.verifiers.length;
13635        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13636        for (int i = 0; i < N; i++) {
13637            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13638
13639            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13640                    receivers);
13641            if (comp == null) {
13642                continue;
13643            }
13644
13645            final int verifierUid = getUidForVerifier(verifierInfo);
13646            if (verifierUid == -1) {
13647                continue;
13648            }
13649
13650            if (DEBUG_VERIFY) {
13651                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13652                        + " with the correct signature");
13653            }
13654            sufficientVerifiers.add(comp);
13655            verificationState.addSufficientVerifier(verifierUid);
13656        }
13657
13658        return sufficientVerifiers;
13659    }
13660
13661    private int getUidForVerifier(VerifierInfo verifierInfo) {
13662        synchronized (mPackages) {
13663            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13664            if (pkg == null) {
13665                return -1;
13666            } else if (pkg.mSignatures.length != 1) {
13667                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13668                        + " has more than one signature; ignoring");
13669                return -1;
13670            }
13671
13672            /*
13673             * If the public key of the package's signature does not match
13674             * our expected public key, then this is a different package and
13675             * we should skip.
13676             */
13677
13678            final byte[] expectedPublicKey;
13679            try {
13680                final Signature verifierSig = pkg.mSignatures[0];
13681                final PublicKey publicKey = verifierSig.getPublicKey();
13682                expectedPublicKey = publicKey.getEncoded();
13683            } catch (CertificateException e) {
13684                return -1;
13685            }
13686
13687            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13688
13689            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13690                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13691                        + " does not have the expected public key; ignoring");
13692                return -1;
13693            }
13694
13695            return pkg.applicationInfo.uid;
13696        }
13697    }
13698
13699    @Override
13700    public void finishPackageInstall(int token, boolean didLaunch) {
13701        enforceSystemOrRoot("Only the system is allowed to finish installs");
13702
13703        if (DEBUG_INSTALL) {
13704            Slog.v(TAG, "BM finishing package install for " + token);
13705        }
13706        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13707
13708        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13709        mHandler.sendMessage(msg);
13710    }
13711
13712    /**
13713     * Get the verification agent timeout.
13714     *
13715     * @return verification timeout in milliseconds
13716     */
13717    private long getVerificationTimeout() {
13718        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13719                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13720                DEFAULT_VERIFICATION_TIMEOUT);
13721    }
13722
13723    /**
13724     * Get the default verification agent response code.
13725     *
13726     * @return default verification response code
13727     */
13728    private int getDefaultVerificationResponse() {
13729        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13730                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13731                DEFAULT_VERIFICATION_RESPONSE);
13732    }
13733
13734    /**
13735     * Check whether or not package verification has been enabled.
13736     *
13737     * @return true if verification should be performed
13738     */
13739    private boolean isVerificationEnabled(int userId, int installFlags) {
13740        if (!DEFAULT_VERIFY_ENABLE) {
13741            return false;
13742        }
13743        // Ephemeral apps don't get the full verification treatment
13744        if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13745            if (DEBUG_EPHEMERAL) {
13746                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
13747            }
13748            return false;
13749        }
13750
13751        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13752
13753        // Check if installing from ADB
13754        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13755            // Do not run verification in a test harness environment
13756            if (ActivityManager.isRunningInTestHarness()) {
13757                return false;
13758            }
13759            if (ensureVerifyAppsEnabled) {
13760                return true;
13761            }
13762            // Check if the developer does not want package verification for ADB installs
13763            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13764                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13765                return false;
13766            }
13767        }
13768
13769        if (ensureVerifyAppsEnabled) {
13770            return true;
13771        }
13772
13773        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13774                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13775    }
13776
13777    @Override
13778    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13779            throws RemoteException {
13780        mContext.enforceCallingOrSelfPermission(
13781                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13782                "Only intentfilter verification agents can verify applications");
13783
13784        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13785        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13786                Binder.getCallingUid(), verificationCode, failedDomains);
13787        msg.arg1 = id;
13788        msg.obj = response;
13789        mHandler.sendMessage(msg);
13790    }
13791
13792    @Override
13793    public int getIntentVerificationStatus(String packageName, int userId) {
13794        synchronized (mPackages) {
13795            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13796        }
13797    }
13798
13799    @Override
13800    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13801        mContext.enforceCallingOrSelfPermission(
13802                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13803
13804        boolean result = false;
13805        synchronized (mPackages) {
13806            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13807        }
13808        if (result) {
13809            scheduleWritePackageRestrictionsLocked(userId);
13810        }
13811        return result;
13812    }
13813
13814    @Override
13815    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13816            String packageName) {
13817        synchronized (mPackages) {
13818            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13819        }
13820    }
13821
13822    @Override
13823    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13824        if (TextUtils.isEmpty(packageName)) {
13825            return ParceledListSlice.emptyList();
13826        }
13827        synchronized (mPackages) {
13828            PackageParser.Package pkg = mPackages.get(packageName);
13829            if (pkg == null || pkg.activities == null) {
13830                return ParceledListSlice.emptyList();
13831            }
13832            final int count = pkg.activities.size();
13833            ArrayList<IntentFilter> result = new ArrayList<>();
13834            for (int n=0; n<count; n++) {
13835                PackageParser.Activity activity = pkg.activities.get(n);
13836                if (activity.intents != null && activity.intents.size() > 0) {
13837                    result.addAll(activity.intents);
13838                }
13839            }
13840            return new ParceledListSlice<>(result);
13841        }
13842    }
13843
13844    @Override
13845    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13846        mContext.enforceCallingOrSelfPermission(
13847                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13848
13849        synchronized (mPackages) {
13850            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13851            if (packageName != null) {
13852                result |= updateIntentVerificationStatus(packageName,
13853                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13854                        userId);
13855                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13856                        packageName, userId);
13857            }
13858            return result;
13859        }
13860    }
13861
13862    @Override
13863    public String getDefaultBrowserPackageName(int userId) {
13864        synchronized (mPackages) {
13865            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13866        }
13867    }
13868
13869    /**
13870     * Get the "allow unknown sources" setting.
13871     *
13872     * @return the current "allow unknown sources" setting
13873     */
13874    private int getUnknownSourcesSettings() {
13875        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13876                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13877                -1);
13878    }
13879
13880    @Override
13881    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13882        final int uid = Binder.getCallingUid();
13883        // writer
13884        synchronized (mPackages) {
13885            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13886            if (targetPackageSetting == null) {
13887                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13888            }
13889
13890            PackageSetting installerPackageSetting;
13891            if (installerPackageName != null) {
13892                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13893                if (installerPackageSetting == null) {
13894                    throw new IllegalArgumentException("Unknown installer package: "
13895                            + installerPackageName);
13896                }
13897            } else {
13898                installerPackageSetting = null;
13899            }
13900
13901            Signature[] callerSignature;
13902            Object obj = mSettings.getUserIdLPr(uid);
13903            if (obj != null) {
13904                if (obj instanceof SharedUserSetting) {
13905                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13906                } else if (obj instanceof PackageSetting) {
13907                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13908                } else {
13909                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13910                }
13911            } else {
13912                throw new SecurityException("Unknown calling UID: " + uid);
13913            }
13914
13915            // Verify: can't set installerPackageName to a package that is
13916            // not signed with the same cert as the caller.
13917            if (installerPackageSetting != null) {
13918                if (compareSignatures(callerSignature,
13919                        installerPackageSetting.signatures.mSignatures)
13920                        != PackageManager.SIGNATURE_MATCH) {
13921                    throw new SecurityException(
13922                            "Caller does not have same cert as new installer package "
13923                            + installerPackageName);
13924                }
13925            }
13926
13927            // Verify: if target already has an installer package, it must
13928            // be signed with the same cert as the caller.
13929            if (targetPackageSetting.installerPackageName != null) {
13930                PackageSetting setting = mSettings.mPackages.get(
13931                        targetPackageSetting.installerPackageName);
13932                // If the currently set package isn't valid, then it's always
13933                // okay to change it.
13934                if (setting != null) {
13935                    if (compareSignatures(callerSignature,
13936                            setting.signatures.mSignatures)
13937                            != PackageManager.SIGNATURE_MATCH) {
13938                        throw new SecurityException(
13939                                "Caller does not have same cert as old installer package "
13940                                + targetPackageSetting.installerPackageName);
13941                    }
13942                }
13943            }
13944
13945            // Okay!
13946            targetPackageSetting.installerPackageName = installerPackageName;
13947            if (installerPackageName != null) {
13948                mSettings.mInstallerPackages.add(installerPackageName);
13949            }
13950            scheduleWriteSettingsLocked();
13951        }
13952    }
13953
13954    @Override
13955    public void setApplicationCategoryHint(String packageName, int categoryHint,
13956            String callerPackageName) {
13957        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13958                callerPackageName);
13959        synchronized (mPackages) {
13960            PackageSetting ps = mSettings.mPackages.get(packageName);
13961            if (ps == null) {
13962                throw new IllegalArgumentException("Unknown target package " + packageName);
13963            }
13964
13965            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13966                throw new IllegalArgumentException("Calling package " + callerPackageName
13967                        + " is not installer for " + packageName);
13968            }
13969
13970            if (ps.categoryHint != categoryHint) {
13971                ps.categoryHint = categoryHint;
13972                scheduleWriteSettingsLocked();
13973            }
13974        }
13975    }
13976
13977    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13978        // Queue up an async operation since the package installation may take a little while.
13979        mHandler.post(new Runnable() {
13980            public void run() {
13981                mHandler.removeCallbacks(this);
13982                 // Result object to be returned
13983                PackageInstalledInfo res = new PackageInstalledInfo();
13984                res.setReturnCode(currentStatus);
13985                res.uid = -1;
13986                res.pkg = null;
13987                res.removedInfo = null;
13988                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13989                    args.doPreInstall(res.returnCode);
13990                    synchronized (mInstallLock) {
13991                        installPackageTracedLI(args, res);
13992                    }
13993                    args.doPostInstall(res.returnCode, res.uid);
13994                }
13995
13996                // A restore should be performed at this point if (a) the install
13997                // succeeded, (b) the operation is not an update, and (c) the new
13998                // package has not opted out of backup participation.
13999                final boolean update = res.removedInfo != null
14000                        && res.removedInfo.removedPackage != null;
14001                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14002                boolean doRestore = !update
14003                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14004
14005                // Set up the post-install work request bookkeeping.  This will be used
14006                // and cleaned up by the post-install event handling regardless of whether
14007                // there's a restore pass performed.  Token values are >= 1.
14008                int token;
14009                if (mNextInstallToken < 0) mNextInstallToken = 1;
14010                token = mNextInstallToken++;
14011
14012                PostInstallData data = new PostInstallData(args, res);
14013                mRunningInstalls.put(token, data);
14014                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14015
14016                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14017                    // Pass responsibility to the Backup Manager.  It will perform a
14018                    // restore if appropriate, then pass responsibility back to the
14019                    // Package Manager to run the post-install observer callbacks
14020                    // and broadcasts.
14021                    IBackupManager bm = IBackupManager.Stub.asInterface(
14022                            ServiceManager.getService(Context.BACKUP_SERVICE));
14023                    if (bm != null) {
14024                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14025                                + " to BM for possible restore");
14026                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14027                        try {
14028                            // TODO: http://b/22388012
14029                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14030                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14031                            } else {
14032                                doRestore = false;
14033                            }
14034                        } catch (RemoteException e) {
14035                            // can't happen; the backup manager is local
14036                        } catch (Exception e) {
14037                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14038                            doRestore = false;
14039                        }
14040                    } else {
14041                        Slog.e(TAG, "Backup Manager not found!");
14042                        doRestore = false;
14043                    }
14044                }
14045
14046                if (!doRestore) {
14047                    // No restore possible, or the Backup Manager was mysteriously not
14048                    // available -- just fire the post-install work request directly.
14049                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14050
14051                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14052
14053                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14054                    mHandler.sendMessage(msg);
14055                }
14056            }
14057        });
14058    }
14059
14060    /**
14061     * Callback from PackageSettings whenever an app is first transitioned out of the
14062     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14063     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14064     * here whether the app is the target of an ongoing install, and only send the
14065     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14066     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14067     * handling.
14068     */
14069    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14070        // Serialize this with the rest of the install-process message chain.  In the
14071        // restore-at-install case, this Runnable will necessarily run before the
14072        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14073        // are coherent.  In the non-restore case, the app has already completed install
14074        // and been launched through some other means, so it is not in a problematic
14075        // state for observers to see the FIRST_LAUNCH signal.
14076        mHandler.post(new Runnable() {
14077            @Override
14078            public void run() {
14079                for (int i = 0; i < mRunningInstalls.size(); i++) {
14080                    final PostInstallData data = mRunningInstalls.valueAt(i);
14081                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14082                        continue;
14083                    }
14084                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14085                        // right package; but is it for the right user?
14086                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14087                            if (userId == data.res.newUsers[uIndex]) {
14088                                if (DEBUG_BACKUP) {
14089                                    Slog.i(TAG, "Package " + pkgName
14090                                            + " being restored so deferring FIRST_LAUNCH");
14091                                }
14092                                return;
14093                            }
14094                        }
14095                    }
14096                }
14097                // didn't find it, so not being restored
14098                if (DEBUG_BACKUP) {
14099                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14100                }
14101                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14102            }
14103        });
14104    }
14105
14106    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14107        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14108                installerPkg, null, userIds);
14109    }
14110
14111    private abstract class HandlerParams {
14112        private static final int MAX_RETRIES = 4;
14113
14114        /**
14115         * Number of times startCopy() has been attempted and had a non-fatal
14116         * error.
14117         */
14118        private int mRetries = 0;
14119
14120        /** User handle for the user requesting the information or installation. */
14121        private final UserHandle mUser;
14122        String traceMethod;
14123        int traceCookie;
14124
14125        HandlerParams(UserHandle user) {
14126            mUser = user;
14127        }
14128
14129        UserHandle getUser() {
14130            return mUser;
14131        }
14132
14133        HandlerParams setTraceMethod(String traceMethod) {
14134            this.traceMethod = traceMethod;
14135            return this;
14136        }
14137
14138        HandlerParams setTraceCookie(int traceCookie) {
14139            this.traceCookie = traceCookie;
14140            return this;
14141        }
14142
14143        final boolean startCopy() {
14144            boolean res;
14145            try {
14146                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14147
14148                if (++mRetries > MAX_RETRIES) {
14149                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14150                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14151                    handleServiceError();
14152                    return false;
14153                } else {
14154                    handleStartCopy();
14155                    res = true;
14156                }
14157            } catch (RemoteException e) {
14158                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14159                mHandler.sendEmptyMessage(MCS_RECONNECT);
14160                res = false;
14161            }
14162            handleReturnCode();
14163            return res;
14164        }
14165
14166        final void serviceError() {
14167            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14168            handleServiceError();
14169            handleReturnCode();
14170        }
14171
14172        abstract void handleStartCopy() throws RemoteException;
14173        abstract void handleServiceError();
14174        abstract void handleReturnCode();
14175    }
14176
14177    class MeasureParams extends HandlerParams {
14178        private final PackageStats mStats;
14179        private boolean mSuccess;
14180
14181        private final IPackageStatsObserver mObserver;
14182
14183        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
14184            super(new UserHandle(stats.userHandle));
14185            mObserver = observer;
14186            mStats = stats;
14187        }
14188
14189        @Override
14190        public String toString() {
14191            return "MeasureParams{"
14192                + Integer.toHexString(System.identityHashCode(this))
14193                + " " + mStats.packageName + "}";
14194        }
14195
14196        @Override
14197        void handleStartCopy() throws RemoteException {
14198            synchronized (mInstallLock) {
14199                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
14200            }
14201
14202            if (mSuccess) {
14203                boolean mounted = false;
14204                try {
14205                    final String status = Environment.getExternalStorageState();
14206                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
14207                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
14208                } catch (Exception e) {
14209                }
14210
14211                if (mounted) {
14212                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
14213
14214                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
14215                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
14216
14217                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
14218                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
14219
14220                    // Always subtract cache size, since it's a subdirectory
14221                    mStats.externalDataSize -= mStats.externalCacheSize;
14222
14223                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
14224                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
14225
14226                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
14227                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
14228                }
14229            }
14230        }
14231
14232        @Override
14233        void handleReturnCode() {
14234            if (mObserver != null) {
14235                try {
14236                    mObserver.onGetStatsCompleted(mStats, mSuccess);
14237                } catch (RemoteException e) {
14238                    Slog.i(TAG, "Observer no longer exists.");
14239                }
14240            }
14241        }
14242
14243        @Override
14244        void handleServiceError() {
14245            Slog.e(TAG, "Could not measure application " + mStats.packageName
14246                            + " external storage");
14247        }
14248    }
14249
14250    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
14251            throws RemoteException {
14252        long result = 0;
14253        for (File path : paths) {
14254            result += mcs.calculateDirectorySize(path.getAbsolutePath());
14255        }
14256        return result;
14257    }
14258
14259    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14260        for (File path : paths) {
14261            try {
14262                mcs.clearDirectory(path.getAbsolutePath());
14263            } catch (RemoteException e) {
14264            }
14265        }
14266    }
14267
14268    static class OriginInfo {
14269        /**
14270         * Location where install is coming from, before it has been
14271         * copied/renamed into place. This could be a single monolithic APK
14272         * file, or a cluster directory. This location may be untrusted.
14273         */
14274        final File file;
14275        final String cid;
14276
14277        /**
14278         * Flag indicating that {@link #file} or {@link #cid} has already been
14279         * staged, meaning downstream users don't need to defensively copy the
14280         * contents.
14281         */
14282        final boolean staged;
14283
14284        /**
14285         * Flag indicating that {@link #file} or {@link #cid} is an already
14286         * installed app that is being moved.
14287         */
14288        final boolean existing;
14289
14290        final String resolvedPath;
14291        final File resolvedFile;
14292
14293        static OriginInfo fromNothing() {
14294            return new OriginInfo(null, null, false, false);
14295        }
14296
14297        static OriginInfo fromUntrustedFile(File file) {
14298            return new OriginInfo(file, null, false, false);
14299        }
14300
14301        static OriginInfo fromExistingFile(File file) {
14302            return new OriginInfo(file, null, false, true);
14303        }
14304
14305        static OriginInfo fromStagedFile(File file) {
14306            return new OriginInfo(file, null, true, false);
14307        }
14308
14309        static OriginInfo fromStagedContainer(String cid) {
14310            return new OriginInfo(null, cid, true, false);
14311        }
14312
14313        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14314            this.file = file;
14315            this.cid = cid;
14316            this.staged = staged;
14317            this.existing = existing;
14318
14319            if (cid != null) {
14320                resolvedPath = PackageHelper.getSdDir(cid);
14321                resolvedFile = new File(resolvedPath);
14322            } else if (file != null) {
14323                resolvedPath = file.getAbsolutePath();
14324                resolvedFile = file;
14325            } else {
14326                resolvedPath = null;
14327                resolvedFile = null;
14328            }
14329        }
14330    }
14331
14332    static class MoveInfo {
14333        final int moveId;
14334        final String fromUuid;
14335        final String toUuid;
14336        final String packageName;
14337        final String dataAppName;
14338        final int appId;
14339        final String seinfo;
14340        final int targetSdkVersion;
14341
14342        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14343                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14344            this.moveId = moveId;
14345            this.fromUuid = fromUuid;
14346            this.toUuid = toUuid;
14347            this.packageName = packageName;
14348            this.dataAppName = dataAppName;
14349            this.appId = appId;
14350            this.seinfo = seinfo;
14351            this.targetSdkVersion = targetSdkVersion;
14352        }
14353    }
14354
14355    static class VerificationInfo {
14356        /** A constant used to indicate that a uid value is not present. */
14357        public static final int NO_UID = -1;
14358
14359        /** URI referencing where the package was downloaded from. */
14360        final Uri originatingUri;
14361
14362        /** HTTP referrer URI associated with the originatingURI. */
14363        final Uri referrer;
14364
14365        /** UID of the application that the install request originated from. */
14366        final int originatingUid;
14367
14368        /** UID of application requesting the install */
14369        final int installerUid;
14370
14371        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14372            this.originatingUri = originatingUri;
14373            this.referrer = referrer;
14374            this.originatingUid = originatingUid;
14375            this.installerUid = installerUid;
14376        }
14377    }
14378
14379    class InstallParams extends HandlerParams {
14380        final OriginInfo origin;
14381        final MoveInfo move;
14382        final IPackageInstallObserver2 observer;
14383        int installFlags;
14384        final String installerPackageName;
14385        final String volumeUuid;
14386        private InstallArgs mArgs;
14387        private int mRet;
14388        final String packageAbiOverride;
14389        final String[] grantedRuntimePermissions;
14390        final VerificationInfo verificationInfo;
14391        final Certificate[][] certificates;
14392        final int installReason;
14393
14394        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14395                int installFlags, String installerPackageName, String volumeUuid,
14396                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14397                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14398            super(user);
14399            this.origin = origin;
14400            this.move = move;
14401            this.observer = observer;
14402            this.installFlags = installFlags;
14403            this.installerPackageName = installerPackageName;
14404            this.volumeUuid = volumeUuid;
14405            this.verificationInfo = verificationInfo;
14406            this.packageAbiOverride = packageAbiOverride;
14407            this.grantedRuntimePermissions = grantedPermissions;
14408            this.certificates = certificates;
14409            this.installReason = installReason;
14410        }
14411
14412        @Override
14413        public String toString() {
14414            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14415                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14416        }
14417
14418        private int installLocationPolicy(PackageInfoLite pkgLite) {
14419            String packageName = pkgLite.packageName;
14420            int installLocation = pkgLite.installLocation;
14421            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14422            // reader
14423            synchronized (mPackages) {
14424                // Currently installed package which the new package is attempting to replace or
14425                // null if no such package is installed.
14426                PackageParser.Package installedPkg = mPackages.get(packageName);
14427                // Package which currently owns the data which the new package will own if installed.
14428                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14429                // will be null whereas dataOwnerPkg will contain information about the package
14430                // which was uninstalled while keeping its data.
14431                PackageParser.Package dataOwnerPkg = installedPkg;
14432                if (dataOwnerPkg  == null) {
14433                    PackageSetting ps = mSettings.mPackages.get(packageName);
14434                    if (ps != null) {
14435                        dataOwnerPkg = ps.pkg;
14436                    }
14437                }
14438
14439                if (dataOwnerPkg != null) {
14440                    // If installed, the package will get access to data left on the device by its
14441                    // predecessor. As a security measure, this is permited only if this is not a
14442                    // version downgrade or if the predecessor package is marked as debuggable and
14443                    // a downgrade is explicitly requested.
14444                    //
14445                    // On debuggable platform builds, downgrades are permitted even for
14446                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14447                    // not offer security guarantees and thus it's OK to disable some security
14448                    // mechanisms to make debugging/testing easier on those builds. However, even on
14449                    // debuggable builds downgrades of packages are permitted only if requested via
14450                    // installFlags. This is because we aim to keep the behavior of debuggable
14451                    // platform builds as close as possible to the behavior of non-debuggable
14452                    // platform builds.
14453                    final boolean downgradeRequested =
14454                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14455                    final boolean packageDebuggable =
14456                                (dataOwnerPkg.applicationInfo.flags
14457                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14458                    final boolean downgradePermitted =
14459                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14460                    if (!downgradePermitted) {
14461                        try {
14462                            checkDowngrade(dataOwnerPkg, pkgLite);
14463                        } catch (PackageManagerException e) {
14464                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14465                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14466                        }
14467                    }
14468                }
14469
14470                if (installedPkg != null) {
14471                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14472                        // Check for updated system application.
14473                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14474                            if (onSd) {
14475                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14476                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14477                            }
14478                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14479                        } else {
14480                            if (onSd) {
14481                                // Install flag overrides everything.
14482                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14483                            }
14484                            // If current upgrade specifies particular preference
14485                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14486                                // Application explicitly specified internal.
14487                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14488                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14489                                // App explictly prefers external. Let policy decide
14490                            } else {
14491                                // Prefer previous location
14492                                if (isExternal(installedPkg)) {
14493                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14494                                }
14495                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14496                            }
14497                        }
14498                    } else {
14499                        // Invalid install. Return error code
14500                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14501                    }
14502                }
14503            }
14504            // All the special cases have been taken care of.
14505            // Return result based on recommended install location.
14506            if (onSd) {
14507                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14508            }
14509            return pkgLite.recommendedInstallLocation;
14510        }
14511
14512        /*
14513         * Invoke remote method to get package information and install
14514         * location values. Override install location based on default
14515         * policy if needed and then create install arguments based
14516         * on the install location.
14517         */
14518        public void handleStartCopy() throws RemoteException {
14519            int ret = PackageManager.INSTALL_SUCCEEDED;
14520
14521            // If we're already staged, we've firmly committed to an install location
14522            if (origin.staged) {
14523                if (origin.file != null) {
14524                    installFlags |= PackageManager.INSTALL_INTERNAL;
14525                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14526                } else if (origin.cid != null) {
14527                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14528                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14529                } else {
14530                    throw new IllegalStateException("Invalid stage location");
14531                }
14532            }
14533
14534            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14535            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14536            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14537            PackageInfoLite pkgLite = null;
14538
14539            if (onInt && onSd) {
14540                // Check if both bits are set.
14541                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14542                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14543            } else if (onSd && ephemeral) {
14544                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14545                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14546            } else {
14547                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14548                        packageAbiOverride);
14549
14550                if (DEBUG_EPHEMERAL && ephemeral) {
14551                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14552                }
14553
14554                /*
14555                 * If we have too little free space, try to free cache
14556                 * before giving up.
14557                 */
14558                if (!origin.staged && pkgLite.recommendedInstallLocation
14559                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14560                    // TODO: focus freeing disk space on the target device
14561                    final StorageManager storage = StorageManager.from(mContext);
14562                    final long lowThreshold = storage.getStorageLowBytes(
14563                            Environment.getDataDirectory());
14564
14565                    final long sizeBytes = mContainerService.calculateInstalledSize(
14566                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14567
14568                    try {
14569                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14570                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14571                                installFlags, packageAbiOverride);
14572                    } catch (InstallerException e) {
14573                        Slog.w(TAG, "Failed to free cache", e);
14574                    }
14575
14576                    /*
14577                     * The cache free must have deleted the file we
14578                     * downloaded to install.
14579                     *
14580                     * TODO: fix the "freeCache" call to not delete
14581                     *       the file we care about.
14582                     */
14583                    if (pkgLite.recommendedInstallLocation
14584                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14585                        pkgLite.recommendedInstallLocation
14586                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14587                    }
14588                }
14589            }
14590
14591            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14592                int loc = pkgLite.recommendedInstallLocation;
14593                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14594                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14595                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14596                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14597                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14598                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14599                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14600                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14601                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14602                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14603                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14604                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14605                } else {
14606                    // Override with defaults if needed.
14607                    loc = installLocationPolicy(pkgLite);
14608                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14609                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14610                    } else if (!onSd && !onInt) {
14611                        // Override install location with flags
14612                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14613                            // Set the flag to install on external media.
14614                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14615                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14616                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14617                            if (DEBUG_EPHEMERAL) {
14618                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14619                            }
14620                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14621                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14622                                    |PackageManager.INSTALL_INTERNAL);
14623                        } else {
14624                            // Make sure the flag for installing on external
14625                            // media is unset
14626                            installFlags |= PackageManager.INSTALL_INTERNAL;
14627                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14628                        }
14629                    }
14630                }
14631            }
14632
14633            final InstallArgs args = createInstallArgs(this);
14634            mArgs = args;
14635
14636            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14637                // TODO: http://b/22976637
14638                // Apps installed for "all" users use the device owner to verify the app
14639                UserHandle verifierUser = getUser();
14640                if (verifierUser == UserHandle.ALL) {
14641                    verifierUser = UserHandle.SYSTEM;
14642                }
14643
14644                /*
14645                 * Determine if we have any installed package verifiers. If we
14646                 * do, then we'll defer to them to verify the packages.
14647                 */
14648                final int requiredUid = mRequiredVerifierPackage == null ? -1
14649                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14650                                verifierUser.getIdentifier());
14651                if (!origin.existing && requiredUid != -1
14652                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14653                    final Intent verification = new Intent(
14654                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14655                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14656                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14657                            PACKAGE_MIME_TYPE);
14658                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14659
14660                    // Query all live verifiers based on current user state
14661                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14662                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14663
14664                    if (DEBUG_VERIFY) {
14665                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14666                                + verification.toString() + " with " + pkgLite.verifiers.length
14667                                + " optional verifiers");
14668                    }
14669
14670                    final int verificationId = mPendingVerificationToken++;
14671
14672                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14673
14674                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14675                            installerPackageName);
14676
14677                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14678                            installFlags);
14679
14680                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14681                            pkgLite.packageName);
14682
14683                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14684                            pkgLite.versionCode);
14685
14686                    if (verificationInfo != null) {
14687                        if (verificationInfo.originatingUri != null) {
14688                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14689                                    verificationInfo.originatingUri);
14690                        }
14691                        if (verificationInfo.referrer != null) {
14692                            verification.putExtra(Intent.EXTRA_REFERRER,
14693                                    verificationInfo.referrer);
14694                        }
14695                        if (verificationInfo.originatingUid >= 0) {
14696                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14697                                    verificationInfo.originatingUid);
14698                        }
14699                        if (verificationInfo.installerUid >= 0) {
14700                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14701                                    verificationInfo.installerUid);
14702                        }
14703                    }
14704
14705                    final PackageVerificationState verificationState = new PackageVerificationState(
14706                            requiredUid, args);
14707
14708                    mPendingVerification.append(verificationId, verificationState);
14709
14710                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14711                            receivers, verificationState);
14712
14713                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14714                    final long idleDuration = getVerificationTimeout();
14715
14716                    /*
14717                     * If any sufficient verifiers were listed in the package
14718                     * manifest, attempt to ask them.
14719                     */
14720                    if (sufficientVerifiers != null) {
14721                        final int N = sufficientVerifiers.size();
14722                        if (N == 0) {
14723                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14724                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14725                        } else {
14726                            for (int i = 0; i < N; i++) {
14727                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14728                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14729                                        verifierComponent.getPackageName(), idleDuration,
14730                                        verifierUser.getIdentifier(), false, "package verifier");
14731
14732                                final Intent sufficientIntent = new Intent(verification);
14733                                sufficientIntent.setComponent(verifierComponent);
14734                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14735                            }
14736                        }
14737                    }
14738
14739                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14740                            mRequiredVerifierPackage, receivers);
14741                    if (ret == PackageManager.INSTALL_SUCCEEDED
14742                            && mRequiredVerifierPackage != null) {
14743                        Trace.asyncTraceBegin(
14744                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14745                        /*
14746                         * Send the intent to the required verification agent,
14747                         * but only start the verification timeout after the
14748                         * target BroadcastReceivers have run.
14749                         */
14750                        verification.setComponent(requiredVerifierComponent);
14751                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14752                                requiredVerifierComponent.getPackageName(), idleDuration,
14753                                verifierUser.getIdentifier(), false, "package verifier");
14754                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14755                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14756                                new BroadcastReceiver() {
14757                                    @Override
14758                                    public void onReceive(Context context, Intent intent) {
14759                                        final Message msg = mHandler
14760                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14761                                        msg.arg1 = verificationId;
14762                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14763                                    }
14764                                }, null, 0, null, null);
14765
14766                        /*
14767                         * We don't want the copy to proceed until verification
14768                         * succeeds, so null out this field.
14769                         */
14770                        mArgs = null;
14771                    }
14772                } else {
14773                    /*
14774                     * No package verification is enabled, so immediately start
14775                     * the remote call to initiate copy using temporary file.
14776                     */
14777                    ret = args.copyApk(mContainerService, true);
14778                }
14779            }
14780
14781            mRet = ret;
14782        }
14783
14784        @Override
14785        void handleReturnCode() {
14786            // If mArgs is null, then MCS couldn't be reached. When it
14787            // reconnects, it will try again to install. At that point, this
14788            // will succeed.
14789            if (mArgs != null) {
14790                processPendingInstall(mArgs, mRet);
14791            }
14792        }
14793
14794        @Override
14795        void handleServiceError() {
14796            mArgs = createInstallArgs(this);
14797            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14798        }
14799
14800        public boolean isForwardLocked() {
14801            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14802        }
14803    }
14804
14805    /**
14806     * Used during creation of InstallArgs
14807     *
14808     * @param installFlags package installation flags
14809     * @return true if should be installed on external storage
14810     */
14811    private static boolean installOnExternalAsec(int installFlags) {
14812        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14813            return false;
14814        }
14815        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14816            return true;
14817        }
14818        return false;
14819    }
14820
14821    /**
14822     * Used during creation of InstallArgs
14823     *
14824     * @param installFlags package installation flags
14825     * @return true if should be installed as forward locked
14826     */
14827    private static boolean installForwardLocked(int installFlags) {
14828        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14829    }
14830
14831    private InstallArgs createInstallArgs(InstallParams params) {
14832        if (params.move != null) {
14833            return new MoveInstallArgs(params);
14834        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14835            return new AsecInstallArgs(params);
14836        } else {
14837            return new FileInstallArgs(params);
14838        }
14839    }
14840
14841    /**
14842     * Create args that describe an existing installed package. Typically used
14843     * when cleaning up old installs, or used as a move source.
14844     */
14845    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14846            String resourcePath, String[] instructionSets) {
14847        final boolean isInAsec;
14848        if (installOnExternalAsec(installFlags)) {
14849            /* Apps on SD card are always in ASEC containers. */
14850            isInAsec = true;
14851        } else if (installForwardLocked(installFlags)
14852                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14853            /*
14854             * Forward-locked apps are only in ASEC containers if they're the
14855             * new style
14856             */
14857            isInAsec = true;
14858        } else {
14859            isInAsec = false;
14860        }
14861
14862        if (isInAsec) {
14863            return new AsecInstallArgs(codePath, instructionSets,
14864                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14865        } else {
14866            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14867        }
14868    }
14869
14870    static abstract class InstallArgs {
14871        /** @see InstallParams#origin */
14872        final OriginInfo origin;
14873        /** @see InstallParams#move */
14874        final MoveInfo move;
14875
14876        final IPackageInstallObserver2 observer;
14877        // Always refers to PackageManager flags only
14878        final int installFlags;
14879        final String installerPackageName;
14880        final String volumeUuid;
14881        final UserHandle user;
14882        final String abiOverride;
14883        final String[] installGrantPermissions;
14884        /** If non-null, drop an async trace when the install completes */
14885        final String traceMethod;
14886        final int traceCookie;
14887        final Certificate[][] certificates;
14888        final int installReason;
14889
14890        // The list of instruction sets supported by this app. This is currently
14891        // only used during the rmdex() phase to clean up resources. We can get rid of this
14892        // if we move dex files under the common app path.
14893        /* nullable */ String[] instructionSets;
14894
14895        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14896                int installFlags, String installerPackageName, String volumeUuid,
14897                UserHandle user, String[] instructionSets,
14898                String abiOverride, String[] installGrantPermissions,
14899                String traceMethod, int traceCookie, Certificate[][] certificates,
14900                int installReason) {
14901            this.origin = origin;
14902            this.move = move;
14903            this.installFlags = installFlags;
14904            this.observer = observer;
14905            this.installerPackageName = installerPackageName;
14906            this.volumeUuid = volumeUuid;
14907            this.user = user;
14908            this.instructionSets = instructionSets;
14909            this.abiOverride = abiOverride;
14910            this.installGrantPermissions = installGrantPermissions;
14911            this.traceMethod = traceMethod;
14912            this.traceCookie = traceCookie;
14913            this.certificates = certificates;
14914            this.installReason = installReason;
14915        }
14916
14917        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14918        abstract int doPreInstall(int status);
14919
14920        /**
14921         * Rename package into final resting place. All paths on the given
14922         * scanned package should be updated to reflect the rename.
14923         */
14924        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14925        abstract int doPostInstall(int status, int uid);
14926
14927        /** @see PackageSettingBase#codePathString */
14928        abstract String getCodePath();
14929        /** @see PackageSettingBase#resourcePathString */
14930        abstract String getResourcePath();
14931
14932        // Need installer lock especially for dex file removal.
14933        abstract void cleanUpResourcesLI();
14934        abstract boolean doPostDeleteLI(boolean delete);
14935
14936        /**
14937         * Called before the source arguments are copied. This is used mostly
14938         * for MoveParams when it needs to read the source file to put it in the
14939         * destination.
14940         */
14941        int doPreCopy() {
14942            return PackageManager.INSTALL_SUCCEEDED;
14943        }
14944
14945        /**
14946         * Called after the source arguments are copied. This is used mostly for
14947         * MoveParams when it needs to read the source file to put it in the
14948         * destination.
14949         */
14950        int doPostCopy(int uid) {
14951            return PackageManager.INSTALL_SUCCEEDED;
14952        }
14953
14954        protected boolean isFwdLocked() {
14955            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14956        }
14957
14958        protected boolean isExternalAsec() {
14959            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14960        }
14961
14962        protected boolean isEphemeral() {
14963            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14964        }
14965
14966        UserHandle getUser() {
14967            return user;
14968        }
14969    }
14970
14971    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14972        if (!allCodePaths.isEmpty()) {
14973            if (instructionSets == null) {
14974                throw new IllegalStateException("instructionSet == null");
14975            }
14976            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14977            for (String codePath : allCodePaths) {
14978                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14979                    try {
14980                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14981                    } catch (InstallerException ignored) {
14982                    }
14983                }
14984            }
14985        }
14986    }
14987
14988    /**
14989     * Logic to handle installation of non-ASEC applications, including copying
14990     * and renaming logic.
14991     */
14992    class FileInstallArgs extends InstallArgs {
14993        private File codeFile;
14994        private File resourceFile;
14995
14996        // Example topology:
14997        // /data/app/com.example/base.apk
14998        // /data/app/com.example/split_foo.apk
14999        // /data/app/com.example/lib/arm/libfoo.so
15000        // /data/app/com.example/lib/arm64/libfoo.so
15001        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15002
15003        /** New install */
15004        FileInstallArgs(InstallParams params) {
15005            super(params.origin, params.move, params.observer, params.installFlags,
15006                    params.installerPackageName, params.volumeUuid,
15007                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15008                    params.grantedRuntimePermissions,
15009                    params.traceMethod, params.traceCookie, params.certificates,
15010                    params.installReason);
15011            if (isFwdLocked()) {
15012                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15013            }
15014        }
15015
15016        /** Existing install */
15017        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15018            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15019                    null, null, null, 0, null /*certificates*/,
15020                    PackageManager.INSTALL_REASON_UNKNOWN);
15021            this.codeFile = (codePath != null) ? new File(codePath) : null;
15022            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15023        }
15024
15025        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15026            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15027            try {
15028                return doCopyApk(imcs, temp);
15029            } finally {
15030                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15031            }
15032        }
15033
15034        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15035            if (origin.staged) {
15036                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15037                codeFile = origin.file;
15038                resourceFile = origin.file;
15039                return PackageManager.INSTALL_SUCCEEDED;
15040            }
15041
15042            try {
15043                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15044                final File tempDir =
15045                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15046                codeFile = tempDir;
15047                resourceFile = tempDir;
15048            } catch (IOException e) {
15049                Slog.w(TAG, "Failed to create copy file: " + e);
15050                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15051            }
15052
15053            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15054                @Override
15055                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15056                    if (!FileUtils.isValidExtFilename(name)) {
15057                        throw new IllegalArgumentException("Invalid filename: " + name);
15058                    }
15059                    try {
15060                        final File file = new File(codeFile, name);
15061                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15062                                O_RDWR | O_CREAT, 0644);
15063                        Os.chmod(file.getAbsolutePath(), 0644);
15064                        return new ParcelFileDescriptor(fd);
15065                    } catch (ErrnoException e) {
15066                        throw new RemoteException("Failed to open: " + e.getMessage());
15067                    }
15068                }
15069            };
15070
15071            int ret = PackageManager.INSTALL_SUCCEEDED;
15072            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15073            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15074                Slog.e(TAG, "Failed to copy package");
15075                return ret;
15076            }
15077
15078            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15079            NativeLibraryHelper.Handle handle = null;
15080            try {
15081                handle = NativeLibraryHelper.Handle.create(codeFile);
15082                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15083                        abiOverride);
15084            } catch (IOException e) {
15085                Slog.e(TAG, "Copying native libraries failed", e);
15086                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15087            } finally {
15088                IoUtils.closeQuietly(handle);
15089            }
15090
15091            return ret;
15092        }
15093
15094        int doPreInstall(int status) {
15095            if (status != PackageManager.INSTALL_SUCCEEDED) {
15096                cleanUp();
15097            }
15098            return status;
15099        }
15100
15101        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15102            if (status != PackageManager.INSTALL_SUCCEEDED) {
15103                cleanUp();
15104                return false;
15105            }
15106
15107            final File targetDir = codeFile.getParentFile();
15108            final File beforeCodeFile = codeFile;
15109            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15110
15111            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15112            try {
15113                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15114            } catch (ErrnoException e) {
15115                Slog.w(TAG, "Failed to rename", e);
15116                return false;
15117            }
15118
15119            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15120                Slog.w(TAG, "Failed to restorecon");
15121                return false;
15122            }
15123
15124            // Reflect the rename internally
15125            codeFile = afterCodeFile;
15126            resourceFile = afterCodeFile;
15127
15128            // Reflect the rename in scanned details
15129            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15130            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15131                    afterCodeFile, pkg.baseCodePath));
15132            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15133                    afterCodeFile, pkg.splitCodePaths));
15134
15135            // Reflect the rename in app info
15136            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15137            pkg.setApplicationInfoCodePath(pkg.codePath);
15138            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15139            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15140            pkg.setApplicationInfoResourcePath(pkg.codePath);
15141            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15142            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15143
15144            return true;
15145        }
15146
15147        int doPostInstall(int status, int uid) {
15148            if (status != PackageManager.INSTALL_SUCCEEDED) {
15149                cleanUp();
15150            }
15151            return status;
15152        }
15153
15154        @Override
15155        String getCodePath() {
15156            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15157        }
15158
15159        @Override
15160        String getResourcePath() {
15161            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15162        }
15163
15164        private boolean cleanUp() {
15165            if (codeFile == null || !codeFile.exists()) {
15166                return false;
15167            }
15168
15169            removeCodePathLI(codeFile);
15170
15171            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15172                resourceFile.delete();
15173            }
15174
15175            return true;
15176        }
15177
15178        void cleanUpResourcesLI() {
15179            // Try enumerating all code paths before deleting
15180            List<String> allCodePaths = Collections.EMPTY_LIST;
15181            if (codeFile != null && codeFile.exists()) {
15182                try {
15183                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15184                    allCodePaths = pkg.getAllCodePaths();
15185                } catch (PackageParserException e) {
15186                    // Ignored; we tried our best
15187                }
15188            }
15189
15190            cleanUp();
15191            removeDexFiles(allCodePaths, instructionSets);
15192        }
15193
15194        boolean doPostDeleteLI(boolean delete) {
15195            // XXX err, shouldn't we respect the delete flag?
15196            cleanUpResourcesLI();
15197            return true;
15198        }
15199    }
15200
15201    private boolean isAsecExternal(String cid) {
15202        final String asecPath = PackageHelper.getSdFilesystem(cid);
15203        return !asecPath.startsWith(mAsecInternalPath);
15204    }
15205
15206    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15207            PackageManagerException {
15208        if (copyRet < 0) {
15209            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15210                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15211                throw new PackageManagerException(copyRet, message);
15212            }
15213        }
15214    }
15215
15216    /**
15217     * Extract the StorageManagerService "container ID" from the full code path of an
15218     * .apk.
15219     */
15220    static String cidFromCodePath(String fullCodePath) {
15221        int eidx = fullCodePath.lastIndexOf("/");
15222        String subStr1 = fullCodePath.substring(0, eidx);
15223        int sidx = subStr1.lastIndexOf("/");
15224        return subStr1.substring(sidx+1, eidx);
15225    }
15226
15227    /**
15228     * Logic to handle installation of ASEC applications, including copying and
15229     * renaming logic.
15230     */
15231    class AsecInstallArgs extends InstallArgs {
15232        static final String RES_FILE_NAME = "pkg.apk";
15233        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15234
15235        String cid;
15236        String packagePath;
15237        String resourcePath;
15238
15239        /** New install */
15240        AsecInstallArgs(InstallParams params) {
15241            super(params.origin, params.move, params.observer, params.installFlags,
15242                    params.installerPackageName, params.volumeUuid,
15243                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15244                    params.grantedRuntimePermissions,
15245                    params.traceMethod, params.traceCookie, params.certificates,
15246                    params.installReason);
15247        }
15248
15249        /** Existing install */
15250        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15251                        boolean isExternal, boolean isForwardLocked) {
15252            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15253                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15254                    instructionSets, null, null, null, 0, null /*certificates*/,
15255                    PackageManager.INSTALL_REASON_UNKNOWN);
15256            // Hackily pretend we're still looking at a full code path
15257            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15258                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15259            }
15260
15261            // Extract cid from fullCodePath
15262            int eidx = fullCodePath.lastIndexOf("/");
15263            String subStr1 = fullCodePath.substring(0, eidx);
15264            int sidx = subStr1.lastIndexOf("/");
15265            cid = subStr1.substring(sidx+1, eidx);
15266            setMountPath(subStr1);
15267        }
15268
15269        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15270            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15271                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15272                    instructionSets, null, null, null, 0, null /*certificates*/,
15273                    PackageManager.INSTALL_REASON_UNKNOWN);
15274            this.cid = cid;
15275            setMountPath(PackageHelper.getSdDir(cid));
15276        }
15277
15278        void createCopyFile() {
15279            cid = mInstallerService.allocateExternalStageCidLegacy();
15280        }
15281
15282        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15283            if (origin.staged && origin.cid != null) {
15284                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15285                cid = origin.cid;
15286                setMountPath(PackageHelper.getSdDir(cid));
15287                return PackageManager.INSTALL_SUCCEEDED;
15288            }
15289
15290            if (temp) {
15291                createCopyFile();
15292            } else {
15293                /*
15294                 * Pre-emptively destroy the container since it's destroyed if
15295                 * copying fails due to it existing anyway.
15296                 */
15297                PackageHelper.destroySdDir(cid);
15298            }
15299
15300            final String newMountPath = imcs.copyPackageToContainer(
15301                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15302                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15303
15304            if (newMountPath != null) {
15305                setMountPath(newMountPath);
15306                return PackageManager.INSTALL_SUCCEEDED;
15307            } else {
15308                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15309            }
15310        }
15311
15312        @Override
15313        String getCodePath() {
15314            return packagePath;
15315        }
15316
15317        @Override
15318        String getResourcePath() {
15319            return resourcePath;
15320        }
15321
15322        int doPreInstall(int status) {
15323            if (status != PackageManager.INSTALL_SUCCEEDED) {
15324                // Destroy container
15325                PackageHelper.destroySdDir(cid);
15326            } else {
15327                boolean mounted = PackageHelper.isContainerMounted(cid);
15328                if (!mounted) {
15329                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15330                            Process.SYSTEM_UID);
15331                    if (newMountPath != null) {
15332                        setMountPath(newMountPath);
15333                    } else {
15334                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15335                    }
15336                }
15337            }
15338            return status;
15339        }
15340
15341        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15342            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15343            String newMountPath = null;
15344            if (PackageHelper.isContainerMounted(cid)) {
15345                // Unmount the container
15346                if (!PackageHelper.unMountSdDir(cid)) {
15347                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15348                    return false;
15349                }
15350            }
15351            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15352                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15353                        " which might be stale. Will try to clean up.");
15354                // Clean up the stale container and proceed to recreate.
15355                if (!PackageHelper.destroySdDir(newCacheId)) {
15356                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15357                    return false;
15358                }
15359                // Successfully cleaned up stale container. Try to rename again.
15360                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15361                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15362                            + " inspite of cleaning it up.");
15363                    return false;
15364                }
15365            }
15366            if (!PackageHelper.isContainerMounted(newCacheId)) {
15367                Slog.w(TAG, "Mounting container " + newCacheId);
15368                newMountPath = PackageHelper.mountSdDir(newCacheId,
15369                        getEncryptKey(), Process.SYSTEM_UID);
15370            } else {
15371                newMountPath = PackageHelper.getSdDir(newCacheId);
15372            }
15373            if (newMountPath == null) {
15374                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15375                return false;
15376            }
15377            Log.i(TAG, "Succesfully renamed " + cid +
15378                    " to " + newCacheId +
15379                    " at new path: " + newMountPath);
15380            cid = newCacheId;
15381
15382            final File beforeCodeFile = new File(packagePath);
15383            setMountPath(newMountPath);
15384            final File afterCodeFile = new File(packagePath);
15385
15386            // Reflect the rename in scanned details
15387            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15388            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15389                    afterCodeFile, pkg.baseCodePath));
15390            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15391                    afterCodeFile, pkg.splitCodePaths));
15392
15393            // Reflect the rename in app info
15394            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15395            pkg.setApplicationInfoCodePath(pkg.codePath);
15396            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15397            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15398            pkg.setApplicationInfoResourcePath(pkg.codePath);
15399            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15400            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15401
15402            return true;
15403        }
15404
15405        private void setMountPath(String mountPath) {
15406            final File mountFile = new File(mountPath);
15407
15408            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15409            if (monolithicFile.exists()) {
15410                packagePath = monolithicFile.getAbsolutePath();
15411                if (isFwdLocked()) {
15412                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15413                } else {
15414                    resourcePath = packagePath;
15415                }
15416            } else {
15417                packagePath = mountFile.getAbsolutePath();
15418                resourcePath = packagePath;
15419            }
15420        }
15421
15422        int doPostInstall(int status, int uid) {
15423            if (status != PackageManager.INSTALL_SUCCEEDED) {
15424                cleanUp();
15425            } else {
15426                final int groupOwner;
15427                final String protectedFile;
15428                if (isFwdLocked()) {
15429                    groupOwner = UserHandle.getSharedAppGid(uid);
15430                    protectedFile = RES_FILE_NAME;
15431                } else {
15432                    groupOwner = -1;
15433                    protectedFile = null;
15434                }
15435
15436                if (uid < Process.FIRST_APPLICATION_UID
15437                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15438                    Slog.e(TAG, "Failed to finalize " + cid);
15439                    PackageHelper.destroySdDir(cid);
15440                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15441                }
15442
15443                boolean mounted = PackageHelper.isContainerMounted(cid);
15444                if (!mounted) {
15445                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15446                }
15447            }
15448            return status;
15449        }
15450
15451        private void cleanUp() {
15452            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15453
15454            // Destroy secure container
15455            PackageHelper.destroySdDir(cid);
15456        }
15457
15458        private List<String> getAllCodePaths() {
15459            final File codeFile = new File(getCodePath());
15460            if (codeFile != null && codeFile.exists()) {
15461                try {
15462                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15463                    return pkg.getAllCodePaths();
15464                } catch (PackageParserException e) {
15465                    // Ignored; we tried our best
15466                }
15467            }
15468            return Collections.EMPTY_LIST;
15469        }
15470
15471        void cleanUpResourcesLI() {
15472            // Enumerate all code paths before deleting
15473            cleanUpResourcesLI(getAllCodePaths());
15474        }
15475
15476        private void cleanUpResourcesLI(List<String> allCodePaths) {
15477            cleanUp();
15478            removeDexFiles(allCodePaths, instructionSets);
15479        }
15480
15481        String getPackageName() {
15482            return getAsecPackageName(cid);
15483        }
15484
15485        boolean doPostDeleteLI(boolean delete) {
15486            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15487            final List<String> allCodePaths = getAllCodePaths();
15488            boolean mounted = PackageHelper.isContainerMounted(cid);
15489            if (mounted) {
15490                // Unmount first
15491                if (PackageHelper.unMountSdDir(cid)) {
15492                    mounted = false;
15493                }
15494            }
15495            if (!mounted && delete) {
15496                cleanUpResourcesLI(allCodePaths);
15497            }
15498            return !mounted;
15499        }
15500
15501        @Override
15502        int doPreCopy() {
15503            if (isFwdLocked()) {
15504                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15505                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15506                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15507                }
15508            }
15509
15510            return PackageManager.INSTALL_SUCCEEDED;
15511        }
15512
15513        @Override
15514        int doPostCopy(int uid) {
15515            if (isFwdLocked()) {
15516                if (uid < Process.FIRST_APPLICATION_UID
15517                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15518                                RES_FILE_NAME)) {
15519                    Slog.e(TAG, "Failed to finalize " + cid);
15520                    PackageHelper.destroySdDir(cid);
15521                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15522                }
15523            }
15524
15525            return PackageManager.INSTALL_SUCCEEDED;
15526        }
15527    }
15528
15529    /**
15530     * Logic to handle movement of existing installed applications.
15531     */
15532    class MoveInstallArgs extends InstallArgs {
15533        private File codeFile;
15534        private File resourceFile;
15535
15536        /** New install */
15537        MoveInstallArgs(InstallParams params) {
15538            super(params.origin, params.move, params.observer, params.installFlags,
15539                    params.installerPackageName, params.volumeUuid,
15540                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15541                    params.grantedRuntimePermissions,
15542                    params.traceMethod, params.traceCookie, params.certificates,
15543                    params.installReason);
15544        }
15545
15546        int copyApk(IMediaContainerService imcs, boolean temp) {
15547            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15548                    + move.fromUuid + " to " + move.toUuid);
15549            synchronized (mInstaller) {
15550                try {
15551                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15552                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15553                } catch (InstallerException e) {
15554                    Slog.w(TAG, "Failed to move app", e);
15555                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15556                }
15557            }
15558
15559            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15560            resourceFile = codeFile;
15561            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15562
15563            return PackageManager.INSTALL_SUCCEEDED;
15564        }
15565
15566        int doPreInstall(int status) {
15567            if (status != PackageManager.INSTALL_SUCCEEDED) {
15568                cleanUp(move.toUuid);
15569            }
15570            return status;
15571        }
15572
15573        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15574            if (status != PackageManager.INSTALL_SUCCEEDED) {
15575                cleanUp(move.toUuid);
15576                return false;
15577            }
15578
15579            // Reflect the move in app info
15580            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15581            pkg.setApplicationInfoCodePath(pkg.codePath);
15582            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15583            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15584            pkg.setApplicationInfoResourcePath(pkg.codePath);
15585            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15586            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15587
15588            return true;
15589        }
15590
15591        int doPostInstall(int status, int uid) {
15592            if (status == PackageManager.INSTALL_SUCCEEDED) {
15593                cleanUp(move.fromUuid);
15594            } else {
15595                cleanUp(move.toUuid);
15596            }
15597            return status;
15598        }
15599
15600        @Override
15601        String getCodePath() {
15602            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15603        }
15604
15605        @Override
15606        String getResourcePath() {
15607            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15608        }
15609
15610        private boolean cleanUp(String volumeUuid) {
15611            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15612                    move.dataAppName);
15613            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15614            final int[] userIds = sUserManager.getUserIds();
15615            synchronized (mInstallLock) {
15616                // Clean up both app data and code
15617                // All package moves are frozen until finished
15618                for (int userId : userIds) {
15619                    try {
15620                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15621                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15622                    } catch (InstallerException e) {
15623                        Slog.w(TAG, String.valueOf(e));
15624                    }
15625                }
15626                removeCodePathLI(codeFile);
15627            }
15628            return true;
15629        }
15630
15631        void cleanUpResourcesLI() {
15632            throw new UnsupportedOperationException();
15633        }
15634
15635        boolean doPostDeleteLI(boolean delete) {
15636            throw new UnsupportedOperationException();
15637        }
15638    }
15639
15640    static String getAsecPackageName(String packageCid) {
15641        int idx = packageCid.lastIndexOf("-");
15642        if (idx == -1) {
15643            return packageCid;
15644        }
15645        return packageCid.substring(0, idx);
15646    }
15647
15648    // Utility method used to create code paths based on package name and available index.
15649    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15650        String idxStr = "";
15651        int idx = 1;
15652        // Fall back to default value of idx=1 if prefix is not
15653        // part of oldCodePath
15654        if (oldCodePath != null) {
15655            String subStr = oldCodePath;
15656            // Drop the suffix right away
15657            if (suffix != null && subStr.endsWith(suffix)) {
15658                subStr = subStr.substring(0, subStr.length() - suffix.length());
15659            }
15660            // If oldCodePath already contains prefix find out the
15661            // ending index to either increment or decrement.
15662            int sidx = subStr.lastIndexOf(prefix);
15663            if (sidx != -1) {
15664                subStr = subStr.substring(sidx + prefix.length());
15665                if (subStr != null) {
15666                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15667                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15668                    }
15669                    try {
15670                        idx = Integer.parseInt(subStr);
15671                        if (idx <= 1) {
15672                            idx++;
15673                        } else {
15674                            idx--;
15675                        }
15676                    } catch(NumberFormatException e) {
15677                    }
15678                }
15679            }
15680        }
15681        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15682        return prefix + idxStr;
15683    }
15684
15685    private File getNextCodePath(File targetDir, String packageName) {
15686        File result;
15687        SecureRandom random = new SecureRandom();
15688        byte[] bytes = new byte[16];
15689        do {
15690            random.nextBytes(bytes);
15691            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15692            result = new File(targetDir, packageName + "-" + suffix);
15693        } while (result.exists());
15694        return result;
15695    }
15696
15697    // Utility method that returns the relative package path with respect
15698    // to the installation directory. Like say for /data/data/com.test-1.apk
15699    // string com.test-1 is returned.
15700    static String deriveCodePathName(String codePath) {
15701        if (codePath == null) {
15702            return null;
15703        }
15704        final File codeFile = new File(codePath);
15705        final String name = codeFile.getName();
15706        if (codeFile.isDirectory()) {
15707            return name;
15708        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15709            final int lastDot = name.lastIndexOf('.');
15710            return name.substring(0, lastDot);
15711        } else {
15712            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15713            return null;
15714        }
15715    }
15716
15717    static class PackageInstalledInfo {
15718        String name;
15719        int uid;
15720        // The set of users that originally had this package installed.
15721        int[] origUsers;
15722        // The set of users that now have this package installed.
15723        int[] newUsers;
15724        PackageParser.Package pkg;
15725        int returnCode;
15726        String returnMsg;
15727        PackageRemovedInfo removedInfo;
15728        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15729
15730        public void setError(int code, String msg) {
15731            setReturnCode(code);
15732            setReturnMessage(msg);
15733            Slog.w(TAG, msg);
15734        }
15735
15736        public void setError(String msg, PackageParserException e) {
15737            setReturnCode(e.error);
15738            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15739            Slog.w(TAG, msg, e);
15740        }
15741
15742        public void setError(String msg, PackageManagerException e) {
15743            returnCode = e.error;
15744            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15745            Slog.w(TAG, msg, e);
15746        }
15747
15748        public void setReturnCode(int returnCode) {
15749            this.returnCode = returnCode;
15750            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15751            for (int i = 0; i < childCount; i++) {
15752                addedChildPackages.valueAt(i).returnCode = returnCode;
15753            }
15754        }
15755
15756        private void setReturnMessage(String returnMsg) {
15757            this.returnMsg = returnMsg;
15758            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15759            for (int i = 0; i < childCount; i++) {
15760                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15761            }
15762        }
15763
15764        // In some error cases we want to convey more info back to the observer
15765        String origPackage;
15766        String origPermission;
15767    }
15768
15769    /*
15770     * Install a non-existing package.
15771     */
15772    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15773            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15774            PackageInstalledInfo res, int installReason) {
15775        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15776
15777        // Remember this for later, in case we need to rollback this install
15778        String pkgName = pkg.packageName;
15779
15780        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15781
15782        synchronized(mPackages) {
15783            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15784            if (renamedPackage != null) {
15785                // A package with the same name is already installed, though
15786                // it has been renamed to an older name.  The package we
15787                // are trying to install should be installed as an update to
15788                // the existing one, but that has not been requested, so bail.
15789                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15790                        + " without first uninstalling package running as "
15791                        + renamedPackage);
15792                return;
15793            }
15794            if (mPackages.containsKey(pkgName)) {
15795                // Don't allow installation over an existing package with the same name.
15796                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15797                        + " without first uninstalling.");
15798                return;
15799            }
15800        }
15801
15802        try {
15803            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15804                    System.currentTimeMillis(), user);
15805
15806            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15807
15808            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15809                prepareAppDataAfterInstallLIF(newPackage);
15810
15811            } else {
15812                // Remove package from internal structures, but keep around any
15813                // data that might have already existed
15814                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15815                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15816            }
15817        } catch (PackageManagerException e) {
15818            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15819        }
15820
15821        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15822    }
15823
15824    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15825        // Can't rotate keys during boot or if sharedUser.
15826        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15827                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15828            return false;
15829        }
15830        // app is using upgradeKeySets; make sure all are valid
15831        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15832        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15833        for (int i = 0; i < upgradeKeySets.length; i++) {
15834            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15835                Slog.wtf(TAG, "Package "
15836                         + (oldPs.name != null ? oldPs.name : "<null>")
15837                         + " contains upgrade-key-set reference to unknown key-set: "
15838                         + upgradeKeySets[i]
15839                         + " reverting to signatures check.");
15840                return false;
15841            }
15842        }
15843        return true;
15844    }
15845
15846    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15847        // Upgrade keysets are being used.  Determine if new package has a superset of the
15848        // required keys.
15849        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15850        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15851        for (int i = 0; i < upgradeKeySets.length; i++) {
15852            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15853            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15854                return true;
15855            }
15856        }
15857        return false;
15858    }
15859
15860    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15861        try (DigestInputStream digestStream =
15862                new DigestInputStream(new FileInputStream(file), digest)) {
15863            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15864        }
15865    }
15866
15867    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15868            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15869            int installReason) {
15870        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15871
15872        final PackageParser.Package oldPackage;
15873        final String pkgName = pkg.packageName;
15874        final int[] allUsers;
15875        final int[] installedUsers;
15876
15877        synchronized(mPackages) {
15878            oldPackage = mPackages.get(pkgName);
15879            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15880
15881            // don't allow upgrade to target a release SDK from a pre-release SDK
15882            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15883                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15884            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15885                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15886            if (oldTargetsPreRelease
15887                    && !newTargetsPreRelease
15888                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15889                Slog.w(TAG, "Can't install package targeting released sdk");
15890                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15891                return;
15892            }
15893
15894            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15895
15896            // don't allow an upgrade from full to ephemeral
15897            if (isInstantApp && !ps.getInstantApp(user.getIdentifier())) {
15898                // can't downgrade from full to instant
15899                Slog.w(TAG, "Can't replace app with instant app: " + pkgName);
15900                res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15901                return;
15902            }
15903
15904            // verify signatures are valid
15905            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15906                if (!checkUpgradeKeySetLP(ps, pkg)) {
15907                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15908                            "New package not signed by keys specified by upgrade-keysets: "
15909                                    + pkgName);
15910                    return;
15911                }
15912            } else {
15913                // default to original signature matching
15914                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15915                        != PackageManager.SIGNATURE_MATCH) {
15916                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15917                            "New package has a different signature: " + pkgName);
15918                    return;
15919                }
15920            }
15921
15922            // don't allow a system upgrade unless the upgrade hash matches
15923            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15924                byte[] digestBytes = null;
15925                try {
15926                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15927                    updateDigest(digest, new File(pkg.baseCodePath));
15928                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15929                        for (String path : pkg.splitCodePaths) {
15930                            updateDigest(digest, new File(path));
15931                        }
15932                    }
15933                    digestBytes = digest.digest();
15934                } catch (NoSuchAlgorithmException | IOException e) {
15935                    res.setError(INSTALL_FAILED_INVALID_APK,
15936                            "Could not compute hash: " + pkgName);
15937                    return;
15938                }
15939                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15940                    res.setError(INSTALL_FAILED_INVALID_APK,
15941                            "New package fails restrict-update check: " + pkgName);
15942                    return;
15943                }
15944                // retain upgrade restriction
15945                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15946            }
15947
15948            // Check for shared user id changes
15949            String invalidPackageName =
15950                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15951            if (invalidPackageName != null) {
15952                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15953                        "Package " + invalidPackageName + " tried to change user "
15954                                + oldPackage.mSharedUserId);
15955                return;
15956            }
15957
15958            // In case of rollback, remember per-user/profile install state
15959            allUsers = sUserManager.getUserIds();
15960            installedUsers = ps.queryInstalledUsers(allUsers, true);
15961        }
15962
15963        // Update what is removed
15964        res.removedInfo = new PackageRemovedInfo();
15965        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15966        res.removedInfo.removedPackage = oldPackage.packageName;
15967        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15968        res.removedInfo.isUpdate = true;
15969        res.removedInfo.origUsers = installedUsers;
15970        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15971        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15972        for (int i = 0; i < installedUsers.length; i++) {
15973            final int userId = installedUsers[i];
15974            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15975        }
15976
15977        final int childCount = (oldPackage.childPackages != null)
15978                ? oldPackage.childPackages.size() : 0;
15979        for (int i = 0; i < childCount; i++) {
15980            boolean childPackageUpdated = false;
15981            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15982            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15983            if (res.addedChildPackages != null) {
15984                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15985                if (childRes != null) {
15986                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15987                    childRes.removedInfo.removedPackage = childPkg.packageName;
15988                    childRes.removedInfo.isUpdate = true;
15989                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15990                    childPackageUpdated = true;
15991                }
15992            }
15993            if (!childPackageUpdated) {
15994                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15995                childRemovedRes.removedPackage = childPkg.packageName;
15996                childRemovedRes.isUpdate = false;
15997                childRemovedRes.dataRemoved = true;
15998                synchronized (mPackages) {
15999                    if (childPs != null) {
16000                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16001                    }
16002                }
16003                if (res.removedInfo.removedChildPackages == null) {
16004                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16005                }
16006                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16007            }
16008        }
16009
16010        boolean sysPkg = (isSystemApp(oldPackage));
16011        if (sysPkg) {
16012            // Set the system/privileged flags as needed
16013            final boolean privileged =
16014                    (oldPackage.applicationInfo.privateFlags
16015                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16016            final int systemPolicyFlags = policyFlags
16017                    | PackageParser.PARSE_IS_SYSTEM
16018                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16019
16020            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16021                    user, allUsers, installerPackageName, res, installReason);
16022        } else {
16023            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16024                    user, allUsers, installerPackageName, res, installReason);
16025        }
16026    }
16027
16028    public List<String> getPreviousCodePaths(String packageName) {
16029        final PackageSetting ps = mSettings.mPackages.get(packageName);
16030        final List<String> result = new ArrayList<String>();
16031        if (ps != null && ps.oldCodePaths != null) {
16032            result.addAll(ps.oldCodePaths);
16033        }
16034        return result;
16035    }
16036
16037    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16038            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16039            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16040            int installReason) {
16041        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16042                + deletedPackage);
16043
16044        String pkgName = deletedPackage.packageName;
16045        boolean deletedPkg = true;
16046        boolean addedPkg = false;
16047        boolean updatedSettings = false;
16048        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16049        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16050                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16051
16052        final long origUpdateTime = (pkg.mExtras != null)
16053                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16054
16055        // First delete the existing package while retaining the data directory
16056        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16057                res.removedInfo, true, pkg)) {
16058            // If the existing package wasn't successfully deleted
16059            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16060            deletedPkg = false;
16061        } else {
16062            // Successfully deleted the old package; proceed with replace.
16063
16064            // If deleted package lived in a container, give users a chance to
16065            // relinquish resources before killing.
16066            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16067                if (DEBUG_INSTALL) {
16068                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16069                }
16070                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16071                final ArrayList<String> pkgList = new ArrayList<String>(1);
16072                pkgList.add(deletedPackage.applicationInfo.packageName);
16073                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16074            }
16075
16076            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16077                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16078            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16079
16080            try {
16081                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16082                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16083                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16084                        installReason);
16085
16086                // Update the in-memory copy of the previous code paths.
16087                PackageSetting ps = mSettings.mPackages.get(pkgName);
16088                if (!killApp) {
16089                    if (ps.oldCodePaths == null) {
16090                        ps.oldCodePaths = new ArraySet<>();
16091                    }
16092                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16093                    if (deletedPackage.splitCodePaths != null) {
16094                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16095                    }
16096                } else {
16097                    ps.oldCodePaths = null;
16098                }
16099                if (ps.childPackageNames != null) {
16100                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16101                        final String childPkgName = ps.childPackageNames.get(i);
16102                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16103                        childPs.oldCodePaths = ps.oldCodePaths;
16104                    }
16105                }
16106                // set instant app status, but, only if it's explicitly specified
16107                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16108                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16109                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16110                prepareAppDataAfterInstallLIF(newPackage);
16111                addedPkg = true;
16112            } catch (PackageManagerException e) {
16113                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16114            }
16115        }
16116
16117        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16118            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16119
16120            // Revert all internal state mutations and added folders for the failed install
16121            if (addedPkg) {
16122                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16123                        res.removedInfo, true, null);
16124            }
16125
16126            // Restore the old package
16127            if (deletedPkg) {
16128                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16129                File restoreFile = new File(deletedPackage.codePath);
16130                // Parse old package
16131                boolean oldExternal = isExternal(deletedPackage);
16132                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16133                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16134                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16135                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16136                try {
16137                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16138                            null);
16139                } catch (PackageManagerException e) {
16140                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16141                            + e.getMessage());
16142                    return;
16143                }
16144
16145                synchronized (mPackages) {
16146                    // Ensure the installer package name up to date
16147                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16148
16149                    // Update permissions for restored package
16150                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16151
16152                    mSettings.writeLPr();
16153                }
16154
16155                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16156            }
16157        } else {
16158            synchronized (mPackages) {
16159                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16160                if (ps != null) {
16161                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16162                    if (res.removedInfo.removedChildPackages != null) {
16163                        final int childCount = res.removedInfo.removedChildPackages.size();
16164                        // Iterate in reverse as we may modify the collection
16165                        for (int i = childCount - 1; i >= 0; i--) {
16166                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16167                            if (res.addedChildPackages.containsKey(childPackageName)) {
16168                                res.removedInfo.removedChildPackages.removeAt(i);
16169                            } else {
16170                                PackageRemovedInfo childInfo = res.removedInfo
16171                                        .removedChildPackages.valueAt(i);
16172                                childInfo.removedForAllUsers = mPackages.get(
16173                                        childInfo.removedPackage) == null;
16174                            }
16175                        }
16176                    }
16177                }
16178            }
16179        }
16180    }
16181
16182    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16183            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16184            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16185            int installReason) {
16186        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16187                + ", old=" + deletedPackage);
16188
16189        final boolean disabledSystem;
16190
16191        // Remove existing system package
16192        removePackageLI(deletedPackage, true);
16193
16194        synchronized (mPackages) {
16195            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16196        }
16197        if (!disabledSystem) {
16198            // We didn't need to disable the .apk as a current system package,
16199            // which means we are replacing another update that is already
16200            // installed.  We need to make sure to delete the older one's .apk.
16201            res.removedInfo.args = createInstallArgsForExisting(0,
16202                    deletedPackage.applicationInfo.getCodePath(),
16203                    deletedPackage.applicationInfo.getResourcePath(),
16204                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16205        } else {
16206            res.removedInfo.args = null;
16207        }
16208
16209        // Successfully disabled the old package. Now proceed with re-installation
16210        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16211                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16212        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16213
16214        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16215        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16216                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16217
16218        PackageParser.Package newPackage = null;
16219        try {
16220            // Add the package to the internal data structures
16221            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16222
16223            // Set the update and install times
16224            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16225            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16226                    System.currentTimeMillis());
16227
16228            // Update the package dynamic state if succeeded
16229            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16230                // Now that the install succeeded make sure we remove data
16231                // directories for any child package the update removed.
16232                final int deletedChildCount = (deletedPackage.childPackages != null)
16233                        ? deletedPackage.childPackages.size() : 0;
16234                final int newChildCount = (newPackage.childPackages != null)
16235                        ? newPackage.childPackages.size() : 0;
16236                for (int i = 0; i < deletedChildCount; i++) {
16237                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16238                    boolean childPackageDeleted = true;
16239                    for (int j = 0; j < newChildCount; j++) {
16240                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16241                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16242                            childPackageDeleted = false;
16243                            break;
16244                        }
16245                    }
16246                    if (childPackageDeleted) {
16247                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16248                                deletedChildPkg.packageName);
16249                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16250                            PackageRemovedInfo removedChildRes = res.removedInfo
16251                                    .removedChildPackages.get(deletedChildPkg.packageName);
16252                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16253                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16254                        }
16255                    }
16256                }
16257
16258                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16259                        installReason);
16260                prepareAppDataAfterInstallLIF(newPackage);
16261            }
16262        } catch (PackageManagerException e) {
16263            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16264            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16265        }
16266
16267        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16268            // Re installation failed. Restore old information
16269            // Remove new pkg information
16270            if (newPackage != null) {
16271                removeInstalledPackageLI(newPackage, true);
16272            }
16273            // Add back the old system package
16274            try {
16275                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16276            } catch (PackageManagerException e) {
16277                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16278            }
16279
16280            synchronized (mPackages) {
16281                if (disabledSystem) {
16282                    enableSystemPackageLPw(deletedPackage);
16283                }
16284
16285                // Ensure the installer package name up to date
16286                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16287
16288                // Update permissions for restored package
16289                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16290
16291                mSettings.writeLPr();
16292            }
16293
16294            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16295                    + " after failed upgrade");
16296        }
16297    }
16298
16299    /**
16300     * Checks whether the parent or any of the child packages have a change shared
16301     * user. For a package to be a valid update the shred users of the parent and
16302     * the children should match. We may later support changing child shared users.
16303     * @param oldPkg The updated package.
16304     * @param newPkg The update package.
16305     * @return The shared user that change between the versions.
16306     */
16307    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16308            PackageParser.Package newPkg) {
16309        // Check parent shared user
16310        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16311            return newPkg.packageName;
16312        }
16313        // Check child shared users
16314        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16315        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16316        for (int i = 0; i < newChildCount; i++) {
16317            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16318            // If this child was present, did it have the same shared user?
16319            for (int j = 0; j < oldChildCount; j++) {
16320                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16321                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16322                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16323                    return newChildPkg.packageName;
16324                }
16325            }
16326        }
16327        return null;
16328    }
16329
16330    private void removeNativeBinariesLI(PackageSetting ps) {
16331        // Remove the lib path for the parent package
16332        if (ps != null) {
16333            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16334            // Remove the lib path for the child packages
16335            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16336            for (int i = 0; i < childCount; i++) {
16337                PackageSetting childPs = null;
16338                synchronized (mPackages) {
16339                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16340                }
16341                if (childPs != null) {
16342                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16343                            .legacyNativeLibraryPathString);
16344                }
16345            }
16346        }
16347    }
16348
16349    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16350        // Enable the parent package
16351        mSettings.enableSystemPackageLPw(pkg.packageName);
16352        // Enable the child packages
16353        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16354        for (int i = 0; i < childCount; i++) {
16355            PackageParser.Package childPkg = pkg.childPackages.get(i);
16356            mSettings.enableSystemPackageLPw(childPkg.packageName);
16357        }
16358    }
16359
16360    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16361            PackageParser.Package newPkg) {
16362        // Disable the parent package (parent always replaced)
16363        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16364        // Disable the child packages
16365        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16366        for (int i = 0; i < childCount; i++) {
16367            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16368            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16369            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16370        }
16371        return disabled;
16372    }
16373
16374    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16375            String installerPackageName) {
16376        // Enable the parent package
16377        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16378        // Enable the child packages
16379        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16380        for (int i = 0; i < childCount; i++) {
16381            PackageParser.Package childPkg = pkg.childPackages.get(i);
16382            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16383        }
16384    }
16385
16386    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16387        // Collect all used permissions in the UID
16388        ArraySet<String> usedPermissions = new ArraySet<>();
16389        final int packageCount = su.packages.size();
16390        for (int i = 0; i < packageCount; i++) {
16391            PackageSetting ps = su.packages.valueAt(i);
16392            if (ps.pkg == null) {
16393                continue;
16394            }
16395            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16396            for (int j = 0; j < requestedPermCount; j++) {
16397                String permission = ps.pkg.requestedPermissions.get(j);
16398                BasePermission bp = mSettings.mPermissions.get(permission);
16399                if (bp != null) {
16400                    usedPermissions.add(permission);
16401                }
16402            }
16403        }
16404
16405        PermissionsState permissionsState = su.getPermissionsState();
16406        // Prune install permissions
16407        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16408        final int installPermCount = installPermStates.size();
16409        for (int i = installPermCount - 1; i >= 0;  i--) {
16410            PermissionState permissionState = installPermStates.get(i);
16411            if (!usedPermissions.contains(permissionState.getName())) {
16412                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16413                if (bp != null) {
16414                    permissionsState.revokeInstallPermission(bp);
16415                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16416                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16417                }
16418            }
16419        }
16420
16421        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16422
16423        // Prune runtime permissions
16424        for (int userId : allUserIds) {
16425            List<PermissionState> runtimePermStates = permissionsState
16426                    .getRuntimePermissionStates(userId);
16427            final int runtimePermCount = runtimePermStates.size();
16428            for (int i = runtimePermCount - 1; i >= 0; i--) {
16429                PermissionState permissionState = runtimePermStates.get(i);
16430                if (!usedPermissions.contains(permissionState.getName())) {
16431                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16432                    if (bp != null) {
16433                        permissionsState.revokeRuntimePermission(bp, userId);
16434                        permissionsState.updatePermissionFlags(bp, userId,
16435                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16436                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16437                                runtimePermissionChangedUserIds, userId);
16438                    }
16439                }
16440            }
16441        }
16442
16443        return runtimePermissionChangedUserIds;
16444    }
16445
16446    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16447            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16448        // Update the parent package setting
16449        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16450                res, user, installReason);
16451        // Update the child packages setting
16452        final int childCount = (newPackage.childPackages != null)
16453                ? newPackage.childPackages.size() : 0;
16454        for (int i = 0; i < childCount; i++) {
16455            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16456            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16457            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16458                    childRes.origUsers, childRes, user, installReason);
16459        }
16460    }
16461
16462    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16463            String installerPackageName, int[] allUsers, int[] installedForUsers,
16464            PackageInstalledInfo res, UserHandle user, int installReason) {
16465        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16466
16467        String pkgName = newPackage.packageName;
16468        synchronized (mPackages) {
16469            //write settings. the installStatus will be incomplete at this stage.
16470            //note that the new package setting would have already been
16471            //added to mPackages. It hasn't been persisted yet.
16472            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16473            // TODO: Remove this write? It's also written at the end of this method
16474            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16475            mSettings.writeLPr();
16476            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16477        }
16478
16479        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16480        synchronized (mPackages) {
16481            updatePermissionsLPw(newPackage.packageName, newPackage,
16482                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16483                            ? UPDATE_PERMISSIONS_ALL : 0));
16484            // For system-bundled packages, we assume that installing an upgraded version
16485            // of the package implies that the user actually wants to run that new code,
16486            // so we enable the package.
16487            PackageSetting ps = mSettings.mPackages.get(pkgName);
16488            final int userId = user.getIdentifier();
16489            if (ps != null) {
16490                if (isSystemApp(newPackage)) {
16491                    if (DEBUG_INSTALL) {
16492                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16493                    }
16494                    // Enable system package for requested users
16495                    if (res.origUsers != null) {
16496                        for (int origUserId : res.origUsers) {
16497                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16498                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16499                                        origUserId, installerPackageName);
16500                            }
16501                        }
16502                    }
16503                    // Also convey the prior install/uninstall state
16504                    if (allUsers != null && installedForUsers != null) {
16505                        for (int currentUserId : allUsers) {
16506                            final boolean installed = ArrayUtils.contains(
16507                                    installedForUsers, currentUserId);
16508                            if (DEBUG_INSTALL) {
16509                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16510                            }
16511                            ps.setInstalled(installed, currentUserId);
16512                        }
16513                        // these install state changes will be persisted in the
16514                        // upcoming call to mSettings.writeLPr().
16515                    }
16516                }
16517                // It's implied that when a user requests installation, they want the app to be
16518                // installed and enabled.
16519                if (userId != UserHandle.USER_ALL) {
16520                    ps.setInstalled(true, userId);
16521                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16522                }
16523
16524                // When replacing an existing package, preserve the original install reason for all
16525                // users that had the package installed before.
16526                final Set<Integer> previousUserIds = new ArraySet<>();
16527                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16528                    final int installReasonCount = res.removedInfo.installReasons.size();
16529                    for (int i = 0; i < installReasonCount; i++) {
16530                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16531                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16532                        ps.setInstallReason(previousInstallReason, previousUserId);
16533                        previousUserIds.add(previousUserId);
16534                    }
16535                }
16536
16537                // Set install reason for users that are having the package newly installed.
16538                if (userId == UserHandle.USER_ALL) {
16539                    for (int currentUserId : sUserManager.getUserIds()) {
16540                        if (!previousUserIds.contains(currentUserId)) {
16541                            ps.setInstallReason(installReason, currentUserId);
16542                        }
16543                    }
16544                } else if (!previousUserIds.contains(userId)) {
16545                    ps.setInstallReason(installReason, userId);
16546                }
16547                mSettings.writeKernelMappingLPr(ps);
16548            }
16549            res.name = pkgName;
16550            res.uid = newPackage.applicationInfo.uid;
16551            res.pkg = newPackage;
16552            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16553            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16554            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16555            //to update install status
16556            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16557            mSettings.writeLPr();
16558            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16559        }
16560
16561        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16562    }
16563
16564    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16565        try {
16566            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16567            installPackageLI(args, res);
16568        } finally {
16569            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16570        }
16571    }
16572
16573    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16574        final int installFlags = args.installFlags;
16575        final String installerPackageName = args.installerPackageName;
16576        final String volumeUuid = args.volumeUuid;
16577        final File tmpPackageFile = new File(args.getCodePath());
16578        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16579        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16580                || (args.volumeUuid != null));
16581        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16582        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16583        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16584        boolean replace = false;
16585        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16586        if (args.move != null) {
16587            // moving a complete application; perform an initial scan on the new install location
16588            scanFlags |= SCAN_INITIAL;
16589        }
16590        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16591            scanFlags |= SCAN_DONT_KILL_APP;
16592        }
16593        if (instantApp) {
16594            scanFlags |= SCAN_AS_INSTANT_APP;
16595        }
16596        if (fullApp) {
16597            scanFlags |= SCAN_AS_FULL_APP;
16598        }
16599
16600        // Result object to be returned
16601        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16602
16603        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16604
16605        // Sanity check
16606        if (instantApp && (forwardLocked || onExternal)) {
16607            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16608                    + " external=" + onExternal);
16609            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16610            return;
16611        }
16612
16613        // Retrieve PackageSettings and parse package
16614        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16615                | PackageParser.PARSE_ENFORCE_CODE
16616                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16617                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16618                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16619                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16620        PackageParser pp = new PackageParser();
16621        pp.setSeparateProcesses(mSeparateProcesses);
16622        pp.setDisplayMetrics(mMetrics);
16623
16624        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16625        final PackageParser.Package pkg;
16626        try {
16627            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16628        } catch (PackageParserException e) {
16629            res.setError("Failed parse during installPackageLI", e);
16630            return;
16631        } finally {
16632            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16633        }
16634
16635//        // Ephemeral apps must have target SDK >= O.
16636//        // TODO: Update conditional and error message when O gets locked down
16637//        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16638//            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
16639//                    "Ephemeral apps must have target SDK version of at least O");
16640//            return;
16641//        }
16642
16643        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16644            // Static shared libraries have synthetic package names
16645            renameStaticSharedLibraryPackage(pkg);
16646
16647            // No static shared libs on external storage
16648            if (onExternal) {
16649                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16650                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16651                        "Packages declaring static-shared libs cannot be updated");
16652                return;
16653            }
16654        }
16655
16656        // If we are installing a clustered package add results for the children
16657        if (pkg.childPackages != null) {
16658            synchronized (mPackages) {
16659                final int childCount = pkg.childPackages.size();
16660                for (int i = 0; i < childCount; i++) {
16661                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16662                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16663                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16664                    childRes.pkg = childPkg;
16665                    childRes.name = childPkg.packageName;
16666                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16667                    if (childPs != null) {
16668                        childRes.origUsers = childPs.queryInstalledUsers(
16669                                sUserManager.getUserIds(), true);
16670                    }
16671                    if ((mPackages.containsKey(childPkg.packageName))) {
16672                        childRes.removedInfo = new PackageRemovedInfo();
16673                        childRes.removedInfo.removedPackage = childPkg.packageName;
16674                    }
16675                    if (res.addedChildPackages == null) {
16676                        res.addedChildPackages = new ArrayMap<>();
16677                    }
16678                    res.addedChildPackages.put(childPkg.packageName, childRes);
16679                }
16680            }
16681        }
16682
16683        // If package doesn't declare API override, mark that we have an install
16684        // time CPU ABI override.
16685        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16686            pkg.cpuAbiOverride = args.abiOverride;
16687        }
16688
16689        String pkgName = res.name = pkg.packageName;
16690        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16691            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16692                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16693                return;
16694            }
16695        }
16696
16697        try {
16698            // either use what we've been given or parse directly from the APK
16699            if (args.certificates != null) {
16700                try {
16701                    PackageParser.populateCertificates(pkg, args.certificates);
16702                } catch (PackageParserException e) {
16703                    // there was something wrong with the certificates we were given;
16704                    // try to pull them from the APK
16705                    PackageParser.collectCertificates(pkg, parseFlags);
16706                }
16707            } else {
16708                PackageParser.collectCertificates(pkg, parseFlags);
16709            }
16710        } catch (PackageParserException e) {
16711            res.setError("Failed collect during installPackageLI", e);
16712            return;
16713        }
16714
16715        // Get rid of all references to package scan path via parser.
16716        pp = null;
16717        String oldCodePath = null;
16718        boolean systemApp = false;
16719        synchronized (mPackages) {
16720            // Check if installing already existing package
16721            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16722                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16723                if (pkg.mOriginalPackages != null
16724                        && pkg.mOriginalPackages.contains(oldName)
16725                        && mPackages.containsKey(oldName)) {
16726                    // This package is derived from an original package,
16727                    // and this device has been updating from that original
16728                    // name.  We must continue using the original name, so
16729                    // rename the new package here.
16730                    pkg.setPackageName(oldName);
16731                    pkgName = pkg.packageName;
16732                    replace = true;
16733                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16734                            + oldName + " pkgName=" + pkgName);
16735                } else if (mPackages.containsKey(pkgName)) {
16736                    // This package, under its official name, already exists
16737                    // on the device; we should replace it.
16738                    replace = true;
16739                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16740                }
16741
16742                // Child packages are installed through the parent package
16743                if (pkg.parentPackage != null) {
16744                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16745                            "Package " + pkg.packageName + " is child of package "
16746                                    + pkg.parentPackage.parentPackage + ". Child packages "
16747                                    + "can be updated only through the parent package.");
16748                    return;
16749                }
16750
16751                if (replace) {
16752                    // Prevent apps opting out from runtime permissions
16753                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16754                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16755                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16756                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16757                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16758                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16759                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16760                                        + " doesn't support runtime permissions but the old"
16761                                        + " target SDK " + oldTargetSdk + " does.");
16762                        return;
16763                    }
16764
16765                    // Prevent installing of child packages
16766                    if (oldPackage.parentPackage != null) {
16767                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16768                                "Package " + pkg.packageName + " is child of package "
16769                                        + oldPackage.parentPackage + ". Child packages "
16770                                        + "can be updated only through the parent package.");
16771                        return;
16772                    }
16773                }
16774            }
16775
16776            PackageSetting ps = mSettings.mPackages.get(pkgName);
16777            if (ps != null) {
16778                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16779
16780                // Static shared libs have same package with different versions where
16781                // we internally use a synthetic package name to allow multiple versions
16782                // of the same package, therefore we need to compare signatures against
16783                // the package setting for the latest library version.
16784                PackageSetting signatureCheckPs = ps;
16785                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16786                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16787                    if (libraryEntry != null) {
16788                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16789                    }
16790                }
16791
16792                // Quick sanity check that we're signed correctly if updating;
16793                // we'll check this again later when scanning, but we want to
16794                // bail early here before tripping over redefined permissions.
16795                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16796                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16797                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16798                                + pkg.packageName + " upgrade keys do not match the "
16799                                + "previously installed version");
16800                        return;
16801                    }
16802                } else {
16803                    try {
16804                        verifySignaturesLP(signatureCheckPs, pkg);
16805                    } catch (PackageManagerException e) {
16806                        res.setError(e.error, e.getMessage());
16807                        return;
16808                    }
16809                }
16810
16811                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16812                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16813                    systemApp = (ps.pkg.applicationInfo.flags &
16814                            ApplicationInfo.FLAG_SYSTEM) != 0;
16815                }
16816                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16817            }
16818
16819            // Check whether the newly-scanned package wants to define an already-defined perm
16820            int N = pkg.permissions.size();
16821            for (int i = N-1; i >= 0; i--) {
16822                PackageParser.Permission perm = pkg.permissions.get(i);
16823                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16824                if (bp != null) {
16825                    // If the defining package is signed with our cert, it's okay.  This
16826                    // also includes the "updating the same package" case, of course.
16827                    // "updating same package" could also involve key-rotation.
16828                    final boolean sigsOk;
16829                    if (bp.sourcePackage.equals(pkg.packageName)
16830                            && (bp.packageSetting instanceof PackageSetting)
16831                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16832                                    scanFlags))) {
16833                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16834                    } else {
16835                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16836                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16837                    }
16838                    if (!sigsOk) {
16839                        // If the owning package is the system itself, we log but allow
16840                        // install to proceed; we fail the install on all other permission
16841                        // redefinitions.
16842                        if (!bp.sourcePackage.equals("android")) {
16843                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16844                                    + pkg.packageName + " attempting to redeclare permission "
16845                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16846                            res.origPermission = perm.info.name;
16847                            res.origPackage = bp.sourcePackage;
16848                            return;
16849                        } else {
16850                            Slog.w(TAG, "Package " + pkg.packageName
16851                                    + " attempting to redeclare system permission "
16852                                    + perm.info.name + "; ignoring new declaration");
16853                            pkg.permissions.remove(i);
16854                        }
16855                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16856                        // Prevent apps to change protection level to dangerous from any other
16857                        // type as this would allow a privilege escalation where an app adds a
16858                        // normal/signature permission in other app's group and later redefines
16859                        // it as dangerous leading to the group auto-grant.
16860                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16861                                == PermissionInfo.PROTECTION_DANGEROUS) {
16862                            if (bp != null && !bp.isRuntime()) {
16863                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16864                                        + "non-runtime permission " + perm.info.name
16865                                        + " to runtime; keeping old protection level");
16866                                perm.info.protectionLevel = bp.protectionLevel;
16867                            }
16868                        }
16869                    }
16870                }
16871            }
16872        }
16873
16874        if (systemApp) {
16875            if (onExternal) {
16876                // Abort update; system app can't be replaced with app on sdcard
16877                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16878                        "Cannot install updates to system apps on sdcard");
16879                return;
16880            } else if (instantApp) {
16881                // Abort update; system app can't be replaced with an instant app
16882                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16883                        "Cannot update a system app with an instant app");
16884                return;
16885            }
16886        }
16887
16888        if (args.move != null) {
16889            // We did an in-place move, so dex is ready to roll
16890            scanFlags |= SCAN_NO_DEX;
16891            scanFlags |= SCAN_MOVE;
16892
16893            synchronized (mPackages) {
16894                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16895                if (ps == null) {
16896                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16897                            "Missing settings for moved package " + pkgName);
16898                }
16899
16900                // We moved the entire application as-is, so bring over the
16901                // previously derived ABI information.
16902                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16903                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16904            }
16905
16906        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16907            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16908            scanFlags |= SCAN_NO_DEX;
16909
16910            try {
16911                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16912                    args.abiOverride : pkg.cpuAbiOverride);
16913                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16914                        true /*extractLibs*/, mAppLib32InstallDir);
16915            } catch (PackageManagerException pme) {
16916                Slog.e(TAG, "Error deriving application ABI", pme);
16917                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16918                return;
16919            }
16920
16921            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16922            // Do not run PackageDexOptimizer through the local performDexOpt
16923            // method because `pkg` may not be in `mPackages` yet.
16924            //
16925            // Also, don't fail application installs if the dexopt step fails.
16926            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16927                    null /* instructionSets */, false /* checkProfiles */,
16928                    getCompilerFilterForReason(REASON_INSTALL),
16929                    getOrCreateCompilerPackageStats(pkg));
16930            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16931
16932            // Notify BackgroundDexOptJobService that the package has been changed.
16933            // If this is an update of a package which used to fail to compile,
16934            // BDOS will remove it from its blacklist.
16935            // TODO: Layering violation
16936            BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName);
16937        }
16938
16939        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16940            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16941            return;
16942        }
16943
16944        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16945
16946        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16947                "installPackageLI")) {
16948            if (replace) {
16949                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16950                    // Static libs have a synthetic package name containing the version
16951                    // and cannot be updated as an update would get a new package name,
16952                    // unless this is the exact same version code which is useful for
16953                    // development.
16954                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16955                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16956                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16957                                + "static-shared libs cannot be updated");
16958                        return;
16959                    }
16960                }
16961                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16962                        installerPackageName, res, args.installReason);
16963            } else {
16964                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16965                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16966            }
16967        }
16968        synchronized (mPackages) {
16969            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16970            if (ps != null) {
16971                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16972            }
16973
16974            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16975            for (int i = 0; i < childCount; i++) {
16976                PackageParser.Package childPkg = pkg.childPackages.get(i);
16977                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16978                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16979                if (childPs != null) {
16980                    childRes.newUsers = childPs.queryInstalledUsers(
16981                            sUserManager.getUserIds(), true);
16982                }
16983            }
16984
16985            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16986                updateSequenceNumberLP(pkgName, res.newUsers);
16987            }
16988        }
16989    }
16990
16991    private void startIntentFilterVerifications(int userId, boolean replacing,
16992            PackageParser.Package pkg) {
16993        if (mIntentFilterVerifierComponent == null) {
16994            Slog.w(TAG, "No IntentFilter verification will not be done as "
16995                    + "there is no IntentFilterVerifier available!");
16996            return;
16997        }
16998
16999        final int verifierUid = getPackageUid(
17000                mIntentFilterVerifierComponent.getPackageName(),
17001                MATCH_DEBUG_TRIAGED_MISSING,
17002                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17003
17004        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17005        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17006        mHandler.sendMessage(msg);
17007
17008        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17009        for (int i = 0; i < childCount; i++) {
17010            PackageParser.Package childPkg = pkg.childPackages.get(i);
17011            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17012            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17013            mHandler.sendMessage(msg);
17014        }
17015    }
17016
17017    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17018            PackageParser.Package pkg) {
17019        int size = pkg.activities.size();
17020        if (size == 0) {
17021            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17022                    "No activity, so no need to verify any IntentFilter!");
17023            return;
17024        }
17025
17026        final boolean hasDomainURLs = hasDomainURLs(pkg);
17027        if (!hasDomainURLs) {
17028            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17029                    "No domain URLs, so no need to verify any IntentFilter!");
17030            return;
17031        }
17032
17033        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17034                + " if any IntentFilter from the " + size
17035                + " Activities needs verification ...");
17036
17037        int count = 0;
17038        final String packageName = pkg.packageName;
17039
17040        synchronized (mPackages) {
17041            // If this is a new install and we see that we've already run verification for this
17042            // package, we have nothing to do: it means the state was restored from backup.
17043            if (!replacing) {
17044                IntentFilterVerificationInfo ivi =
17045                        mSettings.getIntentFilterVerificationLPr(packageName);
17046                if (ivi != null) {
17047                    if (DEBUG_DOMAIN_VERIFICATION) {
17048                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17049                                + ivi.getStatusString());
17050                    }
17051                    return;
17052                }
17053            }
17054
17055            // If any filters need to be verified, then all need to be.
17056            boolean needToVerify = false;
17057            for (PackageParser.Activity a : pkg.activities) {
17058                for (ActivityIntentInfo filter : a.intents) {
17059                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17060                        if (DEBUG_DOMAIN_VERIFICATION) {
17061                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17062                        }
17063                        needToVerify = true;
17064                        break;
17065                    }
17066                }
17067            }
17068
17069            if (needToVerify) {
17070                final int verificationId = mIntentFilterVerificationToken++;
17071                for (PackageParser.Activity a : pkg.activities) {
17072                    for (ActivityIntentInfo filter : a.intents) {
17073                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17074                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17075                                    "Verification needed for IntentFilter:" + filter.toString());
17076                            mIntentFilterVerifier.addOneIntentFilterVerification(
17077                                    verifierUid, userId, verificationId, filter, packageName);
17078                            count++;
17079                        }
17080                    }
17081                }
17082            }
17083        }
17084
17085        if (count > 0) {
17086            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17087                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17088                    +  " for userId:" + userId);
17089            mIntentFilterVerifier.startVerifications(userId);
17090        } else {
17091            if (DEBUG_DOMAIN_VERIFICATION) {
17092                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17093            }
17094        }
17095    }
17096
17097    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17098        final ComponentName cn  = filter.activity.getComponentName();
17099        final String packageName = cn.getPackageName();
17100
17101        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17102                packageName);
17103        if (ivi == null) {
17104            return true;
17105        }
17106        int status = ivi.getStatus();
17107        switch (status) {
17108            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17109            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17110                return true;
17111
17112            default:
17113                // Nothing to do
17114                return false;
17115        }
17116    }
17117
17118    private static boolean isMultiArch(ApplicationInfo info) {
17119        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17120    }
17121
17122    private static boolean isExternal(PackageParser.Package pkg) {
17123        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17124    }
17125
17126    private static boolean isExternal(PackageSetting ps) {
17127        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17128    }
17129
17130    private static boolean isSystemApp(PackageParser.Package pkg) {
17131        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17132    }
17133
17134    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17135        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17136    }
17137
17138    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17139        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17140    }
17141
17142    private static boolean isSystemApp(PackageSetting ps) {
17143        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17144    }
17145
17146    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17147        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17148    }
17149
17150    private int packageFlagsToInstallFlags(PackageSetting ps) {
17151        int installFlags = 0;
17152        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17153            // This existing package was an external ASEC install when we have
17154            // the external flag without a UUID
17155            installFlags |= PackageManager.INSTALL_EXTERNAL;
17156        }
17157        if (ps.isForwardLocked()) {
17158            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17159        }
17160        return installFlags;
17161    }
17162
17163    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17164        if (isExternal(pkg)) {
17165            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17166                return StorageManager.UUID_PRIMARY_PHYSICAL;
17167            } else {
17168                return pkg.volumeUuid;
17169            }
17170        } else {
17171            return StorageManager.UUID_PRIVATE_INTERNAL;
17172        }
17173    }
17174
17175    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17176        if (isExternal(pkg)) {
17177            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17178                return mSettings.getExternalVersion();
17179            } else {
17180                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17181            }
17182        } else {
17183            return mSettings.getInternalVersion();
17184        }
17185    }
17186
17187    private void deleteTempPackageFiles() {
17188        final FilenameFilter filter = new FilenameFilter() {
17189            public boolean accept(File dir, String name) {
17190                return name.startsWith("vmdl") && name.endsWith(".tmp");
17191            }
17192        };
17193        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17194            file.delete();
17195        }
17196    }
17197
17198    @Override
17199    public void deletePackageAsUser(String packageName, int versionCode,
17200            IPackageDeleteObserver observer, int userId, int flags) {
17201        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17202                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17203    }
17204
17205    @Override
17206    public void deletePackageVersioned(VersionedPackage versionedPackage,
17207            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17208        mContext.enforceCallingOrSelfPermission(
17209                android.Manifest.permission.DELETE_PACKAGES, null);
17210        Preconditions.checkNotNull(versionedPackage);
17211        Preconditions.checkNotNull(observer);
17212        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17213                PackageManager.VERSION_CODE_HIGHEST,
17214                Integer.MAX_VALUE, "versionCode must be >= -1");
17215
17216        final String packageName = versionedPackage.getPackageName();
17217        // TODO: We will change version code to long, so in the new API it is long
17218        final int versionCode = (int) versionedPackage.getVersionCode();
17219        final String internalPackageName;
17220        synchronized (mPackages) {
17221            // Normalize package name to handle renamed packages and static libs
17222            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17223                    // TODO: We will change version code to long, so in the new API it is long
17224                    (int) versionedPackage.getVersionCode());
17225        }
17226
17227        final int uid = Binder.getCallingUid();
17228        if (!isOrphaned(internalPackageName)
17229                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17230            try {
17231                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17232                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17233                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17234                observer.onUserActionRequired(intent);
17235            } catch (RemoteException re) {
17236            }
17237            return;
17238        }
17239        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17240        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17241        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17242            mContext.enforceCallingOrSelfPermission(
17243                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17244                    "deletePackage for user " + userId);
17245        }
17246
17247        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17248            try {
17249                observer.onPackageDeleted(packageName,
17250                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17251            } catch (RemoteException re) {
17252            }
17253            return;
17254        }
17255
17256        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17257            try {
17258                observer.onPackageDeleted(packageName,
17259                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17260            } catch (RemoteException re) {
17261            }
17262            return;
17263        }
17264
17265        if (DEBUG_REMOVE) {
17266            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17267                    + " deleteAllUsers: " + deleteAllUsers + " version="
17268                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17269                    ? "VERSION_CODE_HIGHEST" : versionCode));
17270        }
17271        // Queue up an async operation since the package deletion may take a little while.
17272        mHandler.post(new Runnable() {
17273            public void run() {
17274                mHandler.removeCallbacks(this);
17275                int returnCode;
17276                if (!deleteAllUsers) {
17277                    returnCode = deletePackageX(internalPackageName, versionCode,
17278                            userId, deleteFlags);
17279                } else {
17280                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17281                            internalPackageName, users);
17282                    // If nobody is blocking uninstall, proceed with delete for all users
17283                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17284                        returnCode = deletePackageX(internalPackageName, versionCode,
17285                                userId, deleteFlags);
17286                    } else {
17287                        // Otherwise uninstall individually for users with blockUninstalls=false
17288                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17289                        for (int userId : users) {
17290                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17291                                returnCode = deletePackageX(internalPackageName, versionCode,
17292                                        userId, userFlags);
17293                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17294                                    Slog.w(TAG, "Package delete failed for user " + userId
17295                                            + ", returnCode " + returnCode);
17296                                }
17297                            }
17298                        }
17299                        // The app has only been marked uninstalled for certain users.
17300                        // We still need to report that delete was blocked
17301                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17302                    }
17303                }
17304                try {
17305                    observer.onPackageDeleted(packageName, returnCode, null);
17306                } catch (RemoteException e) {
17307                    Log.i(TAG, "Observer no longer exists.");
17308                } //end catch
17309            } //end run
17310        });
17311    }
17312
17313    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17314        if (pkg.staticSharedLibName != null) {
17315            return pkg.manifestPackageName;
17316        }
17317        return pkg.packageName;
17318    }
17319
17320    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17321        // Handle renamed packages
17322        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17323        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17324
17325        // Is this a static library?
17326        SparseArray<SharedLibraryEntry> versionedLib =
17327                mStaticLibsByDeclaringPackage.get(packageName);
17328        if (versionedLib == null || versionedLib.size() <= 0) {
17329            return packageName;
17330        }
17331
17332        // Figure out which lib versions the caller can see
17333        SparseIntArray versionsCallerCanSee = null;
17334        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17335        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17336                && callingAppId != Process.ROOT_UID) {
17337            versionsCallerCanSee = new SparseIntArray();
17338            String libName = versionedLib.valueAt(0).info.getName();
17339            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17340            if (uidPackages != null) {
17341                for (String uidPackage : uidPackages) {
17342                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17343                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17344                    if (libIdx >= 0) {
17345                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17346                        versionsCallerCanSee.append(libVersion, libVersion);
17347                    }
17348                }
17349            }
17350        }
17351
17352        // Caller can see nothing - done
17353        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17354            return packageName;
17355        }
17356
17357        // Find the version the caller can see and the app version code
17358        SharedLibraryEntry highestVersion = null;
17359        final int versionCount = versionedLib.size();
17360        for (int i = 0; i < versionCount; i++) {
17361            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17362            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17363                    libEntry.info.getVersion()) < 0) {
17364                continue;
17365            }
17366            // TODO: We will change version code to long, so in the new API it is long
17367            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17368            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17369                if (libVersionCode == versionCode) {
17370                    return libEntry.apk;
17371                }
17372            } else if (highestVersion == null) {
17373                highestVersion = libEntry;
17374            } else if (libVersionCode  > highestVersion.info
17375                    .getDeclaringPackage().getVersionCode()) {
17376                highestVersion = libEntry;
17377            }
17378        }
17379
17380        if (highestVersion != null) {
17381            return highestVersion.apk;
17382        }
17383
17384        return packageName;
17385    }
17386
17387    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17388        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17389              || callingUid == Process.SYSTEM_UID) {
17390            return true;
17391        }
17392        final int callingUserId = UserHandle.getUserId(callingUid);
17393        // If the caller installed the pkgName, then allow it to silently uninstall.
17394        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17395            return true;
17396        }
17397
17398        // Allow package verifier to silently uninstall.
17399        if (mRequiredVerifierPackage != null &&
17400                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17401            return true;
17402        }
17403
17404        // Allow package uninstaller to silently uninstall.
17405        if (mRequiredUninstallerPackage != null &&
17406                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17407            return true;
17408        }
17409
17410        // Allow storage manager to silently uninstall.
17411        if (mStorageManagerPackage != null &&
17412                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17413            return true;
17414        }
17415        return false;
17416    }
17417
17418    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17419        int[] result = EMPTY_INT_ARRAY;
17420        for (int userId : userIds) {
17421            if (getBlockUninstallForUser(packageName, userId)) {
17422                result = ArrayUtils.appendInt(result, userId);
17423            }
17424        }
17425        return result;
17426    }
17427
17428    @Override
17429    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17430        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17431    }
17432
17433    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17434        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17435                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17436        try {
17437            if (dpm != null) {
17438                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17439                        /* callingUserOnly =*/ false);
17440                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17441                        : deviceOwnerComponentName.getPackageName();
17442                // Does the package contains the device owner?
17443                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17444                // this check is probably not needed, since DO should be registered as a device
17445                // admin on some user too. (Original bug for this: b/17657954)
17446                if (packageName.equals(deviceOwnerPackageName)) {
17447                    return true;
17448                }
17449                // Does it contain a device admin for any user?
17450                int[] users;
17451                if (userId == UserHandle.USER_ALL) {
17452                    users = sUserManager.getUserIds();
17453                } else {
17454                    users = new int[]{userId};
17455                }
17456                for (int i = 0; i < users.length; ++i) {
17457                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17458                        return true;
17459                    }
17460                }
17461            }
17462        } catch (RemoteException e) {
17463        }
17464        return false;
17465    }
17466
17467    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17468        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17469    }
17470
17471    /**
17472     *  This method is an internal method that could be get invoked either
17473     *  to delete an installed package or to clean up a failed installation.
17474     *  After deleting an installed package, a broadcast is sent to notify any
17475     *  listeners that the package has been removed. For cleaning up a failed
17476     *  installation, the broadcast is not necessary since the package's
17477     *  installation wouldn't have sent the initial broadcast either
17478     *  The key steps in deleting a package are
17479     *  deleting the package information in internal structures like mPackages,
17480     *  deleting the packages base directories through installd
17481     *  updating mSettings to reflect current status
17482     *  persisting settings for later use
17483     *  sending a broadcast if necessary
17484     */
17485    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17486        final PackageRemovedInfo info = new PackageRemovedInfo();
17487        final boolean res;
17488
17489        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17490                ? UserHandle.USER_ALL : userId;
17491
17492        if (isPackageDeviceAdmin(packageName, removeUser)) {
17493            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17494            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17495        }
17496
17497        PackageSetting uninstalledPs = null;
17498
17499        // for the uninstall-updates case and restricted profiles, remember the per-
17500        // user handle installed state
17501        int[] allUsers;
17502        synchronized (mPackages) {
17503            uninstalledPs = mSettings.mPackages.get(packageName);
17504            if (uninstalledPs == null) {
17505                Slog.w(TAG, "Not removing non-existent package " + packageName);
17506                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17507            }
17508
17509            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17510                    && uninstalledPs.versionCode != versionCode) {
17511                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17512                        + uninstalledPs.versionCode + " != " + versionCode);
17513                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17514            }
17515
17516            // Static shared libs can be declared by any package, so let us not
17517            // allow removing a package if it provides a lib others depend on.
17518            PackageParser.Package pkg = mPackages.get(packageName);
17519            if (pkg != null && pkg.staticSharedLibName != null) {
17520                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17521                        pkg.staticSharedLibVersion);
17522                if (libEntry != null) {
17523                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17524                            libEntry.info, 0, userId);
17525                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17526                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17527                                + " hosting lib " + libEntry.info.getName() + " version "
17528                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17529                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17530                    }
17531                }
17532            }
17533
17534            allUsers = sUserManager.getUserIds();
17535            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17536        }
17537
17538        final int freezeUser;
17539        if (isUpdatedSystemApp(uninstalledPs)
17540                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17541            // We're downgrading a system app, which will apply to all users, so
17542            // freeze them all during the downgrade
17543            freezeUser = UserHandle.USER_ALL;
17544        } else {
17545            freezeUser = removeUser;
17546        }
17547
17548        synchronized (mInstallLock) {
17549            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17550            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17551                    deleteFlags, "deletePackageX")) {
17552                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17553                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17554            }
17555            synchronized (mPackages) {
17556                if (res) {
17557                    mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg,
17558                            info.removedUsers);
17559                    updateSequenceNumberLP(packageName, info.removedUsers);
17560                }
17561            }
17562        }
17563
17564        if (res) {
17565            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17566            info.sendPackageRemovedBroadcasts(killApp);
17567            info.sendSystemPackageUpdatedBroadcasts();
17568            info.sendSystemPackageAppearedBroadcasts();
17569        }
17570        // Force a gc here.
17571        Runtime.getRuntime().gc();
17572        // Delete the resources here after sending the broadcast to let
17573        // other processes clean up before deleting resources.
17574        if (info.args != null) {
17575            synchronized (mInstallLock) {
17576                info.args.doPostDeleteLI(true);
17577            }
17578        }
17579
17580        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17581    }
17582
17583    class PackageRemovedInfo {
17584        String removedPackage;
17585        int uid = -1;
17586        int removedAppId = -1;
17587        int[] origUsers;
17588        int[] removedUsers = null;
17589        SparseArray<Integer> installReasons;
17590        boolean isRemovedPackageSystemUpdate = false;
17591        boolean isUpdate;
17592        boolean dataRemoved;
17593        boolean removedForAllUsers;
17594        boolean isStaticSharedLib;
17595        // Clean up resources deleted packages.
17596        InstallArgs args = null;
17597        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17598        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17599
17600        void sendPackageRemovedBroadcasts(boolean killApp) {
17601            sendPackageRemovedBroadcastInternal(killApp);
17602            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17603            for (int i = 0; i < childCount; i++) {
17604                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17605                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17606            }
17607        }
17608
17609        void sendSystemPackageUpdatedBroadcasts() {
17610            if (isRemovedPackageSystemUpdate) {
17611                sendSystemPackageUpdatedBroadcastsInternal();
17612                final int childCount = (removedChildPackages != null)
17613                        ? removedChildPackages.size() : 0;
17614                for (int i = 0; i < childCount; i++) {
17615                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17616                    if (childInfo.isRemovedPackageSystemUpdate) {
17617                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17618                    }
17619                }
17620            }
17621        }
17622
17623        void sendSystemPackageAppearedBroadcasts() {
17624            final int packageCount = (appearedChildPackages != null)
17625                    ? appearedChildPackages.size() : 0;
17626            for (int i = 0; i < packageCount; i++) {
17627                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17628                sendPackageAddedForNewUsers(installedInfo.name, true,
17629                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17630            }
17631        }
17632
17633        private void sendSystemPackageUpdatedBroadcastsInternal() {
17634            Bundle extras = new Bundle(2);
17635            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17636            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17637            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17638                    extras, 0, null, null, null);
17639            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17640                    extras, 0, null, null, null);
17641            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17642                    null, 0, removedPackage, null, null);
17643        }
17644
17645        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17646            // Don't send static shared library removal broadcasts as these
17647            // libs are visible only the the apps that depend on them an one
17648            // cannot remove the library if it has a dependency.
17649            if (isStaticSharedLib) {
17650                return;
17651            }
17652            Bundle extras = new Bundle(2);
17653            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17654            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17655            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17656            if (isUpdate || isRemovedPackageSystemUpdate) {
17657                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17658            }
17659            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17660            if (removedPackage != null) {
17661                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17662                        extras, 0, null, null, removedUsers);
17663                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17664                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17665                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17666                            null, null, removedUsers);
17667                }
17668            }
17669            if (removedAppId >= 0) {
17670                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17671                        removedUsers);
17672            }
17673        }
17674    }
17675
17676    /*
17677     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17678     * flag is not set, the data directory is removed as well.
17679     * make sure this flag is set for partially installed apps. If not its meaningless to
17680     * delete a partially installed application.
17681     */
17682    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17683            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17684        String packageName = ps.name;
17685        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17686        // Retrieve object to delete permissions for shared user later on
17687        final PackageParser.Package deletedPkg;
17688        final PackageSetting deletedPs;
17689        // reader
17690        synchronized (mPackages) {
17691            deletedPkg = mPackages.get(packageName);
17692            deletedPs = mSettings.mPackages.get(packageName);
17693            if (outInfo != null) {
17694                outInfo.removedPackage = packageName;
17695                outInfo.isStaticSharedLib = deletedPkg != null
17696                        && deletedPkg.staticSharedLibName != null;
17697                outInfo.removedUsers = deletedPs != null
17698                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17699                        : null;
17700            }
17701        }
17702
17703        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17704
17705        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17706            final PackageParser.Package resolvedPkg;
17707            if (deletedPkg != null) {
17708                resolvedPkg = deletedPkg;
17709            } else {
17710                // We don't have a parsed package when it lives on an ejected
17711                // adopted storage device, so fake something together
17712                resolvedPkg = new PackageParser.Package(ps.name);
17713                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17714            }
17715            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17716                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17717            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17718            if (outInfo != null) {
17719                outInfo.dataRemoved = true;
17720            }
17721            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17722        }
17723
17724        int removedAppId = -1;
17725
17726        // writer
17727        synchronized (mPackages) {
17728            boolean installedStateChanged = false;
17729            if (deletedPs != null) {
17730                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17731                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17732                    clearDefaultBrowserIfNeeded(packageName);
17733                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17734                    removedAppId = mSettings.removePackageLPw(packageName);
17735                    if (outInfo != null) {
17736                        outInfo.removedAppId = removedAppId;
17737                    }
17738                    updatePermissionsLPw(deletedPs.name, null, 0);
17739                    if (deletedPs.sharedUser != null) {
17740                        // Remove permissions associated with package. Since runtime
17741                        // permissions are per user we have to kill the removed package
17742                        // or packages running under the shared user of the removed
17743                        // package if revoking the permissions requested only by the removed
17744                        // package is successful and this causes a change in gids.
17745                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17746                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17747                                    userId);
17748                            if (userIdToKill == UserHandle.USER_ALL
17749                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17750                                // If gids changed for this user, kill all affected packages.
17751                                mHandler.post(new Runnable() {
17752                                    @Override
17753                                    public void run() {
17754                                        // This has to happen with no lock held.
17755                                        killApplication(deletedPs.name, deletedPs.appId,
17756                                                KILL_APP_REASON_GIDS_CHANGED);
17757                                    }
17758                                });
17759                                break;
17760                            }
17761                        }
17762                    }
17763                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17764                }
17765                // make sure to preserve per-user disabled state if this removal was just
17766                // a downgrade of a system app to the factory package
17767                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17768                    if (DEBUG_REMOVE) {
17769                        Slog.d(TAG, "Propagating install state across downgrade");
17770                    }
17771                    for (int userId : allUserHandles) {
17772                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17773                        if (DEBUG_REMOVE) {
17774                            Slog.d(TAG, "    user " + userId + " => " + installed);
17775                        }
17776                        if (installed != ps.getInstalled(userId)) {
17777                            installedStateChanged = true;
17778                        }
17779                        ps.setInstalled(installed, userId);
17780                    }
17781                }
17782            }
17783            // can downgrade to reader
17784            if (writeSettings) {
17785                // Save settings now
17786                mSettings.writeLPr();
17787            }
17788            if (installedStateChanged) {
17789                mSettings.writeKernelMappingLPr(ps);
17790            }
17791        }
17792        if (removedAppId != -1) {
17793            // A user ID was deleted here. Go through all users and remove it
17794            // from KeyStore.
17795            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17796        }
17797    }
17798
17799    static boolean locationIsPrivileged(File path) {
17800        try {
17801            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17802                    .getCanonicalPath();
17803            return path.getCanonicalPath().startsWith(privilegedAppDir);
17804        } catch (IOException e) {
17805            Slog.e(TAG, "Unable to access code path " + path);
17806        }
17807        return false;
17808    }
17809
17810    /*
17811     * Tries to delete system package.
17812     */
17813    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17814            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17815            boolean writeSettings) {
17816        if (deletedPs.parentPackageName != null) {
17817            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17818            return false;
17819        }
17820
17821        final boolean applyUserRestrictions
17822                = (allUserHandles != null) && (outInfo.origUsers != null);
17823        final PackageSetting disabledPs;
17824        // Confirm if the system package has been updated
17825        // An updated system app can be deleted. This will also have to restore
17826        // the system pkg from system partition
17827        // reader
17828        synchronized (mPackages) {
17829            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17830        }
17831
17832        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17833                + " disabledPs=" + disabledPs);
17834
17835        if (disabledPs == null) {
17836            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17837            return false;
17838        } else if (DEBUG_REMOVE) {
17839            Slog.d(TAG, "Deleting system pkg from data partition");
17840        }
17841
17842        if (DEBUG_REMOVE) {
17843            if (applyUserRestrictions) {
17844                Slog.d(TAG, "Remembering install states:");
17845                for (int userId : allUserHandles) {
17846                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17847                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17848                }
17849            }
17850        }
17851
17852        // Delete the updated package
17853        outInfo.isRemovedPackageSystemUpdate = true;
17854        if (outInfo.removedChildPackages != null) {
17855            final int childCount = (deletedPs.childPackageNames != null)
17856                    ? deletedPs.childPackageNames.size() : 0;
17857            for (int i = 0; i < childCount; i++) {
17858                String childPackageName = deletedPs.childPackageNames.get(i);
17859                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17860                        .contains(childPackageName)) {
17861                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17862                            childPackageName);
17863                    if (childInfo != null) {
17864                        childInfo.isRemovedPackageSystemUpdate = true;
17865                    }
17866                }
17867            }
17868        }
17869
17870        if (disabledPs.versionCode < deletedPs.versionCode) {
17871            // Delete data for downgrades
17872            flags &= ~PackageManager.DELETE_KEEP_DATA;
17873        } else {
17874            // Preserve data by setting flag
17875            flags |= PackageManager.DELETE_KEEP_DATA;
17876        }
17877
17878        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17879                outInfo, writeSettings, disabledPs.pkg);
17880        if (!ret) {
17881            return false;
17882        }
17883
17884        // writer
17885        synchronized (mPackages) {
17886            // Reinstate the old system package
17887            enableSystemPackageLPw(disabledPs.pkg);
17888            // Remove any native libraries from the upgraded package.
17889            removeNativeBinariesLI(deletedPs);
17890        }
17891
17892        // Install the system package
17893        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17894        int parseFlags = mDefParseFlags
17895                | PackageParser.PARSE_MUST_BE_APK
17896                | PackageParser.PARSE_IS_SYSTEM
17897                | PackageParser.PARSE_IS_SYSTEM_DIR;
17898        if (locationIsPrivileged(disabledPs.codePath)) {
17899            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17900        }
17901
17902        final PackageParser.Package newPkg;
17903        try {
17904            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17905                0 /* currentTime */, null);
17906        } catch (PackageManagerException e) {
17907            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17908                    + e.getMessage());
17909            return false;
17910        }
17911
17912        try {
17913            // update shared libraries for the newly re-installed system package
17914            updateSharedLibrariesLPr(newPkg, null);
17915        } catch (PackageManagerException e) {
17916            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17917        }
17918
17919        prepareAppDataAfterInstallLIF(newPkg);
17920
17921        // writer
17922        synchronized (mPackages) {
17923            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17924
17925            // Propagate the permissions state as we do not want to drop on the floor
17926            // runtime permissions. The update permissions method below will take
17927            // care of removing obsolete permissions and grant install permissions.
17928            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17929            updatePermissionsLPw(newPkg.packageName, newPkg,
17930                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17931
17932            if (applyUserRestrictions) {
17933                boolean installedStateChanged = false;
17934                if (DEBUG_REMOVE) {
17935                    Slog.d(TAG, "Propagating install state across reinstall");
17936                }
17937                for (int userId : allUserHandles) {
17938                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17939                    if (DEBUG_REMOVE) {
17940                        Slog.d(TAG, "    user " + userId + " => " + installed);
17941                    }
17942                    if (installed != ps.getInstalled(userId)) {
17943                        installedStateChanged = true;
17944                    }
17945                    ps.setInstalled(installed, userId);
17946
17947                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17948                }
17949                // Regardless of writeSettings we need to ensure that this restriction
17950                // state propagation is persisted
17951                mSettings.writeAllUsersPackageRestrictionsLPr();
17952                if (installedStateChanged) {
17953                    mSettings.writeKernelMappingLPr(ps);
17954                }
17955            }
17956            // can downgrade to reader here
17957            if (writeSettings) {
17958                mSettings.writeLPr();
17959            }
17960        }
17961        return true;
17962    }
17963
17964    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17965            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17966            PackageRemovedInfo outInfo, boolean writeSettings,
17967            PackageParser.Package replacingPackage) {
17968        synchronized (mPackages) {
17969            if (outInfo != null) {
17970                outInfo.uid = ps.appId;
17971            }
17972
17973            if (outInfo != null && outInfo.removedChildPackages != null) {
17974                final int childCount = (ps.childPackageNames != null)
17975                        ? ps.childPackageNames.size() : 0;
17976                for (int i = 0; i < childCount; i++) {
17977                    String childPackageName = ps.childPackageNames.get(i);
17978                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17979                    if (childPs == null) {
17980                        return false;
17981                    }
17982                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17983                            childPackageName);
17984                    if (childInfo != null) {
17985                        childInfo.uid = childPs.appId;
17986                    }
17987                }
17988            }
17989        }
17990
17991        // Delete package data from internal structures and also remove data if flag is set
17992        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17993
17994        // Delete the child packages data
17995        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17996        for (int i = 0; i < childCount; i++) {
17997            PackageSetting childPs;
17998            synchronized (mPackages) {
17999                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18000            }
18001            if (childPs != null) {
18002                PackageRemovedInfo childOutInfo = (outInfo != null
18003                        && outInfo.removedChildPackages != null)
18004                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18005                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18006                        && (replacingPackage != null
18007                        && !replacingPackage.hasChildPackage(childPs.name))
18008                        ? flags & ~DELETE_KEEP_DATA : flags;
18009                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18010                        deleteFlags, writeSettings);
18011            }
18012        }
18013
18014        // Delete application code and resources only for parent packages
18015        if (ps.parentPackageName == null) {
18016            if (deleteCodeAndResources && (outInfo != null)) {
18017                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18018                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18019                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18020            }
18021        }
18022
18023        return true;
18024    }
18025
18026    @Override
18027    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18028            int userId) {
18029        mContext.enforceCallingOrSelfPermission(
18030                android.Manifest.permission.DELETE_PACKAGES, null);
18031        synchronized (mPackages) {
18032            PackageSetting ps = mSettings.mPackages.get(packageName);
18033            if (ps == null) {
18034                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
18035                return false;
18036            }
18037            // Cannot block uninstall of static shared libs as they are
18038            // considered a part of the using app (emulating static linking).
18039            // Also static libs are installed always on internal storage.
18040            PackageParser.Package pkg = mPackages.get(packageName);
18041            if (pkg != null && pkg.staticSharedLibName != null) {
18042                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18043                        + " providing static shared library: " + pkg.staticSharedLibName);
18044                return false;
18045            }
18046            if (!ps.getInstalled(userId)) {
18047                // Can't block uninstall for an app that is not installed or enabled.
18048                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18049                return false;
18050            }
18051            ps.setBlockUninstall(blockUninstall, userId);
18052            mSettings.writePackageRestrictionsLPr(userId);
18053        }
18054        return true;
18055    }
18056
18057    @Override
18058    public boolean getBlockUninstallForUser(String packageName, int userId) {
18059        synchronized (mPackages) {
18060            PackageSetting ps = mSettings.mPackages.get(packageName);
18061            if (ps == null) {
18062                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18063                return false;
18064            }
18065            return ps.getBlockUninstall(userId);
18066        }
18067    }
18068
18069    @Override
18070    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18071        int callingUid = Binder.getCallingUid();
18072        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18073            throw new SecurityException(
18074                    "setRequiredForSystemUser can only be run by the system or root");
18075        }
18076        synchronized (mPackages) {
18077            PackageSetting ps = mSettings.mPackages.get(packageName);
18078            if (ps == null) {
18079                Log.w(TAG, "Package doesn't exist: " + packageName);
18080                return false;
18081            }
18082            if (systemUserApp) {
18083                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18084            } else {
18085                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18086            }
18087            mSettings.writeLPr();
18088        }
18089        return true;
18090    }
18091
18092    /*
18093     * This method handles package deletion in general
18094     */
18095    private boolean deletePackageLIF(String packageName, UserHandle user,
18096            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18097            PackageRemovedInfo outInfo, boolean writeSettings,
18098            PackageParser.Package replacingPackage) {
18099        if (packageName == null) {
18100            Slog.w(TAG, "Attempt to delete null packageName.");
18101            return false;
18102        }
18103
18104        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18105
18106        PackageSetting ps;
18107        synchronized (mPackages) {
18108            ps = mSettings.mPackages.get(packageName);
18109            if (ps == null) {
18110                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18111                return false;
18112            }
18113
18114            if (ps.parentPackageName != null && (!isSystemApp(ps)
18115                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18116                if (DEBUG_REMOVE) {
18117                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18118                            + ((user == null) ? UserHandle.USER_ALL : user));
18119                }
18120                final int removedUserId = (user != null) ? user.getIdentifier()
18121                        : UserHandle.USER_ALL;
18122                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18123                    return false;
18124                }
18125                markPackageUninstalledForUserLPw(ps, user);
18126                scheduleWritePackageRestrictionsLocked(user);
18127                return true;
18128            }
18129        }
18130
18131        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18132                && user.getIdentifier() != UserHandle.USER_ALL)) {
18133            // The caller is asking that the package only be deleted for a single
18134            // user.  To do this, we just mark its uninstalled state and delete
18135            // its data. If this is a system app, we only allow this to happen if
18136            // they have set the special DELETE_SYSTEM_APP which requests different
18137            // semantics than normal for uninstalling system apps.
18138            markPackageUninstalledForUserLPw(ps, user);
18139
18140            if (!isSystemApp(ps)) {
18141                // Do not uninstall the APK if an app should be cached
18142                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18143                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18144                    // Other user still have this package installed, so all
18145                    // we need to do is clear this user's data and save that
18146                    // it is uninstalled.
18147                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18148                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18149                        return false;
18150                    }
18151                    scheduleWritePackageRestrictionsLocked(user);
18152                    return true;
18153                } else {
18154                    // We need to set it back to 'installed' so the uninstall
18155                    // broadcasts will be sent correctly.
18156                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18157                    ps.setInstalled(true, user.getIdentifier());
18158                    mSettings.writeKernelMappingLPr(ps);
18159                }
18160            } else {
18161                // This is a system app, so we assume that the
18162                // other users still have this package installed, so all
18163                // we need to do is clear this user's data and save that
18164                // it is uninstalled.
18165                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18166                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18167                    return false;
18168                }
18169                scheduleWritePackageRestrictionsLocked(user);
18170                return true;
18171            }
18172        }
18173
18174        // If we are deleting a composite package for all users, keep track
18175        // of result for each child.
18176        if (ps.childPackageNames != null && outInfo != null) {
18177            synchronized (mPackages) {
18178                final int childCount = ps.childPackageNames.size();
18179                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18180                for (int i = 0; i < childCount; i++) {
18181                    String childPackageName = ps.childPackageNames.get(i);
18182                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18183                    childInfo.removedPackage = childPackageName;
18184                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18185                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18186                    if (childPs != null) {
18187                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18188                    }
18189                }
18190            }
18191        }
18192
18193        boolean ret = false;
18194        if (isSystemApp(ps)) {
18195            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18196            // When an updated system application is deleted we delete the existing resources
18197            // as well and fall back to existing code in system partition
18198            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18199        } else {
18200            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18201            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18202                    outInfo, writeSettings, replacingPackage);
18203        }
18204
18205        // Take a note whether we deleted the package for all users
18206        if (outInfo != null) {
18207            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18208            if (outInfo.removedChildPackages != null) {
18209                synchronized (mPackages) {
18210                    final int childCount = outInfo.removedChildPackages.size();
18211                    for (int i = 0; i < childCount; i++) {
18212                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18213                        if (childInfo != null) {
18214                            childInfo.removedForAllUsers = mPackages.get(
18215                                    childInfo.removedPackage) == null;
18216                        }
18217                    }
18218                }
18219            }
18220            // If we uninstalled an update to a system app there may be some
18221            // child packages that appeared as they are declared in the system
18222            // app but were not declared in the update.
18223            if (isSystemApp(ps)) {
18224                synchronized (mPackages) {
18225                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18226                    final int childCount = (updatedPs.childPackageNames != null)
18227                            ? updatedPs.childPackageNames.size() : 0;
18228                    for (int i = 0; i < childCount; i++) {
18229                        String childPackageName = updatedPs.childPackageNames.get(i);
18230                        if (outInfo.removedChildPackages == null
18231                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18232                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18233                            if (childPs == null) {
18234                                continue;
18235                            }
18236                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18237                            installRes.name = childPackageName;
18238                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18239                            installRes.pkg = mPackages.get(childPackageName);
18240                            installRes.uid = childPs.pkg.applicationInfo.uid;
18241                            if (outInfo.appearedChildPackages == null) {
18242                                outInfo.appearedChildPackages = new ArrayMap<>();
18243                            }
18244                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18245                        }
18246                    }
18247                }
18248            }
18249        }
18250
18251        return ret;
18252    }
18253
18254    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18255        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18256                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18257        for (int nextUserId : userIds) {
18258            if (DEBUG_REMOVE) {
18259                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18260            }
18261            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18262                    false /*installed*/,
18263                    true /*stopped*/,
18264                    true /*notLaunched*/,
18265                    false /*hidden*/,
18266                    false /*suspended*/,
18267                    false /*instantApp*/,
18268                    null /*lastDisableAppCaller*/,
18269                    null /*enabledComponents*/,
18270                    null /*disabledComponents*/,
18271                    false /*blockUninstall*/,
18272                    ps.readUserState(nextUserId).domainVerificationStatus,
18273                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18274        }
18275        mSettings.writeKernelMappingLPr(ps);
18276    }
18277
18278    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18279            PackageRemovedInfo outInfo) {
18280        final PackageParser.Package pkg;
18281        synchronized (mPackages) {
18282            pkg = mPackages.get(ps.name);
18283        }
18284
18285        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18286                : new int[] {userId};
18287        for (int nextUserId : userIds) {
18288            if (DEBUG_REMOVE) {
18289                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18290                        + nextUserId);
18291            }
18292
18293            destroyAppDataLIF(pkg, userId,
18294                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18295            destroyAppProfilesLIF(pkg, userId);
18296            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18297            schedulePackageCleaning(ps.name, nextUserId, false);
18298            synchronized (mPackages) {
18299                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18300                    scheduleWritePackageRestrictionsLocked(nextUserId);
18301                }
18302                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18303            }
18304        }
18305
18306        if (outInfo != null) {
18307            outInfo.removedPackage = ps.name;
18308            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18309            outInfo.removedAppId = ps.appId;
18310            outInfo.removedUsers = userIds;
18311        }
18312
18313        return true;
18314    }
18315
18316    private final class ClearStorageConnection implements ServiceConnection {
18317        IMediaContainerService mContainerService;
18318
18319        @Override
18320        public void onServiceConnected(ComponentName name, IBinder service) {
18321            synchronized (this) {
18322                mContainerService = IMediaContainerService.Stub
18323                        .asInterface(Binder.allowBlocking(service));
18324                notifyAll();
18325            }
18326        }
18327
18328        @Override
18329        public void onServiceDisconnected(ComponentName name) {
18330        }
18331    }
18332
18333    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18334        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18335
18336        final boolean mounted;
18337        if (Environment.isExternalStorageEmulated()) {
18338            mounted = true;
18339        } else {
18340            final String status = Environment.getExternalStorageState();
18341
18342            mounted = status.equals(Environment.MEDIA_MOUNTED)
18343                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18344        }
18345
18346        if (!mounted) {
18347            return;
18348        }
18349
18350        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18351        int[] users;
18352        if (userId == UserHandle.USER_ALL) {
18353            users = sUserManager.getUserIds();
18354        } else {
18355            users = new int[] { userId };
18356        }
18357        final ClearStorageConnection conn = new ClearStorageConnection();
18358        if (mContext.bindServiceAsUser(
18359                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18360            try {
18361                for (int curUser : users) {
18362                    long timeout = SystemClock.uptimeMillis() + 5000;
18363                    synchronized (conn) {
18364                        long now;
18365                        while (conn.mContainerService == null &&
18366                                (now = SystemClock.uptimeMillis()) < timeout) {
18367                            try {
18368                                conn.wait(timeout - now);
18369                            } catch (InterruptedException e) {
18370                            }
18371                        }
18372                    }
18373                    if (conn.mContainerService == null) {
18374                        return;
18375                    }
18376
18377                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18378                    clearDirectory(conn.mContainerService,
18379                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18380                    if (allData) {
18381                        clearDirectory(conn.mContainerService,
18382                                userEnv.buildExternalStorageAppDataDirs(packageName));
18383                        clearDirectory(conn.mContainerService,
18384                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18385                    }
18386                }
18387            } finally {
18388                mContext.unbindService(conn);
18389            }
18390        }
18391    }
18392
18393    @Override
18394    public void clearApplicationProfileData(String packageName) {
18395        enforceSystemOrRoot("Only the system can clear all profile data");
18396
18397        final PackageParser.Package pkg;
18398        synchronized (mPackages) {
18399            pkg = mPackages.get(packageName);
18400        }
18401
18402        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18403            synchronized (mInstallLock) {
18404                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18405                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
18406                        true /* removeBaseMarker */);
18407            }
18408        }
18409    }
18410
18411    @Override
18412    public void clearApplicationUserData(final String packageName,
18413            final IPackageDataObserver observer, final int userId) {
18414        mContext.enforceCallingOrSelfPermission(
18415                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18416
18417        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18418                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18419
18420        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18421            throw new SecurityException("Cannot clear data for a protected package: "
18422                    + packageName);
18423        }
18424        // Queue up an async operation since the package deletion may take a little while.
18425        mHandler.post(new Runnable() {
18426            public void run() {
18427                mHandler.removeCallbacks(this);
18428                final boolean succeeded;
18429                try (PackageFreezer freezer = freezePackage(packageName,
18430                        "clearApplicationUserData")) {
18431                    synchronized (mInstallLock) {
18432                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18433                    }
18434                    clearExternalStorageDataSync(packageName, userId, true);
18435                    synchronized (mPackages) {
18436                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18437                                packageName, userId);
18438                    }
18439                }
18440                if (succeeded) {
18441                    // invoke DeviceStorageMonitor's update method to clear any notifications
18442                    DeviceStorageMonitorInternal dsm = LocalServices
18443                            .getService(DeviceStorageMonitorInternal.class);
18444                    if (dsm != null) {
18445                        dsm.checkMemory();
18446                    }
18447                }
18448                if(observer != null) {
18449                    try {
18450                        observer.onRemoveCompleted(packageName, succeeded);
18451                    } catch (RemoteException e) {
18452                        Log.i(TAG, "Observer no longer exists.");
18453                    }
18454                } //end if observer
18455            } //end run
18456        });
18457    }
18458
18459    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18460        if (packageName == null) {
18461            Slog.w(TAG, "Attempt to delete null packageName.");
18462            return false;
18463        }
18464
18465        // Try finding details about the requested package
18466        PackageParser.Package pkg;
18467        synchronized (mPackages) {
18468            pkg = mPackages.get(packageName);
18469            if (pkg == null) {
18470                final PackageSetting ps = mSettings.mPackages.get(packageName);
18471                if (ps != null) {
18472                    pkg = ps.pkg;
18473                }
18474            }
18475
18476            if (pkg == null) {
18477                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18478                return false;
18479            }
18480
18481            PackageSetting ps = (PackageSetting) pkg.mExtras;
18482            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18483        }
18484
18485        clearAppDataLIF(pkg, userId,
18486                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18487
18488        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18489        removeKeystoreDataIfNeeded(userId, appId);
18490
18491        UserManagerInternal umInternal = getUserManagerInternal();
18492        final int flags;
18493        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18494            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18495        } else if (umInternal.isUserRunning(userId)) {
18496            flags = StorageManager.FLAG_STORAGE_DE;
18497        } else {
18498            flags = 0;
18499        }
18500        prepareAppDataContentsLIF(pkg, userId, flags);
18501
18502        return true;
18503    }
18504
18505    /**
18506     * Reverts user permission state changes (permissions and flags) in
18507     * all packages for a given user.
18508     *
18509     * @param userId The device user for which to do a reset.
18510     */
18511    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18512        final int packageCount = mPackages.size();
18513        for (int i = 0; i < packageCount; i++) {
18514            PackageParser.Package pkg = mPackages.valueAt(i);
18515            PackageSetting ps = (PackageSetting) pkg.mExtras;
18516            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18517        }
18518    }
18519
18520    private void resetNetworkPolicies(int userId) {
18521        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18522    }
18523
18524    /**
18525     * Reverts user permission state changes (permissions and flags).
18526     *
18527     * @param ps The package for which to reset.
18528     * @param userId The device user for which to do a reset.
18529     */
18530    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18531            final PackageSetting ps, final int userId) {
18532        if (ps.pkg == null) {
18533            return;
18534        }
18535
18536        // These are flags that can change base on user actions.
18537        final int userSettableMask = FLAG_PERMISSION_USER_SET
18538                | FLAG_PERMISSION_USER_FIXED
18539                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18540                | FLAG_PERMISSION_REVIEW_REQUIRED;
18541
18542        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18543                | FLAG_PERMISSION_POLICY_FIXED;
18544
18545        boolean writeInstallPermissions = false;
18546        boolean writeRuntimePermissions = false;
18547
18548        final int permissionCount = ps.pkg.requestedPermissions.size();
18549        for (int i = 0; i < permissionCount; i++) {
18550            String permission = ps.pkg.requestedPermissions.get(i);
18551
18552            BasePermission bp = mSettings.mPermissions.get(permission);
18553            if (bp == null) {
18554                continue;
18555            }
18556
18557            // If shared user we just reset the state to which only this app contributed.
18558            if (ps.sharedUser != null) {
18559                boolean used = false;
18560                final int packageCount = ps.sharedUser.packages.size();
18561                for (int j = 0; j < packageCount; j++) {
18562                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18563                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18564                            && pkg.pkg.requestedPermissions.contains(permission)) {
18565                        used = true;
18566                        break;
18567                    }
18568                }
18569                if (used) {
18570                    continue;
18571                }
18572            }
18573
18574            PermissionsState permissionsState = ps.getPermissionsState();
18575
18576            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18577
18578            // Always clear the user settable flags.
18579            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18580                    bp.name) != null;
18581            // If permission review is enabled and this is a legacy app, mark the
18582            // permission as requiring a review as this is the initial state.
18583            int flags = 0;
18584            if (mPermissionReviewRequired
18585                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18586                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18587            }
18588            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18589                if (hasInstallState) {
18590                    writeInstallPermissions = true;
18591                } else {
18592                    writeRuntimePermissions = true;
18593                }
18594            }
18595
18596            // Below is only runtime permission handling.
18597            if (!bp.isRuntime()) {
18598                continue;
18599            }
18600
18601            // Never clobber system or policy.
18602            if ((oldFlags & policyOrSystemFlags) != 0) {
18603                continue;
18604            }
18605
18606            // If this permission was granted by default, make sure it is.
18607            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18608                if (permissionsState.grantRuntimePermission(bp, userId)
18609                        != PERMISSION_OPERATION_FAILURE) {
18610                    writeRuntimePermissions = true;
18611                }
18612            // If permission review is enabled the permissions for a legacy apps
18613            // are represented as constantly granted runtime ones, so don't revoke.
18614            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18615                // Otherwise, reset the permission.
18616                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18617                switch (revokeResult) {
18618                    case PERMISSION_OPERATION_SUCCESS:
18619                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18620                        writeRuntimePermissions = true;
18621                        final int appId = ps.appId;
18622                        mHandler.post(new Runnable() {
18623                            @Override
18624                            public void run() {
18625                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18626                            }
18627                        });
18628                    } break;
18629                }
18630            }
18631        }
18632
18633        // Synchronously write as we are taking permissions away.
18634        if (writeRuntimePermissions) {
18635            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18636        }
18637
18638        // Synchronously write as we are taking permissions away.
18639        if (writeInstallPermissions) {
18640            mSettings.writeLPr();
18641        }
18642    }
18643
18644    /**
18645     * Remove entries from the keystore daemon. Will only remove it if the
18646     * {@code appId} is valid.
18647     */
18648    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18649        if (appId < 0) {
18650            return;
18651        }
18652
18653        final KeyStore keyStore = KeyStore.getInstance();
18654        if (keyStore != null) {
18655            if (userId == UserHandle.USER_ALL) {
18656                for (final int individual : sUserManager.getUserIds()) {
18657                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18658                }
18659            } else {
18660                keyStore.clearUid(UserHandle.getUid(userId, appId));
18661            }
18662        } else {
18663            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18664        }
18665    }
18666
18667    @Override
18668    public void deleteApplicationCacheFiles(final String packageName,
18669            final IPackageDataObserver observer) {
18670        final int userId = UserHandle.getCallingUserId();
18671        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18672    }
18673
18674    @Override
18675    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18676            final IPackageDataObserver observer) {
18677        mContext.enforceCallingOrSelfPermission(
18678                android.Manifest.permission.DELETE_CACHE_FILES, null);
18679        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18680                /* requireFullPermission= */ true, /* checkShell= */ false,
18681                "delete application cache files");
18682
18683        final PackageParser.Package pkg;
18684        synchronized (mPackages) {
18685            pkg = mPackages.get(packageName);
18686        }
18687
18688        // Queue up an async operation since the package deletion may take a little while.
18689        mHandler.post(new Runnable() {
18690            public void run() {
18691                synchronized (mInstallLock) {
18692                    final int flags = StorageManager.FLAG_STORAGE_DE
18693                            | StorageManager.FLAG_STORAGE_CE;
18694                    // We're only clearing cache files, so we don't care if the
18695                    // app is unfrozen and still able to run
18696                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18697                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18698                }
18699                clearExternalStorageDataSync(packageName, userId, false);
18700                if (observer != null) {
18701                    try {
18702                        observer.onRemoveCompleted(packageName, true);
18703                    } catch (RemoteException e) {
18704                        Log.i(TAG, "Observer no longer exists.");
18705                    }
18706                }
18707            }
18708        });
18709    }
18710
18711    @Override
18712    public void getPackageSizeInfo(final String packageName, int userHandle,
18713            final IPackageStatsObserver observer) {
18714        mContext.enforceCallingOrSelfPermission(
18715                android.Manifest.permission.GET_PACKAGE_SIZE, null);
18716        if (packageName == null) {
18717            throw new IllegalArgumentException("Attempt to get size of null packageName");
18718        }
18719
18720        PackageStats stats = new PackageStats(packageName, userHandle);
18721
18722        /*
18723         * Queue up an async operation since the package measurement may take a
18724         * little while.
18725         */
18726        Message msg = mHandler.obtainMessage(INIT_COPY);
18727        msg.obj = new MeasureParams(stats, observer);
18728        mHandler.sendMessage(msg);
18729    }
18730
18731    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18732        final PackageSetting ps;
18733        synchronized (mPackages) {
18734            ps = mSettings.mPackages.get(packageName);
18735            if (ps == null) {
18736                Slog.w(TAG, "Failed to find settings for " + packageName);
18737                return false;
18738            }
18739        }
18740
18741        final String[] packageNames = { packageName };
18742        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18743        final String[] codePaths = { ps.codePathString };
18744
18745        try {
18746            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18747                    ps.appId, ceDataInodes, codePaths, stats);
18748
18749            // For now, ignore code size of packages on system partition
18750            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18751                stats.codeSize = 0;
18752            }
18753
18754            // External clients expect these to be tracked separately
18755            stats.dataSize -= stats.cacheSize;
18756
18757        } catch (InstallerException e) {
18758            Slog.w(TAG, String.valueOf(e));
18759            return false;
18760        }
18761
18762        return true;
18763    }
18764
18765    private int getUidTargetSdkVersionLockedLPr(int uid) {
18766        Object obj = mSettings.getUserIdLPr(uid);
18767        if (obj instanceof SharedUserSetting) {
18768            final SharedUserSetting sus = (SharedUserSetting) obj;
18769            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18770            final Iterator<PackageSetting> it = sus.packages.iterator();
18771            while (it.hasNext()) {
18772                final PackageSetting ps = it.next();
18773                if (ps.pkg != null) {
18774                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18775                    if (v < vers) vers = v;
18776                }
18777            }
18778            return vers;
18779        } else if (obj instanceof PackageSetting) {
18780            final PackageSetting ps = (PackageSetting) obj;
18781            if (ps.pkg != null) {
18782                return ps.pkg.applicationInfo.targetSdkVersion;
18783            }
18784        }
18785        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18786    }
18787
18788    @Override
18789    public void addPreferredActivity(IntentFilter filter, int match,
18790            ComponentName[] set, ComponentName activity, int userId) {
18791        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18792                "Adding preferred");
18793    }
18794
18795    private void addPreferredActivityInternal(IntentFilter filter, int match,
18796            ComponentName[] set, ComponentName activity, boolean always, int userId,
18797            String opname) {
18798        // writer
18799        int callingUid = Binder.getCallingUid();
18800        enforceCrossUserPermission(callingUid, userId,
18801                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18802        if (filter.countActions() == 0) {
18803            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18804            return;
18805        }
18806        synchronized (mPackages) {
18807            if (mContext.checkCallingOrSelfPermission(
18808                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18809                    != PackageManager.PERMISSION_GRANTED) {
18810                if (getUidTargetSdkVersionLockedLPr(callingUid)
18811                        < Build.VERSION_CODES.FROYO) {
18812                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18813                            + callingUid);
18814                    return;
18815                }
18816                mContext.enforceCallingOrSelfPermission(
18817                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18818            }
18819
18820            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18821            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18822                    + userId + ":");
18823            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18824            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18825            scheduleWritePackageRestrictionsLocked(userId);
18826            postPreferredActivityChangedBroadcast(userId);
18827        }
18828    }
18829
18830    private void postPreferredActivityChangedBroadcast(int userId) {
18831        mHandler.post(() -> {
18832            final IActivityManager am = ActivityManager.getService();
18833            if (am == null) {
18834                return;
18835            }
18836
18837            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18838            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18839            try {
18840                am.broadcastIntent(null, intent, null, null,
18841                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18842                        null, false, false, userId);
18843            } catch (RemoteException e) {
18844            }
18845        });
18846    }
18847
18848    @Override
18849    public void replacePreferredActivity(IntentFilter filter, int match,
18850            ComponentName[] set, ComponentName activity, int userId) {
18851        if (filter.countActions() != 1) {
18852            throw new IllegalArgumentException(
18853                    "replacePreferredActivity expects filter to have only 1 action.");
18854        }
18855        if (filter.countDataAuthorities() != 0
18856                || filter.countDataPaths() != 0
18857                || filter.countDataSchemes() > 1
18858                || filter.countDataTypes() != 0) {
18859            throw new IllegalArgumentException(
18860                    "replacePreferredActivity expects filter to have no data authorities, " +
18861                    "paths, or types; and at most one scheme.");
18862        }
18863
18864        final int callingUid = Binder.getCallingUid();
18865        enforceCrossUserPermission(callingUid, userId,
18866                true /* requireFullPermission */, false /* checkShell */,
18867                "replace preferred activity");
18868        synchronized (mPackages) {
18869            if (mContext.checkCallingOrSelfPermission(
18870                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18871                    != PackageManager.PERMISSION_GRANTED) {
18872                if (getUidTargetSdkVersionLockedLPr(callingUid)
18873                        < Build.VERSION_CODES.FROYO) {
18874                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18875                            + Binder.getCallingUid());
18876                    return;
18877                }
18878                mContext.enforceCallingOrSelfPermission(
18879                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18880            }
18881
18882            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18883            if (pir != null) {
18884                // Get all of the existing entries that exactly match this filter.
18885                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18886                if (existing != null && existing.size() == 1) {
18887                    PreferredActivity cur = existing.get(0);
18888                    if (DEBUG_PREFERRED) {
18889                        Slog.i(TAG, "Checking replace of preferred:");
18890                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18891                        if (!cur.mPref.mAlways) {
18892                            Slog.i(TAG, "  -- CUR; not mAlways!");
18893                        } else {
18894                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18895                            Slog.i(TAG, "  -- CUR: mSet="
18896                                    + Arrays.toString(cur.mPref.mSetComponents));
18897                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18898                            Slog.i(TAG, "  -- NEW: mMatch="
18899                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18900                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18901                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18902                        }
18903                    }
18904                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18905                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18906                            && cur.mPref.sameSet(set)) {
18907                        // Setting the preferred activity to what it happens to be already
18908                        if (DEBUG_PREFERRED) {
18909                            Slog.i(TAG, "Replacing with same preferred activity "
18910                                    + cur.mPref.mShortComponent + " for user "
18911                                    + userId + ":");
18912                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18913                        }
18914                        return;
18915                    }
18916                }
18917
18918                if (existing != null) {
18919                    if (DEBUG_PREFERRED) {
18920                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18921                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18922                    }
18923                    for (int i = 0; i < existing.size(); i++) {
18924                        PreferredActivity pa = existing.get(i);
18925                        if (DEBUG_PREFERRED) {
18926                            Slog.i(TAG, "Removing existing preferred activity "
18927                                    + pa.mPref.mComponent + ":");
18928                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18929                        }
18930                        pir.removeFilter(pa);
18931                    }
18932                }
18933            }
18934            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18935                    "Replacing preferred");
18936        }
18937    }
18938
18939    @Override
18940    public void clearPackagePreferredActivities(String packageName) {
18941        final int uid = Binder.getCallingUid();
18942        // writer
18943        synchronized (mPackages) {
18944            PackageParser.Package pkg = mPackages.get(packageName);
18945            if (pkg == null || pkg.applicationInfo.uid != uid) {
18946                if (mContext.checkCallingOrSelfPermission(
18947                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18948                        != PackageManager.PERMISSION_GRANTED) {
18949                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18950                            < Build.VERSION_CODES.FROYO) {
18951                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18952                                + Binder.getCallingUid());
18953                        return;
18954                    }
18955                    mContext.enforceCallingOrSelfPermission(
18956                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18957                }
18958            }
18959
18960            int user = UserHandle.getCallingUserId();
18961            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18962                scheduleWritePackageRestrictionsLocked(user);
18963            }
18964        }
18965    }
18966
18967    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18968    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18969        ArrayList<PreferredActivity> removed = null;
18970        boolean changed = false;
18971        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18972            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18973            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18974            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18975                continue;
18976            }
18977            Iterator<PreferredActivity> it = pir.filterIterator();
18978            while (it.hasNext()) {
18979                PreferredActivity pa = it.next();
18980                // Mark entry for removal only if it matches the package name
18981                // and the entry is of type "always".
18982                if (packageName == null ||
18983                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18984                                && pa.mPref.mAlways)) {
18985                    if (removed == null) {
18986                        removed = new ArrayList<PreferredActivity>();
18987                    }
18988                    removed.add(pa);
18989                }
18990            }
18991            if (removed != null) {
18992                for (int j=0; j<removed.size(); j++) {
18993                    PreferredActivity pa = removed.get(j);
18994                    pir.removeFilter(pa);
18995                }
18996                changed = true;
18997            }
18998        }
18999        if (changed) {
19000            postPreferredActivityChangedBroadcast(userId);
19001        }
19002        return changed;
19003    }
19004
19005    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19006    private void clearIntentFilterVerificationsLPw(int userId) {
19007        final int packageCount = mPackages.size();
19008        for (int i = 0; i < packageCount; i++) {
19009            PackageParser.Package pkg = mPackages.valueAt(i);
19010            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19011        }
19012    }
19013
19014    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19015    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19016        if (userId == UserHandle.USER_ALL) {
19017            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19018                    sUserManager.getUserIds())) {
19019                for (int oneUserId : sUserManager.getUserIds()) {
19020                    scheduleWritePackageRestrictionsLocked(oneUserId);
19021                }
19022            }
19023        } else {
19024            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19025                scheduleWritePackageRestrictionsLocked(userId);
19026            }
19027        }
19028    }
19029
19030    void clearDefaultBrowserIfNeeded(String packageName) {
19031        for (int oneUserId : sUserManager.getUserIds()) {
19032            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
19033            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
19034            if (packageName.equals(defaultBrowserPackageName)) {
19035                setDefaultBrowserPackageName(null, oneUserId);
19036            }
19037        }
19038    }
19039
19040    @Override
19041    public void resetApplicationPreferences(int userId) {
19042        mContext.enforceCallingOrSelfPermission(
19043                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19044        final long identity = Binder.clearCallingIdentity();
19045        // writer
19046        try {
19047            synchronized (mPackages) {
19048                clearPackagePreferredActivitiesLPw(null, userId);
19049                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19050                // TODO: We have to reset the default SMS and Phone. This requires
19051                // significant refactoring to keep all default apps in the package
19052                // manager (cleaner but more work) or have the services provide
19053                // callbacks to the package manager to request a default app reset.
19054                applyFactoryDefaultBrowserLPw(userId);
19055                clearIntentFilterVerificationsLPw(userId);
19056                primeDomainVerificationsLPw(userId);
19057                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19058                scheduleWritePackageRestrictionsLocked(userId);
19059            }
19060            resetNetworkPolicies(userId);
19061        } finally {
19062            Binder.restoreCallingIdentity(identity);
19063        }
19064    }
19065
19066    @Override
19067    public int getPreferredActivities(List<IntentFilter> outFilters,
19068            List<ComponentName> outActivities, String packageName) {
19069
19070        int num = 0;
19071        final int userId = UserHandle.getCallingUserId();
19072        // reader
19073        synchronized (mPackages) {
19074            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19075            if (pir != null) {
19076                final Iterator<PreferredActivity> it = pir.filterIterator();
19077                while (it.hasNext()) {
19078                    final PreferredActivity pa = it.next();
19079                    if (packageName == null
19080                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19081                                    && pa.mPref.mAlways)) {
19082                        if (outFilters != null) {
19083                            outFilters.add(new IntentFilter(pa));
19084                        }
19085                        if (outActivities != null) {
19086                            outActivities.add(pa.mPref.mComponent);
19087                        }
19088                    }
19089                }
19090            }
19091        }
19092
19093        return num;
19094    }
19095
19096    @Override
19097    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19098            int userId) {
19099        int callingUid = Binder.getCallingUid();
19100        if (callingUid != Process.SYSTEM_UID) {
19101            throw new SecurityException(
19102                    "addPersistentPreferredActivity can only be run by the system");
19103        }
19104        if (filter.countActions() == 0) {
19105            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19106            return;
19107        }
19108        synchronized (mPackages) {
19109            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19110                    ":");
19111            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19112            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19113                    new PersistentPreferredActivity(filter, activity));
19114            scheduleWritePackageRestrictionsLocked(userId);
19115            postPreferredActivityChangedBroadcast(userId);
19116        }
19117    }
19118
19119    @Override
19120    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19121        int callingUid = Binder.getCallingUid();
19122        if (callingUid != Process.SYSTEM_UID) {
19123            throw new SecurityException(
19124                    "clearPackagePersistentPreferredActivities can only be run by the system");
19125        }
19126        ArrayList<PersistentPreferredActivity> removed = null;
19127        boolean changed = false;
19128        synchronized (mPackages) {
19129            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19130                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19131                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19132                        .valueAt(i);
19133                if (userId != thisUserId) {
19134                    continue;
19135                }
19136                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19137                while (it.hasNext()) {
19138                    PersistentPreferredActivity ppa = it.next();
19139                    // Mark entry for removal only if it matches the package name.
19140                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19141                        if (removed == null) {
19142                            removed = new ArrayList<PersistentPreferredActivity>();
19143                        }
19144                        removed.add(ppa);
19145                    }
19146                }
19147                if (removed != null) {
19148                    for (int j=0; j<removed.size(); j++) {
19149                        PersistentPreferredActivity ppa = removed.get(j);
19150                        ppir.removeFilter(ppa);
19151                    }
19152                    changed = true;
19153                }
19154            }
19155
19156            if (changed) {
19157                scheduleWritePackageRestrictionsLocked(userId);
19158                postPreferredActivityChangedBroadcast(userId);
19159            }
19160        }
19161    }
19162
19163    /**
19164     * Common machinery for picking apart a restored XML blob and passing
19165     * it to a caller-supplied functor to be applied to the running system.
19166     */
19167    private void restoreFromXml(XmlPullParser parser, int userId,
19168            String expectedStartTag, BlobXmlRestorer functor)
19169            throws IOException, XmlPullParserException {
19170        int type;
19171        while ((type = parser.next()) != XmlPullParser.START_TAG
19172                && type != XmlPullParser.END_DOCUMENT) {
19173        }
19174        if (type != XmlPullParser.START_TAG) {
19175            // oops didn't find a start tag?!
19176            if (DEBUG_BACKUP) {
19177                Slog.e(TAG, "Didn't find start tag during restore");
19178            }
19179            return;
19180        }
19181Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19182        // this is supposed to be TAG_PREFERRED_BACKUP
19183        if (!expectedStartTag.equals(parser.getName())) {
19184            if (DEBUG_BACKUP) {
19185                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19186            }
19187            return;
19188        }
19189
19190        // skip interfering stuff, then we're aligned with the backing implementation
19191        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19192Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19193        functor.apply(parser, userId);
19194    }
19195
19196    private interface BlobXmlRestorer {
19197        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19198    }
19199
19200    /**
19201     * Non-Binder method, support for the backup/restore mechanism: write the
19202     * full set of preferred activities in its canonical XML format.  Returns the
19203     * XML output as a byte array, or null if there is none.
19204     */
19205    @Override
19206    public byte[] getPreferredActivityBackup(int userId) {
19207        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19208            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19209        }
19210
19211        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19212        try {
19213            final XmlSerializer serializer = new FastXmlSerializer();
19214            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19215            serializer.startDocument(null, true);
19216            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19217
19218            synchronized (mPackages) {
19219                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19220            }
19221
19222            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19223            serializer.endDocument();
19224            serializer.flush();
19225        } catch (Exception e) {
19226            if (DEBUG_BACKUP) {
19227                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19228            }
19229            return null;
19230        }
19231
19232        return dataStream.toByteArray();
19233    }
19234
19235    @Override
19236    public void restorePreferredActivities(byte[] backup, int userId) {
19237        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19238            throw new SecurityException("Only the system may call restorePreferredActivities()");
19239        }
19240
19241        try {
19242            final XmlPullParser parser = Xml.newPullParser();
19243            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19244            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19245                    new BlobXmlRestorer() {
19246                        @Override
19247                        public void apply(XmlPullParser parser, int userId)
19248                                throws XmlPullParserException, IOException {
19249                            synchronized (mPackages) {
19250                                mSettings.readPreferredActivitiesLPw(parser, userId);
19251                            }
19252                        }
19253                    } );
19254        } catch (Exception e) {
19255            if (DEBUG_BACKUP) {
19256                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19257            }
19258        }
19259    }
19260
19261    /**
19262     * Non-Binder method, support for the backup/restore mechanism: write the
19263     * default browser (etc) settings in its canonical XML format.  Returns the default
19264     * browser XML representation as a byte array, or null if there is none.
19265     */
19266    @Override
19267    public byte[] getDefaultAppsBackup(int userId) {
19268        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19269            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19270        }
19271
19272        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19273        try {
19274            final XmlSerializer serializer = new FastXmlSerializer();
19275            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19276            serializer.startDocument(null, true);
19277            serializer.startTag(null, TAG_DEFAULT_APPS);
19278
19279            synchronized (mPackages) {
19280                mSettings.writeDefaultAppsLPr(serializer, userId);
19281            }
19282
19283            serializer.endTag(null, TAG_DEFAULT_APPS);
19284            serializer.endDocument();
19285            serializer.flush();
19286        } catch (Exception e) {
19287            if (DEBUG_BACKUP) {
19288                Slog.e(TAG, "Unable to write default apps for backup", e);
19289            }
19290            return null;
19291        }
19292
19293        return dataStream.toByteArray();
19294    }
19295
19296    @Override
19297    public void restoreDefaultApps(byte[] backup, int userId) {
19298        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19299            throw new SecurityException("Only the system may call restoreDefaultApps()");
19300        }
19301
19302        try {
19303            final XmlPullParser parser = Xml.newPullParser();
19304            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19305            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19306                    new BlobXmlRestorer() {
19307                        @Override
19308                        public void apply(XmlPullParser parser, int userId)
19309                                throws XmlPullParserException, IOException {
19310                            synchronized (mPackages) {
19311                                mSettings.readDefaultAppsLPw(parser, userId);
19312                            }
19313                        }
19314                    } );
19315        } catch (Exception e) {
19316            if (DEBUG_BACKUP) {
19317                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19318            }
19319        }
19320    }
19321
19322    @Override
19323    public byte[] getIntentFilterVerificationBackup(int userId) {
19324        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19325            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19326        }
19327
19328        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19329        try {
19330            final XmlSerializer serializer = new FastXmlSerializer();
19331            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19332            serializer.startDocument(null, true);
19333            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19334
19335            synchronized (mPackages) {
19336                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19337            }
19338
19339            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19340            serializer.endDocument();
19341            serializer.flush();
19342        } catch (Exception e) {
19343            if (DEBUG_BACKUP) {
19344                Slog.e(TAG, "Unable to write default apps for backup", e);
19345            }
19346            return null;
19347        }
19348
19349        return dataStream.toByteArray();
19350    }
19351
19352    @Override
19353    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19354        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19355            throw new SecurityException("Only the system may call restorePreferredActivities()");
19356        }
19357
19358        try {
19359            final XmlPullParser parser = Xml.newPullParser();
19360            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19361            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19362                    new BlobXmlRestorer() {
19363                        @Override
19364                        public void apply(XmlPullParser parser, int userId)
19365                                throws XmlPullParserException, IOException {
19366                            synchronized (mPackages) {
19367                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19368                                mSettings.writeLPr();
19369                            }
19370                        }
19371                    } );
19372        } catch (Exception e) {
19373            if (DEBUG_BACKUP) {
19374                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19375            }
19376        }
19377    }
19378
19379    @Override
19380    public byte[] getPermissionGrantBackup(int userId) {
19381        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19382            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19383        }
19384
19385        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19386        try {
19387            final XmlSerializer serializer = new FastXmlSerializer();
19388            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19389            serializer.startDocument(null, true);
19390            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19391
19392            synchronized (mPackages) {
19393                serializeRuntimePermissionGrantsLPr(serializer, userId);
19394            }
19395
19396            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19397            serializer.endDocument();
19398            serializer.flush();
19399        } catch (Exception e) {
19400            if (DEBUG_BACKUP) {
19401                Slog.e(TAG, "Unable to write default apps for backup", e);
19402            }
19403            return null;
19404        }
19405
19406        return dataStream.toByteArray();
19407    }
19408
19409    @Override
19410    public void restorePermissionGrants(byte[] backup, int userId) {
19411        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19412            throw new SecurityException("Only the system may call restorePermissionGrants()");
19413        }
19414
19415        try {
19416            final XmlPullParser parser = Xml.newPullParser();
19417            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19418            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19419                    new BlobXmlRestorer() {
19420                        @Override
19421                        public void apply(XmlPullParser parser, int userId)
19422                                throws XmlPullParserException, IOException {
19423                            synchronized (mPackages) {
19424                                processRestoredPermissionGrantsLPr(parser, userId);
19425                            }
19426                        }
19427                    } );
19428        } catch (Exception e) {
19429            if (DEBUG_BACKUP) {
19430                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19431            }
19432        }
19433    }
19434
19435    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19436            throws IOException {
19437        serializer.startTag(null, TAG_ALL_GRANTS);
19438
19439        final int N = mSettings.mPackages.size();
19440        for (int i = 0; i < N; i++) {
19441            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19442            boolean pkgGrantsKnown = false;
19443
19444            PermissionsState packagePerms = ps.getPermissionsState();
19445
19446            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19447                final int grantFlags = state.getFlags();
19448                // only look at grants that are not system/policy fixed
19449                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19450                    final boolean isGranted = state.isGranted();
19451                    // And only back up the user-twiddled state bits
19452                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19453                        final String packageName = mSettings.mPackages.keyAt(i);
19454                        if (!pkgGrantsKnown) {
19455                            serializer.startTag(null, TAG_GRANT);
19456                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19457                            pkgGrantsKnown = true;
19458                        }
19459
19460                        final boolean userSet =
19461                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19462                        final boolean userFixed =
19463                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19464                        final boolean revoke =
19465                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19466
19467                        serializer.startTag(null, TAG_PERMISSION);
19468                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19469                        if (isGranted) {
19470                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19471                        }
19472                        if (userSet) {
19473                            serializer.attribute(null, ATTR_USER_SET, "true");
19474                        }
19475                        if (userFixed) {
19476                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19477                        }
19478                        if (revoke) {
19479                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19480                        }
19481                        serializer.endTag(null, TAG_PERMISSION);
19482                    }
19483                }
19484            }
19485
19486            if (pkgGrantsKnown) {
19487                serializer.endTag(null, TAG_GRANT);
19488            }
19489        }
19490
19491        serializer.endTag(null, TAG_ALL_GRANTS);
19492    }
19493
19494    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19495            throws XmlPullParserException, IOException {
19496        String pkgName = null;
19497        int outerDepth = parser.getDepth();
19498        int type;
19499        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19500                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19501            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19502                continue;
19503            }
19504
19505            final String tagName = parser.getName();
19506            if (tagName.equals(TAG_GRANT)) {
19507                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19508                if (DEBUG_BACKUP) {
19509                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19510                }
19511            } else if (tagName.equals(TAG_PERMISSION)) {
19512
19513                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19514                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19515
19516                int newFlagSet = 0;
19517                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19518                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19519                }
19520                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19521                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19522                }
19523                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19524                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19525                }
19526                if (DEBUG_BACKUP) {
19527                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19528                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19529                }
19530                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19531                if (ps != null) {
19532                    // Already installed so we apply the grant immediately
19533                    if (DEBUG_BACKUP) {
19534                        Slog.v(TAG, "        + already installed; applying");
19535                    }
19536                    PermissionsState perms = ps.getPermissionsState();
19537                    BasePermission bp = mSettings.mPermissions.get(permName);
19538                    if (bp != null) {
19539                        if (isGranted) {
19540                            perms.grantRuntimePermission(bp, userId);
19541                        }
19542                        if (newFlagSet != 0) {
19543                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19544                        }
19545                    }
19546                } else {
19547                    // Need to wait for post-restore install to apply the grant
19548                    if (DEBUG_BACKUP) {
19549                        Slog.v(TAG, "        - not yet installed; saving for later");
19550                    }
19551                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19552                            isGranted, newFlagSet, userId);
19553                }
19554            } else {
19555                PackageManagerService.reportSettingsProblem(Log.WARN,
19556                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19557                XmlUtils.skipCurrentTag(parser);
19558            }
19559        }
19560
19561        scheduleWriteSettingsLocked();
19562        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19563    }
19564
19565    @Override
19566    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19567            int sourceUserId, int targetUserId, int flags) {
19568        mContext.enforceCallingOrSelfPermission(
19569                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19570        int callingUid = Binder.getCallingUid();
19571        enforceOwnerRights(ownerPackage, callingUid);
19572        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19573        if (intentFilter.countActions() == 0) {
19574            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19575            return;
19576        }
19577        synchronized (mPackages) {
19578            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19579                    ownerPackage, targetUserId, flags);
19580            CrossProfileIntentResolver resolver =
19581                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19582            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19583            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19584            if (existing != null) {
19585                int size = existing.size();
19586                for (int i = 0; i < size; i++) {
19587                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19588                        return;
19589                    }
19590                }
19591            }
19592            resolver.addFilter(newFilter);
19593            scheduleWritePackageRestrictionsLocked(sourceUserId);
19594        }
19595    }
19596
19597    @Override
19598    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19599        mContext.enforceCallingOrSelfPermission(
19600                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19601        int callingUid = Binder.getCallingUid();
19602        enforceOwnerRights(ownerPackage, callingUid);
19603        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19604        synchronized (mPackages) {
19605            CrossProfileIntentResolver resolver =
19606                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19607            ArraySet<CrossProfileIntentFilter> set =
19608                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19609            for (CrossProfileIntentFilter filter : set) {
19610                if (filter.getOwnerPackage().equals(ownerPackage)) {
19611                    resolver.removeFilter(filter);
19612                }
19613            }
19614            scheduleWritePackageRestrictionsLocked(sourceUserId);
19615        }
19616    }
19617
19618    // Enforcing that callingUid is owning pkg on userId
19619    private void enforceOwnerRights(String pkg, int callingUid) {
19620        // The system owns everything.
19621        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19622            return;
19623        }
19624        int callingUserId = UserHandle.getUserId(callingUid);
19625        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19626        if (pi == null) {
19627            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19628                    + callingUserId);
19629        }
19630        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19631            throw new SecurityException("Calling uid " + callingUid
19632                    + " does not own package " + pkg);
19633        }
19634    }
19635
19636    @Override
19637    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19638        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19639    }
19640
19641    private Intent getHomeIntent() {
19642        Intent intent = new Intent(Intent.ACTION_MAIN);
19643        intent.addCategory(Intent.CATEGORY_HOME);
19644        intent.addCategory(Intent.CATEGORY_DEFAULT);
19645        return intent;
19646    }
19647
19648    private IntentFilter getHomeFilter() {
19649        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19650        filter.addCategory(Intent.CATEGORY_HOME);
19651        filter.addCategory(Intent.CATEGORY_DEFAULT);
19652        return filter;
19653    }
19654
19655    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19656            int userId) {
19657        Intent intent  = getHomeIntent();
19658        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19659                PackageManager.GET_META_DATA, userId);
19660        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19661                true, false, false, userId);
19662
19663        allHomeCandidates.clear();
19664        if (list != null) {
19665            for (ResolveInfo ri : list) {
19666                allHomeCandidates.add(ri);
19667            }
19668        }
19669        return (preferred == null || preferred.activityInfo == null)
19670                ? null
19671                : new ComponentName(preferred.activityInfo.packageName,
19672                        preferred.activityInfo.name);
19673    }
19674
19675    @Override
19676    public void setHomeActivity(ComponentName comp, int userId) {
19677        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19678        getHomeActivitiesAsUser(homeActivities, userId);
19679
19680        boolean found = false;
19681
19682        final int size = homeActivities.size();
19683        final ComponentName[] set = new ComponentName[size];
19684        for (int i = 0; i < size; i++) {
19685            final ResolveInfo candidate = homeActivities.get(i);
19686            final ActivityInfo info = candidate.activityInfo;
19687            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19688            set[i] = activityName;
19689            if (!found && activityName.equals(comp)) {
19690                found = true;
19691            }
19692        }
19693        if (!found) {
19694            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19695                    + userId);
19696        }
19697        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19698                set, comp, userId);
19699    }
19700
19701    private @Nullable String getSetupWizardPackageName() {
19702        final Intent intent = new Intent(Intent.ACTION_MAIN);
19703        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19704
19705        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19706                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19707                        | MATCH_DISABLED_COMPONENTS,
19708                UserHandle.myUserId());
19709        if (matches.size() == 1) {
19710            return matches.get(0).getComponentInfo().packageName;
19711        } else {
19712            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19713                    + ": matches=" + matches);
19714            return null;
19715        }
19716    }
19717
19718    private @Nullable String getStorageManagerPackageName() {
19719        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19720
19721        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19722                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19723                        | MATCH_DISABLED_COMPONENTS,
19724                UserHandle.myUserId());
19725        if (matches.size() == 1) {
19726            return matches.get(0).getComponentInfo().packageName;
19727        } else {
19728            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19729                    + matches.size() + ": matches=" + matches);
19730            return null;
19731        }
19732    }
19733
19734    @Override
19735    public void setApplicationEnabledSetting(String appPackageName,
19736            int newState, int flags, int userId, String callingPackage) {
19737        if (!sUserManager.exists(userId)) return;
19738        if (callingPackage == null) {
19739            callingPackage = Integer.toString(Binder.getCallingUid());
19740        }
19741        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19742    }
19743
19744    @Override
19745    public void setComponentEnabledSetting(ComponentName componentName,
19746            int newState, int flags, int userId) {
19747        if (!sUserManager.exists(userId)) return;
19748        setEnabledSetting(componentName.getPackageName(),
19749                componentName.getClassName(), newState, flags, userId, null);
19750    }
19751
19752    private void setEnabledSetting(final String packageName, String className, int newState,
19753            final int flags, int userId, String callingPackage) {
19754        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19755              || newState == COMPONENT_ENABLED_STATE_ENABLED
19756              || newState == COMPONENT_ENABLED_STATE_DISABLED
19757              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19758              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19759            throw new IllegalArgumentException("Invalid new component state: "
19760                    + newState);
19761        }
19762        PackageSetting pkgSetting;
19763        final int uid = Binder.getCallingUid();
19764        final int permission;
19765        if (uid == Process.SYSTEM_UID) {
19766            permission = PackageManager.PERMISSION_GRANTED;
19767        } else {
19768            permission = mContext.checkCallingOrSelfPermission(
19769                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19770        }
19771        enforceCrossUserPermission(uid, userId,
19772                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19773        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19774        boolean sendNow = false;
19775        boolean isApp = (className == null);
19776        String componentName = isApp ? packageName : className;
19777        int packageUid = -1;
19778        ArrayList<String> components;
19779
19780        // writer
19781        synchronized (mPackages) {
19782            pkgSetting = mSettings.mPackages.get(packageName);
19783            if (pkgSetting == null) {
19784                if (className == null) {
19785                    throw new IllegalArgumentException("Unknown package: " + packageName);
19786                }
19787                throw new IllegalArgumentException(
19788                        "Unknown component: " + packageName + "/" + className);
19789            }
19790        }
19791
19792        // Limit who can change which apps
19793        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19794            // Don't allow apps that don't have permission to modify other apps
19795            if (!allowedByPermission) {
19796                throw new SecurityException(
19797                        "Permission Denial: attempt to change component state from pid="
19798                        + Binder.getCallingPid()
19799                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19800            }
19801            // Don't allow changing protected packages.
19802            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19803                throw new SecurityException("Cannot disable a protected package: " + packageName);
19804            }
19805        }
19806
19807        synchronized (mPackages) {
19808            if (uid == Process.SHELL_UID
19809                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19810                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19811                // unless it is a test package.
19812                int oldState = pkgSetting.getEnabled(userId);
19813                if (className == null
19814                    &&
19815                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19816                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19817                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19818                    &&
19819                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19820                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19821                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19822                    // ok
19823                } else {
19824                    throw new SecurityException(
19825                            "Shell cannot change component state for " + packageName + "/"
19826                            + className + " to " + newState);
19827                }
19828            }
19829            if (className == null) {
19830                // We're dealing with an application/package level state change
19831                if (pkgSetting.getEnabled(userId) == newState) {
19832                    // Nothing to do
19833                    return;
19834                }
19835                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19836                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19837                    // Don't care about who enables an app.
19838                    callingPackage = null;
19839                }
19840                pkgSetting.setEnabled(newState, userId, callingPackage);
19841                // pkgSetting.pkg.mSetEnabled = newState;
19842            } else {
19843                // We're dealing with a component level state change
19844                // First, verify that this is a valid class name.
19845                PackageParser.Package pkg = pkgSetting.pkg;
19846                if (pkg == null || !pkg.hasComponentClassName(className)) {
19847                    if (pkg != null &&
19848                            pkg.applicationInfo.targetSdkVersion >=
19849                                    Build.VERSION_CODES.JELLY_BEAN) {
19850                        throw new IllegalArgumentException("Component class " + className
19851                                + " does not exist in " + packageName);
19852                    } else {
19853                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19854                                + className + " does not exist in " + packageName);
19855                    }
19856                }
19857                switch (newState) {
19858                case COMPONENT_ENABLED_STATE_ENABLED:
19859                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19860                        return;
19861                    }
19862                    break;
19863                case COMPONENT_ENABLED_STATE_DISABLED:
19864                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19865                        return;
19866                    }
19867                    break;
19868                case COMPONENT_ENABLED_STATE_DEFAULT:
19869                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19870                        return;
19871                    }
19872                    break;
19873                default:
19874                    Slog.e(TAG, "Invalid new component state: " + newState);
19875                    return;
19876                }
19877            }
19878            scheduleWritePackageRestrictionsLocked(userId);
19879            updateSequenceNumberLP(packageName, new int[] { userId });
19880            components = mPendingBroadcasts.get(userId, packageName);
19881            final boolean newPackage = components == null;
19882            if (newPackage) {
19883                components = new ArrayList<String>();
19884            }
19885            if (!components.contains(componentName)) {
19886                components.add(componentName);
19887            }
19888            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19889                sendNow = true;
19890                // Purge entry from pending broadcast list if another one exists already
19891                // since we are sending one right away.
19892                mPendingBroadcasts.remove(userId, packageName);
19893            } else {
19894                if (newPackage) {
19895                    mPendingBroadcasts.put(userId, packageName, components);
19896                }
19897                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19898                    // Schedule a message
19899                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19900                }
19901            }
19902        }
19903
19904        long callingId = Binder.clearCallingIdentity();
19905        try {
19906            if (sendNow) {
19907                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19908                sendPackageChangedBroadcast(packageName,
19909                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19910            }
19911        } finally {
19912            Binder.restoreCallingIdentity(callingId);
19913        }
19914    }
19915
19916    @Override
19917    public void flushPackageRestrictionsAsUser(int userId) {
19918        if (!sUserManager.exists(userId)) {
19919            return;
19920        }
19921        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19922                false /* checkShell */, "flushPackageRestrictions");
19923        synchronized (mPackages) {
19924            mSettings.writePackageRestrictionsLPr(userId);
19925            mDirtyUsers.remove(userId);
19926            if (mDirtyUsers.isEmpty()) {
19927                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19928            }
19929        }
19930    }
19931
19932    private void sendPackageChangedBroadcast(String packageName,
19933            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19934        if (DEBUG_INSTALL)
19935            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19936                    + componentNames);
19937        Bundle extras = new Bundle(4);
19938        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19939        String nameList[] = new String[componentNames.size()];
19940        componentNames.toArray(nameList);
19941        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19942        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19943        extras.putInt(Intent.EXTRA_UID, packageUid);
19944        // If this is not reporting a change of the overall package, then only send it
19945        // to registered receivers.  We don't want to launch a swath of apps for every
19946        // little component state change.
19947        final int flags = !componentNames.contains(packageName)
19948                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19949        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19950                new int[] {UserHandle.getUserId(packageUid)});
19951    }
19952
19953    @Override
19954    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19955        if (!sUserManager.exists(userId)) return;
19956        final int uid = Binder.getCallingUid();
19957        final int permission = mContext.checkCallingOrSelfPermission(
19958                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19959        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19960        enforceCrossUserPermission(uid, userId,
19961                true /* requireFullPermission */, true /* checkShell */, "stop package");
19962        // writer
19963        synchronized (mPackages) {
19964            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19965                    allowedByPermission, uid, userId)) {
19966                scheduleWritePackageRestrictionsLocked(userId);
19967            }
19968        }
19969    }
19970
19971    @Override
19972    public String getInstallerPackageName(String packageName) {
19973        // reader
19974        synchronized (mPackages) {
19975            return mSettings.getInstallerPackageNameLPr(packageName);
19976        }
19977    }
19978
19979    public boolean isOrphaned(String packageName) {
19980        // reader
19981        synchronized (mPackages) {
19982            return mSettings.isOrphaned(packageName);
19983        }
19984    }
19985
19986    @Override
19987    public int getApplicationEnabledSetting(String packageName, int userId) {
19988        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19989        int uid = Binder.getCallingUid();
19990        enforceCrossUserPermission(uid, userId,
19991                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19992        // reader
19993        synchronized (mPackages) {
19994            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19995        }
19996    }
19997
19998    @Override
19999    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20000        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20001        int uid = Binder.getCallingUid();
20002        enforceCrossUserPermission(uid, userId,
20003                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20004        // reader
20005        synchronized (mPackages) {
20006            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20007        }
20008    }
20009
20010    @Override
20011    public void enterSafeMode() {
20012        enforceSystemOrRoot("Only the system can request entering safe mode");
20013
20014        if (!mSystemReady) {
20015            mSafeMode = true;
20016        }
20017    }
20018
20019    @Override
20020    public void systemReady() {
20021        mSystemReady = true;
20022
20023        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20024        // disabled after already being started.
20025        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20026                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20027
20028        // Read the compatibilty setting when the system is ready.
20029        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20030                mContext.getContentResolver(),
20031                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20032        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20033        if (DEBUG_SETTINGS) {
20034            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20035        }
20036
20037        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20038
20039        synchronized (mPackages) {
20040            // Verify that all of the preferred activity components actually
20041            // exist.  It is possible for applications to be updated and at
20042            // that point remove a previously declared activity component that
20043            // had been set as a preferred activity.  We try to clean this up
20044            // the next time we encounter that preferred activity, but it is
20045            // possible for the user flow to never be able to return to that
20046            // situation so here we do a sanity check to make sure we haven't
20047            // left any junk around.
20048            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20049            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20050                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20051                removed.clear();
20052                for (PreferredActivity pa : pir.filterSet()) {
20053                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20054                        removed.add(pa);
20055                    }
20056                }
20057                if (removed.size() > 0) {
20058                    for (int r=0; r<removed.size(); r++) {
20059                        PreferredActivity pa = removed.get(r);
20060                        Slog.w(TAG, "Removing dangling preferred activity: "
20061                                + pa.mPref.mComponent);
20062                        pir.removeFilter(pa);
20063                    }
20064                    mSettings.writePackageRestrictionsLPr(
20065                            mSettings.mPreferredActivities.keyAt(i));
20066                }
20067            }
20068
20069            for (int userId : UserManagerService.getInstance().getUserIds()) {
20070                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20071                    grantPermissionsUserIds = ArrayUtils.appendInt(
20072                            grantPermissionsUserIds, userId);
20073                }
20074            }
20075        }
20076        sUserManager.systemReady();
20077
20078        // If we upgraded grant all default permissions before kicking off.
20079        for (int userId : grantPermissionsUserIds) {
20080            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20081        }
20082
20083        // If we did not grant default permissions, we preload from this the
20084        // default permission exceptions lazily to ensure we don't hit the
20085        // disk on a new user creation.
20086        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20087            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20088        }
20089
20090        // Kick off any messages waiting for system ready
20091        if (mPostSystemReadyMessages != null) {
20092            for (Message msg : mPostSystemReadyMessages) {
20093                msg.sendToTarget();
20094            }
20095            mPostSystemReadyMessages = null;
20096        }
20097
20098        // Watch for external volumes that come and go over time
20099        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20100        storage.registerListener(mStorageListener);
20101
20102        mInstallerService.systemReady();
20103        mPackageDexOptimizer.systemReady();
20104
20105        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20106                StorageManagerInternal.class);
20107        StorageManagerInternal.addExternalStoragePolicy(
20108                new StorageManagerInternal.ExternalStorageMountPolicy() {
20109            @Override
20110            public int getMountMode(int uid, String packageName) {
20111                if (Process.isIsolated(uid)) {
20112                    return Zygote.MOUNT_EXTERNAL_NONE;
20113                }
20114                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20115                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20116                }
20117                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20118                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20119                }
20120                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20121                    return Zygote.MOUNT_EXTERNAL_READ;
20122                }
20123                return Zygote.MOUNT_EXTERNAL_WRITE;
20124            }
20125
20126            @Override
20127            public boolean hasExternalStorage(int uid, String packageName) {
20128                return true;
20129            }
20130        });
20131
20132        // Now that we're mostly running, clean up stale users and apps
20133        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20134        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20135
20136        if (mPrivappPermissionsViolations != null) {
20137            Slog.wtf(TAG,"Signature|privileged permissions not in "
20138                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20139            mPrivappPermissionsViolations = null;
20140        }
20141    }
20142
20143    @Override
20144    public boolean isSafeMode() {
20145        return mSafeMode;
20146    }
20147
20148    @Override
20149    public boolean hasSystemUidErrors() {
20150        return mHasSystemUidErrors;
20151    }
20152
20153    static String arrayToString(int[] array) {
20154        StringBuffer buf = new StringBuffer(128);
20155        buf.append('[');
20156        if (array != null) {
20157            for (int i=0; i<array.length; i++) {
20158                if (i > 0) buf.append(", ");
20159                buf.append(array[i]);
20160            }
20161        }
20162        buf.append(']');
20163        return buf.toString();
20164    }
20165
20166    static class DumpState {
20167        public static final int DUMP_LIBS = 1 << 0;
20168        public static final int DUMP_FEATURES = 1 << 1;
20169        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20170        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20171        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20172        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20173        public static final int DUMP_PERMISSIONS = 1 << 6;
20174        public static final int DUMP_PACKAGES = 1 << 7;
20175        public static final int DUMP_SHARED_USERS = 1 << 8;
20176        public static final int DUMP_MESSAGES = 1 << 9;
20177        public static final int DUMP_PROVIDERS = 1 << 10;
20178        public static final int DUMP_VERIFIERS = 1 << 11;
20179        public static final int DUMP_PREFERRED = 1 << 12;
20180        public static final int DUMP_PREFERRED_XML = 1 << 13;
20181        public static final int DUMP_KEYSETS = 1 << 14;
20182        public static final int DUMP_VERSION = 1 << 15;
20183        public static final int DUMP_INSTALLS = 1 << 16;
20184        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20185        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20186        public static final int DUMP_FROZEN = 1 << 19;
20187        public static final int DUMP_DEXOPT = 1 << 20;
20188        public static final int DUMP_COMPILER_STATS = 1 << 21;
20189
20190        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20191
20192        private int mTypes;
20193
20194        private int mOptions;
20195
20196        private boolean mTitlePrinted;
20197
20198        private SharedUserSetting mSharedUser;
20199
20200        public boolean isDumping(int type) {
20201            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20202                return true;
20203            }
20204
20205            return (mTypes & type) != 0;
20206        }
20207
20208        public void setDump(int type) {
20209            mTypes |= type;
20210        }
20211
20212        public boolean isOptionEnabled(int option) {
20213            return (mOptions & option) != 0;
20214        }
20215
20216        public void setOptionEnabled(int option) {
20217            mOptions |= option;
20218        }
20219
20220        public boolean onTitlePrinted() {
20221            final boolean printed = mTitlePrinted;
20222            mTitlePrinted = true;
20223            return printed;
20224        }
20225
20226        public boolean getTitlePrinted() {
20227            return mTitlePrinted;
20228        }
20229
20230        public void setTitlePrinted(boolean enabled) {
20231            mTitlePrinted = enabled;
20232        }
20233
20234        public SharedUserSetting getSharedUser() {
20235            return mSharedUser;
20236        }
20237
20238        public void setSharedUser(SharedUserSetting user) {
20239            mSharedUser = user;
20240        }
20241    }
20242
20243    @Override
20244    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20245            FileDescriptor err, String[] args, ShellCallback callback,
20246            ResultReceiver resultReceiver) {
20247        (new PackageManagerShellCommand(this)).exec(
20248                this, in, out, err, args, callback, resultReceiver);
20249    }
20250
20251    @Override
20252    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20253        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20254                != PackageManager.PERMISSION_GRANTED) {
20255            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20256                    + Binder.getCallingPid()
20257                    + ", uid=" + Binder.getCallingUid()
20258                    + " without permission "
20259                    + android.Manifest.permission.DUMP);
20260            return;
20261        }
20262
20263        DumpState dumpState = new DumpState();
20264        boolean fullPreferred = false;
20265        boolean checkin = false;
20266
20267        String packageName = null;
20268        ArraySet<String> permissionNames = null;
20269
20270        int opti = 0;
20271        while (opti < args.length) {
20272            String opt = args[opti];
20273            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20274                break;
20275            }
20276            opti++;
20277
20278            if ("-a".equals(opt)) {
20279                // Right now we only know how to print all.
20280            } else if ("-h".equals(opt)) {
20281                pw.println("Package manager dump options:");
20282                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20283                pw.println("    --checkin: dump for a checkin");
20284                pw.println("    -f: print details of intent filters");
20285                pw.println("    -h: print this help");
20286                pw.println("  cmd may be one of:");
20287                pw.println("    l[ibraries]: list known shared libraries");
20288                pw.println("    f[eatures]: list device features");
20289                pw.println("    k[eysets]: print known keysets");
20290                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20291                pw.println("    perm[issions]: dump permissions");
20292                pw.println("    permission [name ...]: dump declaration and use of given permission");
20293                pw.println("    pref[erred]: print preferred package settings");
20294                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20295                pw.println("    prov[iders]: dump content providers");
20296                pw.println("    p[ackages]: dump installed packages");
20297                pw.println("    s[hared-users]: dump shared user IDs");
20298                pw.println("    m[essages]: print collected runtime messages");
20299                pw.println("    v[erifiers]: print package verifier info");
20300                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20301                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20302                pw.println("    version: print database version info");
20303                pw.println("    write: write current settings now");
20304                pw.println("    installs: details about install sessions");
20305                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20306                pw.println("    dexopt: dump dexopt state");
20307                pw.println("    compiler-stats: dump compiler statistics");
20308                pw.println("    <package.name>: info about given package");
20309                return;
20310            } else if ("--checkin".equals(opt)) {
20311                checkin = true;
20312            } else if ("-f".equals(opt)) {
20313                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20314            } else {
20315                pw.println("Unknown argument: " + opt + "; use -h for help");
20316            }
20317        }
20318
20319        // Is the caller requesting to dump a particular piece of data?
20320        if (opti < args.length) {
20321            String cmd = args[opti];
20322            opti++;
20323            // Is this a package name?
20324            if ("android".equals(cmd) || cmd.contains(".")) {
20325                packageName = cmd;
20326                // When dumping a single package, we always dump all of its
20327                // filter information since the amount of data will be reasonable.
20328                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20329            } else if ("check-permission".equals(cmd)) {
20330                if (opti >= args.length) {
20331                    pw.println("Error: check-permission missing permission argument");
20332                    return;
20333                }
20334                String perm = args[opti];
20335                opti++;
20336                if (opti >= args.length) {
20337                    pw.println("Error: check-permission missing package argument");
20338                    return;
20339                }
20340
20341                String pkg = args[opti];
20342                opti++;
20343                int user = UserHandle.getUserId(Binder.getCallingUid());
20344                if (opti < args.length) {
20345                    try {
20346                        user = Integer.parseInt(args[opti]);
20347                    } catch (NumberFormatException e) {
20348                        pw.println("Error: check-permission user argument is not a number: "
20349                                + args[opti]);
20350                        return;
20351                    }
20352                }
20353
20354                // Normalize package name to handle renamed packages and static libs
20355                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20356
20357                pw.println(checkPermission(perm, pkg, user));
20358                return;
20359            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20360                dumpState.setDump(DumpState.DUMP_LIBS);
20361            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20362                dumpState.setDump(DumpState.DUMP_FEATURES);
20363            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20364                if (opti >= args.length) {
20365                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20366                            | DumpState.DUMP_SERVICE_RESOLVERS
20367                            | DumpState.DUMP_RECEIVER_RESOLVERS
20368                            | DumpState.DUMP_CONTENT_RESOLVERS);
20369                } else {
20370                    while (opti < args.length) {
20371                        String name = args[opti];
20372                        if ("a".equals(name) || "activity".equals(name)) {
20373                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20374                        } else if ("s".equals(name) || "service".equals(name)) {
20375                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20376                        } else if ("r".equals(name) || "receiver".equals(name)) {
20377                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20378                        } else if ("c".equals(name) || "content".equals(name)) {
20379                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20380                        } else {
20381                            pw.println("Error: unknown resolver table type: " + name);
20382                            return;
20383                        }
20384                        opti++;
20385                    }
20386                }
20387            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20388                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20389            } else if ("permission".equals(cmd)) {
20390                if (opti >= args.length) {
20391                    pw.println("Error: permission requires permission name");
20392                    return;
20393                }
20394                permissionNames = new ArraySet<>();
20395                while (opti < args.length) {
20396                    permissionNames.add(args[opti]);
20397                    opti++;
20398                }
20399                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20400                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20401            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20402                dumpState.setDump(DumpState.DUMP_PREFERRED);
20403            } else if ("preferred-xml".equals(cmd)) {
20404                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20405                if (opti < args.length && "--full".equals(args[opti])) {
20406                    fullPreferred = true;
20407                    opti++;
20408                }
20409            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20410                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20411            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20412                dumpState.setDump(DumpState.DUMP_PACKAGES);
20413            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20414                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20415            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20416                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20417            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20418                dumpState.setDump(DumpState.DUMP_MESSAGES);
20419            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20420                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20421            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20422                    || "intent-filter-verifiers".equals(cmd)) {
20423                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20424            } else if ("version".equals(cmd)) {
20425                dumpState.setDump(DumpState.DUMP_VERSION);
20426            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20427                dumpState.setDump(DumpState.DUMP_KEYSETS);
20428            } else if ("installs".equals(cmd)) {
20429                dumpState.setDump(DumpState.DUMP_INSTALLS);
20430            } else if ("frozen".equals(cmd)) {
20431                dumpState.setDump(DumpState.DUMP_FROZEN);
20432            } else if ("dexopt".equals(cmd)) {
20433                dumpState.setDump(DumpState.DUMP_DEXOPT);
20434            } else if ("compiler-stats".equals(cmd)) {
20435                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20436            } else if ("write".equals(cmd)) {
20437                synchronized (mPackages) {
20438                    mSettings.writeLPr();
20439                    pw.println("Settings written.");
20440                    return;
20441                }
20442            }
20443        }
20444
20445        if (checkin) {
20446            pw.println("vers,1");
20447        }
20448
20449        // reader
20450        synchronized (mPackages) {
20451            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20452                if (!checkin) {
20453                    if (dumpState.onTitlePrinted())
20454                        pw.println();
20455                    pw.println("Database versions:");
20456                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20457                }
20458            }
20459
20460            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20461                if (!checkin) {
20462                    if (dumpState.onTitlePrinted())
20463                        pw.println();
20464                    pw.println("Verifiers:");
20465                    pw.print("  Required: ");
20466                    pw.print(mRequiredVerifierPackage);
20467                    pw.print(" (uid=");
20468                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20469                            UserHandle.USER_SYSTEM));
20470                    pw.println(")");
20471                } else if (mRequiredVerifierPackage != null) {
20472                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20473                    pw.print(",");
20474                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20475                            UserHandle.USER_SYSTEM));
20476                }
20477            }
20478
20479            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20480                    packageName == null) {
20481                if (mIntentFilterVerifierComponent != null) {
20482                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20483                    if (!checkin) {
20484                        if (dumpState.onTitlePrinted())
20485                            pw.println();
20486                        pw.println("Intent Filter Verifier:");
20487                        pw.print("  Using: ");
20488                        pw.print(verifierPackageName);
20489                        pw.print(" (uid=");
20490                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20491                                UserHandle.USER_SYSTEM));
20492                        pw.println(")");
20493                    } else if (verifierPackageName != null) {
20494                        pw.print("ifv,"); pw.print(verifierPackageName);
20495                        pw.print(",");
20496                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20497                                UserHandle.USER_SYSTEM));
20498                    }
20499                } else {
20500                    pw.println();
20501                    pw.println("No Intent Filter Verifier available!");
20502                }
20503            }
20504
20505            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20506                boolean printedHeader = false;
20507                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20508                while (it.hasNext()) {
20509                    String libName = it.next();
20510                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20511                    if (versionedLib == null) {
20512                        continue;
20513                    }
20514                    final int versionCount = versionedLib.size();
20515                    for (int i = 0; i < versionCount; i++) {
20516                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20517                        if (!checkin) {
20518                            if (!printedHeader) {
20519                                if (dumpState.onTitlePrinted())
20520                                    pw.println();
20521                                pw.println("Libraries:");
20522                                printedHeader = true;
20523                            }
20524                            pw.print("  ");
20525                        } else {
20526                            pw.print("lib,");
20527                        }
20528                        pw.print(libEntry.info.getName());
20529                        if (libEntry.info.isStatic()) {
20530                            pw.print(" version=" + libEntry.info.getVersion());
20531                        }
20532                        if (!checkin) {
20533                            pw.print(" -> ");
20534                        }
20535                        if (libEntry.path != null) {
20536                            pw.print(" (jar) ");
20537                            pw.print(libEntry.path);
20538                        } else {
20539                            pw.print(" (apk) ");
20540                            pw.print(libEntry.apk);
20541                        }
20542                        pw.println();
20543                    }
20544                }
20545            }
20546
20547            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20548                if (dumpState.onTitlePrinted())
20549                    pw.println();
20550                if (!checkin) {
20551                    pw.println("Features:");
20552                }
20553
20554                synchronized (mAvailableFeatures) {
20555                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20556                        if (checkin) {
20557                            pw.print("feat,");
20558                            pw.print(feat.name);
20559                            pw.print(",");
20560                            pw.println(feat.version);
20561                        } else {
20562                            pw.print("  ");
20563                            pw.print(feat.name);
20564                            if (feat.version > 0) {
20565                                pw.print(" version=");
20566                                pw.print(feat.version);
20567                            }
20568                            pw.println();
20569                        }
20570                    }
20571                }
20572            }
20573
20574            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20575                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20576                        : "Activity Resolver Table:", "  ", packageName,
20577                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20578                    dumpState.setTitlePrinted(true);
20579                }
20580            }
20581            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20582                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20583                        : "Receiver Resolver Table:", "  ", packageName,
20584                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20585                    dumpState.setTitlePrinted(true);
20586                }
20587            }
20588            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20589                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20590                        : "Service Resolver Table:", "  ", packageName,
20591                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20592                    dumpState.setTitlePrinted(true);
20593                }
20594            }
20595            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20596                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20597                        : "Provider Resolver Table:", "  ", packageName,
20598                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20599                    dumpState.setTitlePrinted(true);
20600                }
20601            }
20602
20603            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20604                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20605                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20606                    int user = mSettings.mPreferredActivities.keyAt(i);
20607                    if (pir.dump(pw,
20608                            dumpState.getTitlePrinted()
20609                                ? "\nPreferred Activities User " + user + ":"
20610                                : "Preferred Activities User " + user + ":", "  ",
20611                            packageName, true, false)) {
20612                        dumpState.setTitlePrinted(true);
20613                    }
20614                }
20615            }
20616
20617            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20618                pw.flush();
20619                FileOutputStream fout = new FileOutputStream(fd);
20620                BufferedOutputStream str = new BufferedOutputStream(fout);
20621                XmlSerializer serializer = new FastXmlSerializer();
20622                try {
20623                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20624                    serializer.startDocument(null, true);
20625                    serializer.setFeature(
20626                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20627                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20628                    serializer.endDocument();
20629                    serializer.flush();
20630                } catch (IllegalArgumentException e) {
20631                    pw.println("Failed writing: " + e);
20632                } catch (IllegalStateException e) {
20633                    pw.println("Failed writing: " + e);
20634                } catch (IOException e) {
20635                    pw.println("Failed writing: " + e);
20636                }
20637            }
20638
20639            if (!checkin
20640                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20641                    && packageName == null) {
20642                pw.println();
20643                int count = mSettings.mPackages.size();
20644                if (count == 0) {
20645                    pw.println("No applications!");
20646                    pw.println();
20647                } else {
20648                    final String prefix = "  ";
20649                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20650                    if (allPackageSettings.size() == 0) {
20651                        pw.println("No domain preferred apps!");
20652                        pw.println();
20653                    } else {
20654                        pw.println("App verification status:");
20655                        pw.println();
20656                        count = 0;
20657                        for (PackageSetting ps : allPackageSettings) {
20658                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20659                            if (ivi == null || ivi.getPackageName() == null) continue;
20660                            pw.println(prefix + "Package: " + ivi.getPackageName());
20661                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20662                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20663                            pw.println();
20664                            count++;
20665                        }
20666                        if (count == 0) {
20667                            pw.println(prefix + "No app verification established.");
20668                            pw.println();
20669                        }
20670                        for (int userId : sUserManager.getUserIds()) {
20671                            pw.println("App linkages for user " + userId + ":");
20672                            pw.println();
20673                            count = 0;
20674                            for (PackageSetting ps : allPackageSettings) {
20675                                final long status = ps.getDomainVerificationStatusForUser(userId);
20676                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20677                                        && !DEBUG_DOMAIN_VERIFICATION) {
20678                                    continue;
20679                                }
20680                                pw.println(prefix + "Package: " + ps.name);
20681                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20682                                String statusStr = IntentFilterVerificationInfo.
20683                                        getStatusStringFromValue(status);
20684                                pw.println(prefix + "Status:  " + statusStr);
20685                                pw.println();
20686                                count++;
20687                            }
20688                            if (count == 0) {
20689                                pw.println(prefix + "No configured app linkages.");
20690                                pw.println();
20691                            }
20692                        }
20693                    }
20694                }
20695            }
20696
20697            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20698                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20699                if (packageName == null && permissionNames == null) {
20700                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20701                        if (iperm == 0) {
20702                            if (dumpState.onTitlePrinted())
20703                                pw.println();
20704                            pw.println("AppOp Permissions:");
20705                        }
20706                        pw.print("  AppOp Permission ");
20707                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20708                        pw.println(":");
20709                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20710                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20711                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20712                        }
20713                    }
20714                }
20715            }
20716
20717            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20718                boolean printedSomething = false;
20719                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20720                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20721                        continue;
20722                    }
20723                    if (!printedSomething) {
20724                        if (dumpState.onTitlePrinted())
20725                            pw.println();
20726                        pw.println("Registered ContentProviders:");
20727                        printedSomething = true;
20728                    }
20729                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20730                    pw.print("    "); pw.println(p.toString());
20731                }
20732                printedSomething = false;
20733                for (Map.Entry<String, PackageParser.Provider> entry :
20734                        mProvidersByAuthority.entrySet()) {
20735                    PackageParser.Provider p = entry.getValue();
20736                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20737                        continue;
20738                    }
20739                    if (!printedSomething) {
20740                        if (dumpState.onTitlePrinted())
20741                            pw.println();
20742                        pw.println("ContentProvider Authorities:");
20743                        printedSomething = true;
20744                    }
20745                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20746                    pw.print("    "); pw.println(p.toString());
20747                    if (p.info != null && p.info.applicationInfo != null) {
20748                        final String appInfo = p.info.applicationInfo.toString();
20749                        pw.print("      applicationInfo="); pw.println(appInfo);
20750                    }
20751                }
20752            }
20753
20754            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20755                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20756            }
20757
20758            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20759                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20760            }
20761
20762            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20763                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20764            }
20765
20766            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20767                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20768            }
20769
20770            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20771                // XXX should handle packageName != null by dumping only install data that
20772                // the given package is involved with.
20773                if (dumpState.onTitlePrinted()) pw.println();
20774                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20775            }
20776
20777            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20778                // XXX should handle packageName != null by dumping only install data that
20779                // the given package is involved with.
20780                if (dumpState.onTitlePrinted()) pw.println();
20781
20782                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20783                ipw.println();
20784                ipw.println("Frozen packages:");
20785                ipw.increaseIndent();
20786                if (mFrozenPackages.size() == 0) {
20787                    ipw.println("(none)");
20788                } else {
20789                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20790                        ipw.println(mFrozenPackages.valueAt(i));
20791                    }
20792                }
20793                ipw.decreaseIndent();
20794            }
20795
20796            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20797                if (dumpState.onTitlePrinted()) pw.println();
20798                dumpDexoptStateLPr(pw, packageName);
20799            }
20800
20801            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20802                if (dumpState.onTitlePrinted()) pw.println();
20803                dumpCompilerStatsLPr(pw, packageName);
20804            }
20805
20806            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20807                if (dumpState.onTitlePrinted()) pw.println();
20808                mSettings.dumpReadMessagesLPr(pw, dumpState);
20809
20810                pw.println();
20811                pw.println("Package warning messages:");
20812                BufferedReader in = null;
20813                String line = null;
20814                try {
20815                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20816                    while ((line = in.readLine()) != null) {
20817                        if (line.contains("ignored: updated version")) continue;
20818                        pw.println(line);
20819                    }
20820                } catch (IOException ignored) {
20821                } finally {
20822                    IoUtils.closeQuietly(in);
20823                }
20824            }
20825
20826            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20827                BufferedReader in = null;
20828                String line = null;
20829                try {
20830                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20831                    while ((line = in.readLine()) != null) {
20832                        if (line.contains("ignored: updated version")) continue;
20833                        pw.print("msg,");
20834                        pw.println(line);
20835                    }
20836                } catch (IOException ignored) {
20837                } finally {
20838                    IoUtils.closeQuietly(in);
20839                }
20840            }
20841        }
20842    }
20843
20844    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20845        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20846        ipw.println();
20847        ipw.println("Dexopt state:");
20848        ipw.increaseIndent();
20849        Collection<PackageParser.Package> packages = null;
20850        if (packageName != null) {
20851            PackageParser.Package targetPackage = mPackages.get(packageName);
20852            if (targetPackage != null) {
20853                packages = Collections.singletonList(targetPackage);
20854            } else {
20855                ipw.println("Unable to find package: " + packageName);
20856                return;
20857            }
20858        } else {
20859            packages = mPackages.values();
20860        }
20861
20862        for (PackageParser.Package pkg : packages) {
20863            ipw.println("[" + pkg.packageName + "]");
20864            ipw.increaseIndent();
20865            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20866            ipw.decreaseIndent();
20867        }
20868    }
20869
20870    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20871        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20872        ipw.println();
20873        ipw.println("Compiler stats:");
20874        ipw.increaseIndent();
20875        Collection<PackageParser.Package> packages = null;
20876        if (packageName != null) {
20877            PackageParser.Package targetPackage = mPackages.get(packageName);
20878            if (targetPackage != null) {
20879                packages = Collections.singletonList(targetPackage);
20880            } else {
20881                ipw.println("Unable to find package: " + packageName);
20882                return;
20883            }
20884        } else {
20885            packages = mPackages.values();
20886        }
20887
20888        for (PackageParser.Package pkg : packages) {
20889            ipw.println("[" + pkg.packageName + "]");
20890            ipw.increaseIndent();
20891
20892            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20893            if (stats == null) {
20894                ipw.println("(No recorded stats)");
20895            } else {
20896                stats.dump(ipw);
20897            }
20898            ipw.decreaseIndent();
20899        }
20900    }
20901
20902    private String dumpDomainString(String packageName) {
20903        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20904                .getList();
20905        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20906
20907        ArraySet<String> result = new ArraySet<>();
20908        if (iviList.size() > 0) {
20909            for (IntentFilterVerificationInfo ivi : iviList) {
20910                for (String host : ivi.getDomains()) {
20911                    result.add(host);
20912                }
20913            }
20914        }
20915        if (filters != null && filters.size() > 0) {
20916            for (IntentFilter filter : filters) {
20917                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20918                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20919                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20920                    result.addAll(filter.getHostsList());
20921                }
20922            }
20923        }
20924
20925        StringBuilder sb = new StringBuilder(result.size() * 16);
20926        for (String domain : result) {
20927            if (sb.length() > 0) sb.append(" ");
20928            sb.append(domain);
20929        }
20930        return sb.toString();
20931    }
20932
20933    // ------- apps on sdcard specific code -------
20934    static final boolean DEBUG_SD_INSTALL = false;
20935
20936    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20937
20938    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20939
20940    private boolean mMediaMounted = false;
20941
20942    static String getEncryptKey() {
20943        try {
20944            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20945                    SD_ENCRYPTION_KEYSTORE_NAME);
20946            if (sdEncKey == null) {
20947                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20948                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20949                if (sdEncKey == null) {
20950                    Slog.e(TAG, "Failed to create encryption keys");
20951                    return null;
20952                }
20953            }
20954            return sdEncKey;
20955        } catch (NoSuchAlgorithmException nsae) {
20956            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20957            return null;
20958        } catch (IOException ioe) {
20959            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20960            return null;
20961        }
20962    }
20963
20964    /*
20965     * Update media status on PackageManager.
20966     */
20967    @Override
20968    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
20969        int callingUid = Binder.getCallingUid();
20970        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
20971            throw new SecurityException("Media status can only be updated by the system");
20972        }
20973        // reader; this apparently protects mMediaMounted, but should probably
20974        // be a different lock in that case.
20975        synchronized (mPackages) {
20976            Log.i(TAG, "Updating external media status from "
20977                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
20978                    + (mediaStatus ? "mounted" : "unmounted"));
20979            if (DEBUG_SD_INSTALL)
20980                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
20981                        + ", mMediaMounted=" + mMediaMounted);
20982            if (mediaStatus == mMediaMounted) {
20983                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
20984                        : 0, -1);
20985                mHandler.sendMessage(msg);
20986                return;
20987            }
20988            mMediaMounted = mediaStatus;
20989        }
20990        // Queue up an async operation since the package installation may take a
20991        // little while.
20992        mHandler.post(new Runnable() {
20993            public void run() {
20994                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
20995            }
20996        });
20997    }
20998
20999    /**
21000     * Called by StorageManagerService when the initial ASECs to scan are available.
21001     * Should block until all the ASEC containers are finished being scanned.
21002     */
21003    public void scanAvailableAsecs() {
21004        updateExternalMediaStatusInner(true, false, false);
21005    }
21006
21007    /*
21008     * Collect information of applications on external media, map them against
21009     * existing containers and update information based on current mount status.
21010     * Please note that we always have to report status if reportStatus has been
21011     * set to true especially when unloading packages.
21012     */
21013    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21014            boolean externalStorage) {
21015        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21016        int[] uidArr = EmptyArray.INT;
21017
21018        final String[] list = PackageHelper.getSecureContainerList();
21019        if (ArrayUtils.isEmpty(list)) {
21020            Log.i(TAG, "No secure containers found");
21021        } else {
21022            // Process list of secure containers and categorize them
21023            // as active or stale based on their package internal state.
21024
21025            // reader
21026            synchronized (mPackages) {
21027                for (String cid : list) {
21028                    // Leave stages untouched for now; installer service owns them
21029                    if (PackageInstallerService.isStageName(cid)) continue;
21030
21031                    if (DEBUG_SD_INSTALL)
21032                        Log.i(TAG, "Processing container " + cid);
21033                    String pkgName = getAsecPackageName(cid);
21034                    if (pkgName == null) {
21035                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21036                        continue;
21037                    }
21038                    if (DEBUG_SD_INSTALL)
21039                        Log.i(TAG, "Looking for pkg : " + pkgName);
21040
21041                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21042                    if (ps == null) {
21043                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21044                        continue;
21045                    }
21046
21047                    /*
21048                     * Skip packages that are not external if we're unmounting
21049                     * external storage.
21050                     */
21051                    if (externalStorage && !isMounted && !isExternal(ps)) {
21052                        continue;
21053                    }
21054
21055                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21056                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21057                    // The package status is changed only if the code path
21058                    // matches between settings and the container id.
21059                    if (ps.codePathString != null
21060                            && ps.codePathString.startsWith(args.getCodePath())) {
21061                        if (DEBUG_SD_INSTALL) {
21062                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21063                                    + " at code path: " + ps.codePathString);
21064                        }
21065
21066                        // We do have a valid package installed on sdcard
21067                        processCids.put(args, ps.codePathString);
21068                        final int uid = ps.appId;
21069                        if (uid != -1) {
21070                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21071                        }
21072                    } else {
21073                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21074                                + ps.codePathString);
21075                    }
21076                }
21077            }
21078
21079            Arrays.sort(uidArr);
21080        }
21081
21082        // Process packages with valid entries.
21083        if (isMounted) {
21084            if (DEBUG_SD_INSTALL)
21085                Log.i(TAG, "Loading packages");
21086            loadMediaPackages(processCids, uidArr, externalStorage);
21087            startCleaningPackages();
21088            mInstallerService.onSecureContainersAvailable();
21089        } else {
21090            if (DEBUG_SD_INSTALL)
21091                Log.i(TAG, "Unloading packages");
21092            unloadMediaPackages(processCids, uidArr, reportStatus);
21093        }
21094    }
21095
21096    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21097            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21098        final int size = infos.size();
21099        final String[] packageNames = new String[size];
21100        final int[] packageUids = new int[size];
21101        for (int i = 0; i < size; i++) {
21102            final ApplicationInfo info = infos.get(i);
21103            packageNames[i] = info.packageName;
21104            packageUids[i] = info.uid;
21105        }
21106        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21107                finishedReceiver);
21108    }
21109
21110    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21111            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21112        sendResourcesChangedBroadcast(mediaStatus, replacing,
21113                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21114    }
21115
21116    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21117            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21118        int size = pkgList.length;
21119        if (size > 0) {
21120            // Send broadcasts here
21121            Bundle extras = new Bundle();
21122            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21123            if (uidArr != null) {
21124                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21125            }
21126            if (replacing) {
21127                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21128            }
21129            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21130                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21131            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21132        }
21133    }
21134
21135   /*
21136     * Look at potentially valid container ids from processCids If package
21137     * information doesn't match the one on record or package scanning fails,
21138     * the cid is added to list of removeCids. We currently don't delete stale
21139     * containers.
21140     */
21141    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21142            boolean externalStorage) {
21143        ArrayList<String> pkgList = new ArrayList<String>();
21144        Set<AsecInstallArgs> keys = processCids.keySet();
21145
21146        for (AsecInstallArgs args : keys) {
21147            String codePath = processCids.get(args);
21148            if (DEBUG_SD_INSTALL)
21149                Log.i(TAG, "Loading container : " + args.cid);
21150            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21151            try {
21152                // Make sure there are no container errors first.
21153                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21154                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21155                            + " when installing from sdcard");
21156                    continue;
21157                }
21158                // Check code path here.
21159                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21160                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21161                            + " does not match one in settings " + codePath);
21162                    continue;
21163                }
21164                // Parse package
21165                int parseFlags = mDefParseFlags;
21166                if (args.isExternalAsec()) {
21167                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21168                }
21169                if (args.isFwdLocked()) {
21170                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21171                }
21172
21173                synchronized (mInstallLock) {
21174                    PackageParser.Package pkg = null;
21175                    try {
21176                        // Sadly we don't know the package name yet to freeze it
21177                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21178                                SCAN_IGNORE_FROZEN, 0, null);
21179                    } catch (PackageManagerException e) {
21180                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21181                    }
21182                    // Scan the package
21183                    if (pkg != null) {
21184                        /*
21185                         * TODO why is the lock being held? doPostInstall is
21186                         * called in other places without the lock. This needs
21187                         * to be straightened out.
21188                         */
21189                        // writer
21190                        synchronized (mPackages) {
21191                            retCode = PackageManager.INSTALL_SUCCEEDED;
21192                            pkgList.add(pkg.packageName);
21193                            // Post process args
21194                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21195                                    pkg.applicationInfo.uid);
21196                        }
21197                    } else {
21198                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21199                    }
21200                }
21201
21202            } finally {
21203                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21204                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21205                }
21206            }
21207        }
21208        // writer
21209        synchronized (mPackages) {
21210            // If the platform SDK has changed since the last time we booted,
21211            // we need to re-grant app permission to catch any new ones that
21212            // appear. This is really a hack, and means that apps can in some
21213            // cases get permissions that the user didn't initially explicitly
21214            // allow... it would be nice to have some better way to handle
21215            // this situation.
21216            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21217                    : mSettings.getInternalVersion();
21218            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21219                    : StorageManager.UUID_PRIVATE_INTERNAL;
21220
21221            int updateFlags = UPDATE_PERMISSIONS_ALL;
21222            if (ver.sdkVersion != mSdkVersion) {
21223                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21224                        + mSdkVersion + "; regranting permissions for external");
21225                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21226            }
21227            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21228
21229            // Yay, everything is now upgraded
21230            ver.forceCurrent();
21231
21232            // can downgrade to reader
21233            // Persist settings
21234            mSettings.writeLPr();
21235        }
21236        // Send a broadcast to let everyone know we are done processing
21237        if (pkgList.size() > 0) {
21238            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21239        }
21240    }
21241
21242   /*
21243     * Utility method to unload a list of specified containers
21244     */
21245    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21246        // Just unmount all valid containers.
21247        for (AsecInstallArgs arg : cidArgs) {
21248            synchronized (mInstallLock) {
21249                arg.doPostDeleteLI(false);
21250           }
21251       }
21252   }
21253
21254    /*
21255     * Unload packages mounted on external media. This involves deleting package
21256     * data from internal structures, sending broadcasts about disabled packages,
21257     * gc'ing to free up references, unmounting all secure containers
21258     * corresponding to packages on external media, and posting a
21259     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21260     * that we always have to post this message if status has been requested no
21261     * matter what.
21262     */
21263    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21264            final boolean reportStatus) {
21265        if (DEBUG_SD_INSTALL)
21266            Log.i(TAG, "unloading media packages");
21267        ArrayList<String> pkgList = new ArrayList<String>();
21268        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21269        final Set<AsecInstallArgs> keys = processCids.keySet();
21270        for (AsecInstallArgs args : keys) {
21271            String pkgName = args.getPackageName();
21272            if (DEBUG_SD_INSTALL)
21273                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21274            // Delete package internally
21275            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21276            synchronized (mInstallLock) {
21277                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21278                final boolean res;
21279                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21280                        "unloadMediaPackages")) {
21281                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21282                            null);
21283                }
21284                if (res) {
21285                    pkgList.add(pkgName);
21286                } else {
21287                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21288                    failedList.add(args);
21289                }
21290            }
21291        }
21292
21293        // reader
21294        synchronized (mPackages) {
21295            // We didn't update the settings after removing each package;
21296            // write them now for all packages.
21297            mSettings.writeLPr();
21298        }
21299
21300        // We have to absolutely send UPDATED_MEDIA_STATUS only
21301        // after confirming that all the receivers processed the ordered
21302        // broadcast when packages get disabled, force a gc to clean things up.
21303        // and unload all the containers.
21304        if (pkgList.size() > 0) {
21305            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21306                    new IIntentReceiver.Stub() {
21307                public void performReceive(Intent intent, int resultCode, String data,
21308                        Bundle extras, boolean ordered, boolean sticky,
21309                        int sendingUser) throws RemoteException {
21310                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21311                            reportStatus ? 1 : 0, 1, keys);
21312                    mHandler.sendMessage(msg);
21313                }
21314            });
21315        } else {
21316            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21317                    keys);
21318            mHandler.sendMessage(msg);
21319        }
21320    }
21321
21322    private void loadPrivatePackages(final VolumeInfo vol) {
21323        mHandler.post(new Runnable() {
21324            @Override
21325            public void run() {
21326                loadPrivatePackagesInner(vol);
21327            }
21328        });
21329    }
21330
21331    private void loadPrivatePackagesInner(VolumeInfo vol) {
21332        final String volumeUuid = vol.fsUuid;
21333        if (TextUtils.isEmpty(volumeUuid)) {
21334            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21335            return;
21336        }
21337
21338        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21339        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21340        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21341
21342        final VersionInfo ver;
21343        final List<PackageSetting> packages;
21344        synchronized (mPackages) {
21345            ver = mSettings.findOrCreateVersion(volumeUuid);
21346            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21347        }
21348
21349        for (PackageSetting ps : packages) {
21350            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21351            synchronized (mInstallLock) {
21352                final PackageParser.Package pkg;
21353                try {
21354                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21355                    loaded.add(pkg.applicationInfo);
21356
21357                } catch (PackageManagerException e) {
21358                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21359                }
21360
21361                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21362                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21363                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21364                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21365                }
21366            }
21367        }
21368
21369        // Reconcile app data for all started/unlocked users
21370        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21371        final UserManager um = mContext.getSystemService(UserManager.class);
21372        UserManagerInternal umInternal = getUserManagerInternal();
21373        for (UserInfo user : um.getUsers()) {
21374            final int flags;
21375            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21376                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21377            } else if (umInternal.isUserRunning(user.id)) {
21378                flags = StorageManager.FLAG_STORAGE_DE;
21379            } else {
21380                continue;
21381            }
21382
21383            try {
21384                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21385                synchronized (mInstallLock) {
21386                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21387                }
21388            } catch (IllegalStateException e) {
21389                // Device was probably ejected, and we'll process that event momentarily
21390                Slog.w(TAG, "Failed to prepare storage: " + e);
21391            }
21392        }
21393
21394        synchronized (mPackages) {
21395            int updateFlags = UPDATE_PERMISSIONS_ALL;
21396            if (ver.sdkVersion != mSdkVersion) {
21397                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21398                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21399                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21400            }
21401            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21402
21403            // Yay, everything is now upgraded
21404            ver.forceCurrent();
21405
21406            mSettings.writeLPr();
21407        }
21408
21409        for (PackageFreezer freezer : freezers) {
21410            freezer.close();
21411        }
21412
21413        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21414        sendResourcesChangedBroadcast(true, false, loaded, null);
21415    }
21416
21417    private void unloadPrivatePackages(final VolumeInfo vol) {
21418        mHandler.post(new Runnable() {
21419            @Override
21420            public void run() {
21421                unloadPrivatePackagesInner(vol);
21422            }
21423        });
21424    }
21425
21426    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21427        final String volumeUuid = vol.fsUuid;
21428        if (TextUtils.isEmpty(volumeUuid)) {
21429            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21430            return;
21431        }
21432
21433        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21434        synchronized (mInstallLock) {
21435        synchronized (mPackages) {
21436            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21437            for (PackageSetting ps : packages) {
21438                if (ps.pkg == null) continue;
21439
21440                final ApplicationInfo info = ps.pkg.applicationInfo;
21441                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21442                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21443
21444                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21445                        "unloadPrivatePackagesInner")) {
21446                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21447                            false, null)) {
21448                        unloaded.add(info);
21449                    } else {
21450                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21451                    }
21452                }
21453
21454                // Try very hard to release any references to this package
21455                // so we don't risk the system server being killed due to
21456                // open FDs
21457                AttributeCache.instance().removePackage(ps.name);
21458            }
21459
21460            mSettings.writeLPr();
21461        }
21462        }
21463
21464        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21465        sendResourcesChangedBroadcast(false, false, unloaded, null);
21466
21467        // Try very hard to release any references to this path so we don't risk
21468        // the system server being killed due to open FDs
21469        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21470
21471        for (int i = 0; i < 3; i++) {
21472            System.gc();
21473            System.runFinalization();
21474        }
21475    }
21476
21477    private void assertPackageKnown(String volumeUuid, String packageName)
21478            throws PackageManagerException {
21479        synchronized (mPackages) {
21480            // Normalize package name to handle renamed packages
21481            packageName = normalizePackageNameLPr(packageName);
21482
21483            final PackageSetting ps = mSettings.mPackages.get(packageName);
21484            if (ps == null) {
21485                throw new PackageManagerException("Package " + packageName + " is unknown");
21486            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21487                throw new PackageManagerException(
21488                        "Package " + packageName + " found on unknown volume " + volumeUuid
21489                                + "; expected volume " + ps.volumeUuid);
21490            }
21491        }
21492    }
21493
21494    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21495            throws PackageManagerException {
21496        synchronized (mPackages) {
21497            // Normalize package name to handle renamed packages
21498            packageName = normalizePackageNameLPr(packageName);
21499
21500            final PackageSetting ps = mSettings.mPackages.get(packageName);
21501            if (ps == null) {
21502                throw new PackageManagerException("Package " + packageName + " is unknown");
21503            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21504                throw new PackageManagerException(
21505                        "Package " + packageName + " found on unknown volume " + volumeUuid
21506                                + "; expected volume " + ps.volumeUuid);
21507            } else if (!ps.getInstalled(userId)) {
21508                throw new PackageManagerException(
21509                        "Package " + packageName + " not installed for user " + userId);
21510            }
21511        }
21512    }
21513
21514    private List<String> collectAbsoluteCodePaths() {
21515        synchronized (mPackages) {
21516            List<String> codePaths = new ArrayList<>();
21517            final int packageCount = mSettings.mPackages.size();
21518            for (int i = 0; i < packageCount; i++) {
21519                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21520                codePaths.add(ps.codePath.getAbsolutePath());
21521            }
21522            return codePaths;
21523        }
21524    }
21525
21526    /**
21527     * Examine all apps present on given mounted volume, and destroy apps that
21528     * aren't expected, either due to uninstallation or reinstallation on
21529     * another volume.
21530     */
21531    private void reconcileApps(String volumeUuid) {
21532        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21533        List<File> filesToDelete = null;
21534
21535        final File[] files = FileUtils.listFilesOrEmpty(
21536                Environment.getDataAppDirectory(volumeUuid));
21537        for (File file : files) {
21538            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21539                    && !PackageInstallerService.isStageName(file.getName());
21540            if (!isPackage) {
21541                // Ignore entries which are not packages
21542                continue;
21543            }
21544
21545            String absolutePath = file.getAbsolutePath();
21546
21547            boolean pathValid = false;
21548            final int absoluteCodePathCount = absoluteCodePaths.size();
21549            for (int i = 0; i < absoluteCodePathCount; i++) {
21550                String absoluteCodePath = absoluteCodePaths.get(i);
21551                if (absolutePath.startsWith(absoluteCodePath)) {
21552                    pathValid = true;
21553                    break;
21554                }
21555            }
21556
21557            if (!pathValid) {
21558                if (filesToDelete == null) {
21559                    filesToDelete = new ArrayList<>();
21560                }
21561                filesToDelete.add(file);
21562            }
21563        }
21564
21565        if (filesToDelete != null) {
21566            final int fileToDeleteCount = filesToDelete.size();
21567            for (int i = 0; i < fileToDeleteCount; i++) {
21568                File fileToDelete = filesToDelete.get(i);
21569                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21570                synchronized (mInstallLock) {
21571                    removeCodePathLI(fileToDelete);
21572                }
21573            }
21574        }
21575    }
21576
21577    /**
21578     * Reconcile all app data for the given user.
21579     * <p>
21580     * Verifies that directories exist and that ownership and labeling is
21581     * correct for all installed apps on all mounted volumes.
21582     */
21583    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21584        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21585        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21586            final String volumeUuid = vol.getFsUuid();
21587            synchronized (mInstallLock) {
21588                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21589            }
21590        }
21591    }
21592
21593    /**
21594     * Reconcile all app data on given mounted volume.
21595     * <p>
21596     * Destroys app data that isn't expected, either due to uninstallation or
21597     * reinstallation on another volume.
21598     * <p>
21599     * Verifies that directories exist and that ownership and labeling is
21600     * correct for all installed apps.
21601     */
21602    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21603            boolean migrateAppData) {
21604        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21605                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21606
21607        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21608        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21609
21610        // First look for stale data that doesn't belong, and check if things
21611        // have changed since we did our last restorecon
21612        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21613            if (StorageManager.isFileEncryptedNativeOrEmulated()
21614                    && !StorageManager.isUserKeyUnlocked(userId)) {
21615                throw new RuntimeException(
21616                        "Yikes, someone asked us to reconcile CE storage while " + userId
21617                                + " was still locked; this would have caused massive data loss!");
21618            }
21619
21620            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21621            for (File file : files) {
21622                final String packageName = file.getName();
21623                try {
21624                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21625                } catch (PackageManagerException e) {
21626                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21627                    try {
21628                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21629                                StorageManager.FLAG_STORAGE_CE, 0);
21630                    } catch (InstallerException e2) {
21631                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21632                    }
21633                }
21634            }
21635        }
21636        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21637            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21638            for (File file : files) {
21639                final String packageName = file.getName();
21640                try {
21641                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21642                } catch (PackageManagerException e) {
21643                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21644                    try {
21645                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21646                                StorageManager.FLAG_STORAGE_DE, 0);
21647                    } catch (InstallerException e2) {
21648                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21649                    }
21650                }
21651            }
21652        }
21653
21654        // Ensure that data directories are ready to roll for all packages
21655        // installed for this volume and user
21656        final List<PackageSetting> packages;
21657        synchronized (mPackages) {
21658            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21659        }
21660        int preparedCount = 0;
21661        for (PackageSetting ps : packages) {
21662            final String packageName = ps.name;
21663            if (ps.pkg == null) {
21664                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21665                // TODO: might be due to legacy ASEC apps; we should circle back
21666                // and reconcile again once they're scanned
21667                continue;
21668            }
21669
21670            if (ps.getInstalled(userId)) {
21671                prepareAppDataLIF(ps.pkg, userId, flags);
21672
21673                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
21674                    // We may have just shuffled around app data directories, so
21675                    // prepare them one more time
21676                    prepareAppDataLIF(ps.pkg, userId, flags);
21677                }
21678
21679                preparedCount++;
21680            }
21681        }
21682
21683        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21684    }
21685
21686    /**
21687     * Prepare app data for the given app just after it was installed or
21688     * upgraded. This method carefully only touches users that it's installed
21689     * for, and it forces a restorecon to handle any seinfo changes.
21690     * <p>
21691     * Verifies that directories exist and that ownership and labeling is
21692     * correct for all installed apps. If there is an ownership mismatch, it
21693     * will try recovering system apps by wiping data; third-party app data is
21694     * left intact.
21695     * <p>
21696     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21697     */
21698    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21699        final PackageSetting ps;
21700        synchronized (mPackages) {
21701            ps = mSettings.mPackages.get(pkg.packageName);
21702            mSettings.writeKernelMappingLPr(ps);
21703        }
21704
21705        final UserManager um = mContext.getSystemService(UserManager.class);
21706        UserManagerInternal umInternal = getUserManagerInternal();
21707        for (UserInfo user : um.getUsers()) {
21708            final int flags;
21709            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21710                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21711            } else if (umInternal.isUserRunning(user.id)) {
21712                flags = StorageManager.FLAG_STORAGE_DE;
21713            } else {
21714                continue;
21715            }
21716
21717            if (ps.getInstalled(user.id)) {
21718                // TODO: when user data is locked, mark that we're still dirty
21719                prepareAppDataLIF(pkg, user.id, flags);
21720            }
21721        }
21722    }
21723
21724    /**
21725     * Prepare app data for the given app.
21726     * <p>
21727     * Verifies that directories exist and that ownership and labeling is
21728     * correct for all installed apps. If there is an ownership mismatch, this
21729     * will try recovering system apps by wiping data; third-party app data is
21730     * left intact.
21731     */
21732    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21733        if (pkg == null) {
21734            Slog.wtf(TAG, "Package was null!", new Throwable());
21735            return;
21736        }
21737        prepareAppDataLeafLIF(pkg, userId, flags);
21738        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21739        for (int i = 0; i < childCount; i++) {
21740            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21741        }
21742    }
21743
21744    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21745        if (DEBUG_APP_DATA) {
21746            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21747                    + Integer.toHexString(flags));
21748        }
21749
21750        final String volumeUuid = pkg.volumeUuid;
21751        final String packageName = pkg.packageName;
21752        final ApplicationInfo app = pkg.applicationInfo;
21753        final int appId = UserHandle.getAppId(app.uid);
21754
21755        Preconditions.checkNotNull(app.seInfo);
21756
21757        long ceDataInode = -1;
21758        try {
21759            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21760                    appId, app.seInfo, app.targetSdkVersion);
21761        } catch (InstallerException e) {
21762            if (app.isSystemApp()) {
21763                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21764                        + ", but trying to recover: " + e);
21765                destroyAppDataLeafLIF(pkg, userId, flags);
21766                try {
21767                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21768                            appId, app.seInfo, app.targetSdkVersion);
21769                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21770                } catch (InstallerException e2) {
21771                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21772                }
21773            } else {
21774                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21775            }
21776        }
21777
21778        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21779            // TODO: mark this structure as dirty so we persist it!
21780            synchronized (mPackages) {
21781                final PackageSetting ps = mSettings.mPackages.get(packageName);
21782                if (ps != null) {
21783                    ps.setCeDataInode(ceDataInode, userId);
21784                }
21785            }
21786        }
21787
21788        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21789    }
21790
21791    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21792        if (pkg == null) {
21793            Slog.wtf(TAG, "Package was null!", new Throwable());
21794            return;
21795        }
21796        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21797        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21798        for (int i = 0; i < childCount; i++) {
21799            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21800        }
21801    }
21802
21803    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21804        final String volumeUuid = pkg.volumeUuid;
21805        final String packageName = pkg.packageName;
21806        final ApplicationInfo app = pkg.applicationInfo;
21807
21808        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21809            // Create a native library symlink only if we have native libraries
21810            // and if the native libraries are 32 bit libraries. We do not provide
21811            // this symlink for 64 bit libraries.
21812            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21813                final String nativeLibPath = app.nativeLibraryDir;
21814                try {
21815                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21816                            nativeLibPath, userId);
21817                } catch (InstallerException e) {
21818                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21819                }
21820            }
21821        }
21822    }
21823
21824    /**
21825     * For system apps on non-FBE devices, this method migrates any existing
21826     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21827     * requested by the app.
21828     */
21829    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21830        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21831                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21832            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21833                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21834            try {
21835                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21836                        storageTarget);
21837            } catch (InstallerException e) {
21838                logCriticalInfo(Log.WARN,
21839                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21840            }
21841            return true;
21842        } else {
21843            return false;
21844        }
21845    }
21846
21847    public PackageFreezer freezePackage(String packageName, String killReason) {
21848        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21849    }
21850
21851    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21852        return new PackageFreezer(packageName, userId, killReason);
21853    }
21854
21855    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21856            String killReason) {
21857        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21858    }
21859
21860    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21861            String killReason) {
21862        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21863            return new PackageFreezer();
21864        } else {
21865            return freezePackage(packageName, userId, killReason);
21866        }
21867    }
21868
21869    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21870            String killReason) {
21871        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21872    }
21873
21874    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21875            String killReason) {
21876        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21877            return new PackageFreezer();
21878        } else {
21879            return freezePackage(packageName, userId, killReason);
21880        }
21881    }
21882
21883    /**
21884     * Class that freezes and kills the given package upon creation, and
21885     * unfreezes it upon closing. This is typically used when doing surgery on
21886     * app code/data to prevent the app from running while you're working.
21887     */
21888    private class PackageFreezer implements AutoCloseable {
21889        private final String mPackageName;
21890        private final PackageFreezer[] mChildren;
21891
21892        private final boolean mWeFroze;
21893
21894        private final AtomicBoolean mClosed = new AtomicBoolean();
21895        private final CloseGuard mCloseGuard = CloseGuard.get();
21896
21897        /**
21898         * Create and return a stub freezer that doesn't actually do anything,
21899         * typically used when someone requested
21900         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21901         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21902         */
21903        public PackageFreezer() {
21904            mPackageName = null;
21905            mChildren = null;
21906            mWeFroze = false;
21907            mCloseGuard.open("close");
21908        }
21909
21910        public PackageFreezer(String packageName, int userId, String killReason) {
21911            synchronized (mPackages) {
21912                mPackageName = packageName;
21913                mWeFroze = mFrozenPackages.add(mPackageName);
21914
21915                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21916                if (ps != null) {
21917                    killApplication(ps.name, ps.appId, userId, killReason);
21918                }
21919
21920                final PackageParser.Package p = mPackages.get(packageName);
21921                if (p != null && p.childPackages != null) {
21922                    final int N = p.childPackages.size();
21923                    mChildren = new PackageFreezer[N];
21924                    for (int i = 0; i < N; i++) {
21925                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21926                                userId, killReason);
21927                    }
21928                } else {
21929                    mChildren = null;
21930                }
21931            }
21932            mCloseGuard.open("close");
21933        }
21934
21935        @Override
21936        protected void finalize() throws Throwable {
21937            try {
21938                mCloseGuard.warnIfOpen();
21939                close();
21940            } finally {
21941                super.finalize();
21942            }
21943        }
21944
21945        @Override
21946        public void close() {
21947            mCloseGuard.close();
21948            if (mClosed.compareAndSet(false, true)) {
21949                synchronized (mPackages) {
21950                    if (mWeFroze) {
21951                        mFrozenPackages.remove(mPackageName);
21952                    }
21953
21954                    if (mChildren != null) {
21955                        for (PackageFreezer freezer : mChildren) {
21956                            freezer.close();
21957                        }
21958                    }
21959                }
21960            }
21961        }
21962    }
21963
21964    /**
21965     * Verify that given package is currently frozen.
21966     */
21967    private void checkPackageFrozen(String packageName) {
21968        synchronized (mPackages) {
21969            if (!mFrozenPackages.contains(packageName)) {
21970                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21971            }
21972        }
21973    }
21974
21975    @Override
21976    public int movePackage(final String packageName, final String volumeUuid) {
21977        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21978
21979        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
21980        final int moveId = mNextMoveId.getAndIncrement();
21981        mHandler.post(new Runnable() {
21982            @Override
21983            public void run() {
21984                try {
21985                    movePackageInternal(packageName, volumeUuid, moveId, user);
21986                } catch (PackageManagerException e) {
21987                    Slog.w(TAG, "Failed to move " + packageName, e);
21988                    mMoveCallbacks.notifyStatusChanged(moveId,
21989                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21990                }
21991            }
21992        });
21993        return moveId;
21994    }
21995
21996    private void movePackageInternal(final String packageName, final String volumeUuid,
21997            final int moveId, UserHandle user) throws PackageManagerException {
21998        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21999        final PackageManager pm = mContext.getPackageManager();
22000
22001        final boolean currentAsec;
22002        final String currentVolumeUuid;
22003        final File codeFile;
22004        final String installerPackageName;
22005        final String packageAbiOverride;
22006        final int appId;
22007        final String seinfo;
22008        final String label;
22009        final int targetSdkVersion;
22010        final PackageFreezer freezer;
22011        final int[] installedUserIds;
22012
22013        // reader
22014        synchronized (mPackages) {
22015            final PackageParser.Package pkg = mPackages.get(packageName);
22016            final PackageSetting ps = mSettings.mPackages.get(packageName);
22017            if (pkg == null || ps == null) {
22018                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22019            }
22020
22021            if (pkg.applicationInfo.isSystemApp()) {
22022                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22023                        "Cannot move system application");
22024            }
22025
22026            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22027            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22028                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22029            if (isInternalStorage && !allow3rdPartyOnInternal) {
22030                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22031                        "3rd party apps are not allowed on internal storage");
22032            }
22033
22034            if (pkg.applicationInfo.isExternalAsec()) {
22035                currentAsec = true;
22036                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22037            } else if (pkg.applicationInfo.isForwardLocked()) {
22038                currentAsec = true;
22039                currentVolumeUuid = "forward_locked";
22040            } else {
22041                currentAsec = false;
22042                currentVolumeUuid = ps.volumeUuid;
22043
22044                final File probe = new File(pkg.codePath);
22045                final File probeOat = new File(probe, "oat");
22046                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22047                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22048                            "Move only supported for modern cluster style installs");
22049                }
22050            }
22051
22052            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22053                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22054                        "Package already moved to " + volumeUuid);
22055            }
22056            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22057                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22058                        "Device admin cannot be moved");
22059            }
22060
22061            if (mFrozenPackages.contains(packageName)) {
22062                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22063                        "Failed to move already frozen package");
22064            }
22065
22066            codeFile = new File(pkg.codePath);
22067            installerPackageName = ps.installerPackageName;
22068            packageAbiOverride = ps.cpuAbiOverrideString;
22069            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22070            seinfo = pkg.applicationInfo.seInfo;
22071            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22072            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22073            freezer = freezePackage(packageName, "movePackageInternal");
22074            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22075        }
22076
22077        final Bundle extras = new Bundle();
22078        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22079        extras.putString(Intent.EXTRA_TITLE, label);
22080        mMoveCallbacks.notifyCreated(moveId, extras);
22081
22082        int installFlags;
22083        final boolean moveCompleteApp;
22084        final File measurePath;
22085
22086        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22087            installFlags = INSTALL_INTERNAL;
22088            moveCompleteApp = !currentAsec;
22089            measurePath = Environment.getDataAppDirectory(volumeUuid);
22090        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22091            installFlags = INSTALL_EXTERNAL;
22092            moveCompleteApp = false;
22093            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22094        } else {
22095            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22096            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22097                    || !volume.isMountedWritable()) {
22098                freezer.close();
22099                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22100                        "Move location not mounted private volume");
22101            }
22102
22103            Preconditions.checkState(!currentAsec);
22104
22105            installFlags = INSTALL_INTERNAL;
22106            moveCompleteApp = true;
22107            measurePath = Environment.getDataAppDirectory(volumeUuid);
22108        }
22109
22110        final PackageStats stats = new PackageStats(null, -1);
22111        synchronized (mInstaller) {
22112            for (int userId : installedUserIds) {
22113                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22114                    freezer.close();
22115                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22116                            "Failed to measure package size");
22117                }
22118            }
22119        }
22120
22121        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22122                + stats.dataSize);
22123
22124        final long startFreeBytes = measurePath.getFreeSpace();
22125        final long sizeBytes;
22126        if (moveCompleteApp) {
22127            sizeBytes = stats.codeSize + stats.dataSize;
22128        } else {
22129            sizeBytes = stats.codeSize;
22130        }
22131
22132        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22133            freezer.close();
22134            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22135                    "Not enough free space to move");
22136        }
22137
22138        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22139
22140        final CountDownLatch installedLatch = new CountDownLatch(1);
22141        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22142            @Override
22143            public void onUserActionRequired(Intent intent) throws RemoteException {
22144                throw new IllegalStateException();
22145            }
22146
22147            @Override
22148            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22149                    Bundle extras) throws RemoteException {
22150                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22151                        + PackageManager.installStatusToString(returnCode, msg));
22152
22153                installedLatch.countDown();
22154                freezer.close();
22155
22156                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22157                switch (status) {
22158                    case PackageInstaller.STATUS_SUCCESS:
22159                        mMoveCallbacks.notifyStatusChanged(moveId,
22160                                PackageManager.MOVE_SUCCEEDED);
22161                        break;
22162                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22163                        mMoveCallbacks.notifyStatusChanged(moveId,
22164                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22165                        break;
22166                    default:
22167                        mMoveCallbacks.notifyStatusChanged(moveId,
22168                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22169                        break;
22170                }
22171            }
22172        };
22173
22174        final MoveInfo move;
22175        if (moveCompleteApp) {
22176            // Kick off a thread to report progress estimates
22177            new Thread() {
22178                @Override
22179                public void run() {
22180                    while (true) {
22181                        try {
22182                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22183                                break;
22184                            }
22185                        } catch (InterruptedException ignored) {
22186                        }
22187
22188                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22189                        final int progress = 10 + (int) MathUtils.constrain(
22190                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22191                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22192                    }
22193                }
22194            }.start();
22195
22196            final String dataAppName = codeFile.getName();
22197            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22198                    dataAppName, appId, seinfo, targetSdkVersion);
22199        } else {
22200            move = null;
22201        }
22202
22203        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22204
22205        final Message msg = mHandler.obtainMessage(INIT_COPY);
22206        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22207        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22208                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22209                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22210                PackageManager.INSTALL_REASON_UNKNOWN);
22211        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22212        msg.obj = params;
22213
22214        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22215                System.identityHashCode(msg.obj));
22216        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22217                System.identityHashCode(msg.obj));
22218
22219        mHandler.sendMessage(msg);
22220    }
22221
22222    @Override
22223    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22224        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22225
22226        final int realMoveId = mNextMoveId.getAndIncrement();
22227        final Bundle extras = new Bundle();
22228        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22229        mMoveCallbacks.notifyCreated(realMoveId, extras);
22230
22231        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22232            @Override
22233            public void onCreated(int moveId, Bundle extras) {
22234                // Ignored
22235            }
22236
22237            @Override
22238            public void onStatusChanged(int moveId, int status, long estMillis) {
22239                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22240            }
22241        };
22242
22243        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22244        storage.setPrimaryStorageUuid(volumeUuid, callback);
22245        return realMoveId;
22246    }
22247
22248    @Override
22249    public int getMoveStatus(int moveId) {
22250        mContext.enforceCallingOrSelfPermission(
22251                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22252        return mMoveCallbacks.mLastStatus.get(moveId);
22253    }
22254
22255    @Override
22256    public void registerMoveCallback(IPackageMoveObserver callback) {
22257        mContext.enforceCallingOrSelfPermission(
22258                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22259        mMoveCallbacks.register(callback);
22260    }
22261
22262    @Override
22263    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22264        mContext.enforceCallingOrSelfPermission(
22265                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22266        mMoveCallbacks.unregister(callback);
22267    }
22268
22269    @Override
22270    public boolean setInstallLocation(int loc) {
22271        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22272                null);
22273        if (getInstallLocation() == loc) {
22274            return true;
22275        }
22276        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22277                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22278            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22279                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22280            return true;
22281        }
22282        return false;
22283   }
22284
22285    @Override
22286    public int getInstallLocation() {
22287        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22288                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22289                PackageHelper.APP_INSTALL_AUTO);
22290    }
22291
22292    /** Called by UserManagerService */
22293    void cleanUpUser(UserManagerService userManager, int userHandle) {
22294        synchronized (mPackages) {
22295            mDirtyUsers.remove(userHandle);
22296            mUserNeedsBadging.delete(userHandle);
22297            mSettings.removeUserLPw(userHandle);
22298            mPendingBroadcasts.remove(userHandle);
22299            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22300            removeUnusedPackagesLPw(userManager, userHandle);
22301        }
22302    }
22303
22304    /**
22305     * We're removing userHandle and would like to remove any downloaded packages
22306     * that are no longer in use by any other user.
22307     * @param userHandle the user being removed
22308     */
22309    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22310        final boolean DEBUG_CLEAN_APKS = false;
22311        int [] users = userManager.getUserIds();
22312        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22313        while (psit.hasNext()) {
22314            PackageSetting ps = psit.next();
22315            if (ps.pkg == null) {
22316                continue;
22317            }
22318            final String packageName = ps.pkg.packageName;
22319            // Skip over if system app
22320            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22321                continue;
22322            }
22323            if (DEBUG_CLEAN_APKS) {
22324                Slog.i(TAG, "Checking package " + packageName);
22325            }
22326            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22327            if (keep) {
22328                if (DEBUG_CLEAN_APKS) {
22329                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22330                }
22331            } else {
22332                for (int i = 0; i < users.length; i++) {
22333                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22334                        keep = true;
22335                        if (DEBUG_CLEAN_APKS) {
22336                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22337                                    + users[i]);
22338                        }
22339                        break;
22340                    }
22341                }
22342            }
22343            if (!keep) {
22344                if (DEBUG_CLEAN_APKS) {
22345                    Slog.i(TAG, "  Removing package " + packageName);
22346                }
22347                mHandler.post(new Runnable() {
22348                    public void run() {
22349                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22350                                userHandle, 0);
22351                    } //end run
22352                });
22353            }
22354        }
22355    }
22356
22357    /** Called by UserManagerService */
22358    void createNewUser(int userId, String[] disallowedPackages) {
22359        synchronized (mInstallLock) {
22360            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22361        }
22362        synchronized (mPackages) {
22363            scheduleWritePackageRestrictionsLocked(userId);
22364            scheduleWritePackageListLocked(userId);
22365            applyFactoryDefaultBrowserLPw(userId);
22366            primeDomainVerificationsLPw(userId);
22367        }
22368    }
22369
22370    void onNewUserCreated(final int userId) {
22371        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22372        // If permission review for legacy apps is required, we represent
22373        // dagerous permissions for such apps as always granted runtime
22374        // permissions to keep per user flag state whether review is needed.
22375        // Hence, if a new user is added we have to propagate dangerous
22376        // permission grants for these legacy apps.
22377        if (mPermissionReviewRequired) {
22378            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22379                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22380        }
22381    }
22382
22383    @Override
22384    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22385        mContext.enforceCallingOrSelfPermission(
22386                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22387                "Only package verification agents can read the verifier device identity");
22388
22389        synchronized (mPackages) {
22390            return mSettings.getVerifierDeviceIdentityLPw();
22391        }
22392    }
22393
22394    @Override
22395    public void setPermissionEnforced(String permission, boolean enforced) {
22396        // TODO: Now that we no longer change GID for storage, this should to away.
22397        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22398                "setPermissionEnforced");
22399        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22400            synchronized (mPackages) {
22401                if (mSettings.mReadExternalStorageEnforced == null
22402                        || mSettings.mReadExternalStorageEnforced != enforced) {
22403                    mSettings.mReadExternalStorageEnforced = enforced;
22404                    mSettings.writeLPr();
22405                }
22406            }
22407            // kill any non-foreground processes so we restart them and
22408            // grant/revoke the GID.
22409            final IActivityManager am = ActivityManager.getService();
22410            if (am != null) {
22411                final long token = Binder.clearCallingIdentity();
22412                try {
22413                    am.killProcessesBelowForeground("setPermissionEnforcement");
22414                } catch (RemoteException e) {
22415                } finally {
22416                    Binder.restoreCallingIdentity(token);
22417                }
22418            }
22419        } else {
22420            throw new IllegalArgumentException("No selective enforcement for " + permission);
22421        }
22422    }
22423
22424    @Override
22425    @Deprecated
22426    public boolean isPermissionEnforced(String permission) {
22427        return true;
22428    }
22429
22430    @Override
22431    public boolean isStorageLow() {
22432        final long token = Binder.clearCallingIdentity();
22433        try {
22434            final DeviceStorageMonitorInternal
22435                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22436            if (dsm != null) {
22437                return dsm.isMemoryLow();
22438            } else {
22439                return false;
22440            }
22441        } finally {
22442            Binder.restoreCallingIdentity(token);
22443        }
22444    }
22445
22446    @Override
22447    public IPackageInstaller getPackageInstaller() {
22448        return mInstallerService;
22449    }
22450
22451    private boolean userNeedsBadging(int userId) {
22452        int index = mUserNeedsBadging.indexOfKey(userId);
22453        if (index < 0) {
22454            final UserInfo userInfo;
22455            final long token = Binder.clearCallingIdentity();
22456            try {
22457                userInfo = sUserManager.getUserInfo(userId);
22458            } finally {
22459                Binder.restoreCallingIdentity(token);
22460            }
22461            final boolean b;
22462            if (userInfo != null && userInfo.isManagedProfile()) {
22463                b = true;
22464            } else {
22465                b = false;
22466            }
22467            mUserNeedsBadging.put(userId, b);
22468            return b;
22469        }
22470        return mUserNeedsBadging.valueAt(index);
22471    }
22472
22473    @Override
22474    public KeySet getKeySetByAlias(String packageName, String alias) {
22475        if (packageName == null || alias == null) {
22476            return null;
22477        }
22478        synchronized(mPackages) {
22479            final PackageParser.Package pkg = mPackages.get(packageName);
22480            if (pkg == null) {
22481                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22482                throw new IllegalArgumentException("Unknown package: " + packageName);
22483            }
22484            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22485            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22486        }
22487    }
22488
22489    @Override
22490    public KeySet getSigningKeySet(String packageName) {
22491        if (packageName == null) {
22492            return null;
22493        }
22494        synchronized(mPackages) {
22495            final PackageParser.Package pkg = mPackages.get(packageName);
22496            if (pkg == null) {
22497                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22498                throw new IllegalArgumentException("Unknown package: " + packageName);
22499            }
22500            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22501                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22502                throw new SecurityException("May not access signing KeySet of other apps.");
22503            }
22504            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22505            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22506        }
22507    }
22508
22509    @Override
22510    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22511        if (packageName == null || ks == null) {
22512            return false;
22513        }
22514        synchronized(mPackages) {
22515            final PackageParser.Package pkg = mPackages.get(packageName);
22516            if (pkg == null) {
22517                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22518                throw new IllegalArgumentException("Unknown package: " + packageName);
22519            }
22520            IBinder ksh = ks.getToken();
22521            if (ksh instanceof KeySetHandle) {
22522                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22523                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22524            }
22525            return false;
22526        }
22527    }
22528
22529    @Override
22530    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22531        if (packageName == null || ks == null) {
22532            return false;
22533        }
22534        synchronized(mPackages) {
22535            final PackageParser.Package pkg = mPackages.get(packageName);
22536            if (pkg == null) {
22537                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22538                throw new IllegalArgumentException("Unknown package: " + packageName);
22539            }
22540            IBinder ksh = ks.getToken();
22541            if (ksh instanceof KeySetHandle) {
22542                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22543                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22544            }
22545            return false;
22546        }
22547    }
22548
22549    private void deletePackageIfUnusedLPr(final String packageName) {
22550        PackageSetting ps = mSettings.mPackages.get(packageName);
22551        if (ps == null) {
22552            return;
22553        }
22554        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22555            // TODO Implement atomic delete if package is unused
22556            // It is currently possible that the package will be deleted even if it is installed
22557            // after this method returns.
22558            mHandler.post(new Runnable() {
22559                public void run() {
22560                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22561                            0, PackageManager.DELETE_ALL_USERS);
22562                }
22563            });
22564        }
22565    }
22566
22567    /**
22568     * Check and throw if the given before/after packages would be considered a
22569     * downgrade.
22570     */
22571    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22572            throws PackageManagerException {
22573        if (after.versionCode < before.mVersionCode) {
22574            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22575                    "Update version code " + after.versionCode + " is older than current "
22576                    + before.mVersionCode);
22577        } else if (after.versionCode == before.mVersionCode) {
22578            if (after.baseRevisionCode < before.baseRevisionCode) {
22579                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22580                        "Update base revision code " + after.baseRevisionCode
22581                        + " is older than current " + before.baseRevisionCode);
22582            }
22583
22584            if (!ArrayUtils.isEmpty(after.splitNames)) {
22585                for (int i = 0; i < after.splitNames.length; i++) {
22586                    final String splitName = after.splitNames[i];
22587                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22588                    if (j != -1) {
22589                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22590                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22591                                    "Update split " + splitName + " revision code "
22592                                    + after.splitRevisionCodes[i] + " is older than current "
22593                                    + before.splitRevisionCodes[j]);
22594                        }
22595                    }
22596                }
22597            }
22598        }
22599    }
22600
22601    private static class MoveCallbacks extends Handler {
22602        private static final int MSG_CREATED = 1;
22603        private static final int MSG_STATUS_CHANGED = 2;
22604
22605        private final RemoteCallbackList<IPackageMoveObserver>
22606                mCallbacks = new RemoteCallbackList<>();
22607
22608        private final SparseIntArray mLastStatus = new SparseIntArray();
22609
22610        public MoveCallbacks(Looper looper) {
22611            super(looper);
22612        }
22613
22614        public void register(IPackageMoveObserver callback) {
22615            mCallbacks.register(callback);
22616        }
22617
22618        public void unregister(IPackageMoveObserver callback) {
22619            mCallbacks.unregister(callback);
22620        }
22621
22622        @Override
22623        public void handleMessage(Message msg) {
22624            final SomeArgs args = (SomeArgs) msg.obj;
22625            final int n = mCallbacks.beginBroadcast();
22626            for (int i = 0; i < n; i++) {
22627                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22628                try {
22629                    invokeCallback(callback, msg.what, args);
22630                } catch (RemoteException ignored) {
22631                }
22632            }
22633            mCallbacks.finishBroadcast();
22634            args.recycle();
22635        }
22636
22637        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22638                throws RemoteException {
22639            switch (what) {
22640                case MSG_CREATED: {
22641                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22642                    break;
22643                }
22644                case MSG_STATUS_CHANGED: {
22645                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22646                    break;
22647                }
22648            }
22649        }
22650
22651        private void notifyCreated(int moveId, Bundle extras) {
22652            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22653
22654            final SomeArgs args = SomeArgs.obtain();
22655            args.argi1 = moveId;
22656            args.arg2 = extras;
22657            obtainMessage(MSG_CREATED, args).sendToTarget();
22658        }
22659
22660        private void notifyStatusChanged(int moveId, int status) {
22661            notifyStatusChanged(moveId, status, -1);
22662        }
22663
22664        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22665            Slog.v(TAG, "Move " + moveId + " status " + status);
22666
22667            final SomeArgs args = SomeArgs.obtain();
22668            args.argi1 = moveId;
22669            args.argi2 = status;
22670            args.arg3 = estMillis;
22671            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22672
22673            synchronized (mLastStatus) {
22674                mLastStatus.put(moveId, status);
22675            }
22676        }
22677    }
22678
22679    private final static class OnPermissionChangeListeners extends Handler {
22680        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22681
22682        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22683                new RemoteCallbackList<>();
22684
22685        public OnPermissionChangeListeners(Looper looper) {
22686            super(looper);
22687        }
22688
22689        @Override
22690        public void handleMessage(Message msg) {
22691            switch (msg.what) {
22692                case MSG_ON_PERMISSIONS_CHANGED: {
22693                    final int uid = msg.arg1;
22694                    handleOnPermissionsChanged(uid);
22695                } break;
22696            }
22697        }
22698
22699        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22700            mPermissionListeners.register(listener);
22701
22702        }
22703
22704        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22705            mPermissionListeners.unregister(listener);
22706        }
22707
22708        public void onPermissionsChanged(int uid) {
22709            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22710                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22711            }
22712        }
22713
22714        private void handleOnPermissionsChanged(int uid) {
22715            final int count = mPermissionListeners.beginBroadcast();
22716            try {
22717                for (int i = 0; i < count; i++) {
22718                    IOnPermissionsChangeListener callback = mPermissionListeners
22719                            .getBroadcastItem(i);
22720                    try {
22721                        callback.onPermissionsChanged(uid);
22722                    } catch (RemoteException e) {
22723                        Log.e(TAG, "Permission listener is dead", e);
22724                    }
22725                }
22726            } finally {
22727                mPermissionListeners.finishBroadcast();
22728            }
22729        }
22730    }
22731
22732    private class PackageManagerInternalImpl extends PackageManagerInternal {
22733        @Override
22734        public void setLocationPackagesProvider(PackagesProvider provider) {
22735            synchronized (mPackages) {
22736                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22737            }
22738        }
22739
22740        @Override
22741        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22742            synchronized (mPackages) {
22743                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22744            }
22745        }
22746
22747        @Override
22748        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22749            synchronized (mPackages) {
22750                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22751            }
22752        }
22753
22754        @Override
22755        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22756            synchronized (mPackages) {
22757                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22758            }
22759        }
22760
22761        @Override
22762        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22763            synchronized (mPackages) {
22764                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22765            }
22766        }
22767
22768        @Override
22769        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22770            synchronized (mPackages) {
22771                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22772            }
22773        }
22774
22775        @Override
22776        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22777            synchronized (mPackages) {
22778                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22779                        packageName, userId);
22780            }
22781        }
22782
22783        @Override
22784        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22785            synchronized (mPackages) {
22786                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22787                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22788                        packageName, userId);
22789            }
22790        }
22791
22792        @Override
22793        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22794            synchronized (mPackages) {
22795                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22796                        packageName, userId);
22797            }
22798        }
22799
22800        @Override
22801        public void setKeepUninstalledPackages(final List<String> packageList) {
22802            Preconditions.checkNotNull(packageList);
22803            List<String> removedFromList = null;
22804            synchronized (mPackages) {
22805                if (mKeepUninstalledPackages != null) {
22806                    final int packagesCount = mKeepUninstalledPackages.size();
22807                    for (int i = 0; i < packagesCount; i++) {
22808                        String oldPackage = mKeepUninstalledPackages.get(i);
22809                        if (packageList != null && packageList.contains(oldPackage)) {
22810                            continue;
22811                        }
22812                        if (removedFromList == null) {
22813                            removedFromList = new ArrayList<>();
22814                        }
22815                        removedFromList.add(oldPackage);
22816                    }
22817                }
22818                mKeepUninstalledPackages = new ArrayList<>(packageList);
22819                if (removedFromList != null) {
22820                    final int removedCount = removedFromList.size();
22821                    for (int i = 0; i < removedCount; i++) {
22822                        deletePackageIfUnusedLPr(removedFromList.get(i));
22823                    }
22824                }
22825            }
22826        }
22827
22828        @Override
22829        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22830            synchronized (mPackages) {
22831                // If we do not support permission review, done.
22832                if (!mPermissionReviewRequired) {
22833                    return false;
22834                }
22835
22836                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22837                if (packageSetting == null) {
22838                    return false;
22839                }
22840
22841                // Permission review applies only to apps not supporting the new permission model.
22842                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22843                    return false;
22844                }
22845
22846                // Legacy apps have the permission and get user consent on launch.
22847                PermissionsState permissionsState = packageSetting.getPermissionsState();
22848                return permissionsState.isPermissionReviewRequired(userId);
22849            }
22850        }
22851
22852        @Override
22853        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22854            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22855        }
22856
22857        @Override
22858        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22859                int userId) {
22860            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22861        }
22862
22863        @Override
22864        public void setDeviceAndProfileOwnerPackages(
22865                int deviceOwnerUserId, String deviceOwnerPackage,
22866                SparseArray<String> profileOwnerPackages) {
22867            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22868                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22869        }
22870
22871        @Override
22872        public boolean isPackageDataProtected(int userId, String packageName) {
22873            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22874        }
22875
22876        @Override
22877        public boolean isPackageEphemeral(int userId, String packageName) {
22878            synchronized (mPackages) {
22879                final PackageSetting ps = mSettings.mPackages.get(packageName);
22880                return ps != null ? ps.getInstantApp(userId) : false;
22881            }
22882        }
22883
22884        @Override
22885        public boolean wasPackageEverLaunched(String packageName, int userId) {
22886            synchronized (mPackages) {
22887                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22888            }
22889        }
22890
22891        @Override
22892        public void grantRuntimePermission(String packageName, String name, int userId,
22893                boolean overridePolicy) {
22894            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22895                    overridePolicy);
22896        }
22897
22898        @Override
22899        public void revokeRuntimePermission(String packageName, String name, int userId,
22900                boolean overridePolicy) {
22901            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
22902                    overridePolicy);
22903        }
22904
22905        @Override
22906        public String getNameForUid(int uid) {
22907            return PackageManagerService.this.getNameForUid(uid);
22908        }
22909
22910        @Override
22911        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
22912                Intent origIntent, String resolvedType, Intent launchIntent,
22913                String callingPackage, int userId) {
22914            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
22915                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
22916        }
22917
22918        @Override
22919        public void grantEphemeralAccess(int userId, Intent intent,
22920                int targetAppId, int ephemeralAppId) {
22921            synchronized (mPackages) {
22922                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
22923                        targetAppId, ephemeralAppId);
22924            }
22925        }
22926
22927        @Override
22928        public void pruneInstantApps() {
22929            synchronized (mPackages) {
22930                mInstantAppRegistry.pruneInstantAppsLPw();
22931            }
22932        }
22933
22934        @Override
22935        public String getSetupWizardPackageName() {
22936            return mSetupWizardPackage;
22937        }
22938
22939        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
22940            if (policy != null) {
22941                mExternalSourcesPolicy = policy;
22942            }
22943        }
22944
22945        @Override
22946        public boolean isPackagePersistent(String packageName) {
22947            synchronized (mPackages) {
22948                PackageParser.Package pkg = mPackages.get(packageName);
22949                return pkg != null
22950                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
22951                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
22952                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
22953                        : false;
22954            }
22955        }
22956
22957        @Override
22958        public List<PackageInfo> getOverlayPackages(int userId) {
22959            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
22960            synchronized (mPackages) {
22961                for (PackageParser.Package p : mPackages.values()) {
22962                    if (p.mOverlayTarget != null) {
22963                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
22964                        if (pkg != null) {
22965                            overlayPackages.add(pkg);
22966                        }
22967                    }
22968                }
22969            }
22970            return overlayPackages;
22971        }
22972
22973        @Override
22974        public List<String> getTargetPackageNames(int userId) {
22975            List<String> targetPackages = new ArrayList<>();
22976            synchronized (mPackages) {
22977                for (PackageParser.Package p : mPackages.values()) {
22978                    if (p.mOverlayTarget == null) {
22979                        targetPackages.add(p.packageName);
22980                    }
22981                }
22982            }
22983            return targetPackages;
22984        }
22985
22986
22987        @Override
22988        public boolean setEnabledOverlayPackages(int userId, String targetPackageName,
22989                List<String> overlayPackageNames) {
22990            // TODO: implement when we integrate OMS properly
22991            return false;
22992        }
22993    }
22994
22995    @Override
22996    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
22997        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
22998        synchronized (mPackages) {
22999            final long identity = Binder.clearCallingIdentity();
23000            try {
23001                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23002                        packageNames, userId);
23003            } finally {
23004                Binder.restoreCallingIdentity(identity);
23005            }
23006        }
23007    }
23008
23009    @Override
23010    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23011        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23012        synchronized (mPackages) {
23013            final long identity = Binder.clearCallingIdentity();
23014            try {
23015                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23016                        packageNames, userId);
23017            } finally {
23018                Binder.restoreCallingIdentity(identity);
23019            }
23020        }
23021    }
23022
23023    private static void enforceSystemOrPhoneCaller(String tag) {
23024        int callingUid = Binder.getCallingUid();
23025        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23026            throw new SecurityException(
23027                    "Cannot call " + tag + " from UID " + callingUid);
23028        }
23029    }
23030
23031    boolean isHistoricalPackageUsageAvailable() {
23032        return mPackageUsage.isHistoricalPackageUsageAvailable();
23033    }
23034
23035    /**
23036     * Return a <b>copy</b> of the collection of packages known to the package manager.
23037     * @return A copy of the values of mPackages.
23038     */
23039    Collection<PackageParser.Package> getPackages() {
23040        synchronized (mPackages) {
23041            return new ArrayList<>(mPackages.values());
23042        }
23043    }
23044
23045    /**
23046     * Logs process start information (including base APK hash) to the security log.
23047     * @hide
23048     */
23049    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23050            String apkFile, int pid) {
23051        if (!SecurityLog.isLoggingEnabled()) {
23052            return;
23053        }
23054        Bundle data = new Bundle();
23055        data.putLong("startTimestamp", System.currentTimeMillis());
23056        data.putString("processName", processName);
23057        data.putInt("uid", uid);
23058        data.putString("seinfo", seinfo);
23059        data.putString("apkFile", apkFile);
23060        data.putInt("pid", pid);
23061        Message msg = mProcessLoggingHandler.obtainMessage(
23062                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23063        msg.setData(data);
23064        mProcessLoggingHandler.sendMessage(msg);
23065    }
23066
23067    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23068        return mCompilerStats.getPackageStats(pkgName);
23069    }
23070
23071    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23072        return getOrCreateCompilerPackageStats(pkg.packageName);
23073    }
23074
23075    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23076        return mCompilerStats.getOrCreatePackageStats(pkgName);
23077    }
23078
23079    public void deleteCompilerPackageStats(String pkgName) {
23080        mCompilerStats.deletePackageStats(pkgName);
23081    }
23082
23083    @Override
23084    public int getInstallReason(String packageName, int userId) {
23085        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23086                true /* requireFullPermission */, false /* checkShell */,
23087                "get install reason");
23088        synchronized (mPackages) {
23089            final PackageSetting ps = mSettings.mPackages.get(packageName);
23090            if (ps != null) {
23091                return ps.getInstallReason(userId);
23092            }
23093        }
23094        return PackageManager.INSTALL_REASON_UNKNOWN;
23095    }
23096
23097    @Override
23098    public boolean canRequestPackageInstalls(String packageName, int userId) {
23099        int callingUid = Binder.getCallingUid();
23100        int uid = getPackageUid(packageName, 0, userId);
23101        if (callingUid != uid && callingUid != Process.ROOT_UID
23102                && callingUid != Process.SYSTEM_UID) {
23103            throw new SecurityException(
23104                    "Caller uid " + callingUid + " does not own package " + packageName);
23105        }
23106        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23107        if (info == null) {
23108            return false;
23109        }
23110        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23111            throw new UnsupportedOperationException(
23112                    "Operation only supported on apps targeting Android O or higher");
23113        }
23114        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23115        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23116        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23117            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23118        }
23119        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23120            return false;
23121        }
23122        if (mExternalSourcesPolicy != null) {
23123            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23124            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23125                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23126            }
23127        }
23128        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23129    }
23130}
23131