PackageManagerService.java revision 533c9ff58d7649c6056f12c85b4122970f77236b
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.EphemeralRequest;
132import android.content.pm.EphemeralResolveInfo;
133import android.content.pm.AuxiliaryResolveInfo;
134import android.content.pm.FallbackCategoryProvider;
135import android.content.pm.FeatureInfo;
136import android.content.pm.IOnPermissionsChangeListener;
137import android.content.pm.IPackageDataObserver;
138import android.content.pm.IPackageDeleteObserver;
139import android.content.pm.IPackageDeleteObserver2;
140import android.content.pm.IPackageInstallObserver2;
141import android.content.pm.IPackageInstaller;
142import android.content.pm.IPackageManager;
143import android.content.pm.IPackageMoveObserver;
144import android.content.pm.IPackageStatsObserver;
145import android.content.pm.InstantAppInfo;
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.StorageEventListener;
208import android.os.storage.StorageManager;
209import android.os.storage.StorageManagerInternal;
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.service.pm.PackageServiceDumpProto;
217import android.system.ErrnoException;
218import android.system.Os;
219import android.text.TextUtils;
220import android.text.format.DateUtils;
221import android.util.ArrayMap;
222import android.util.ArraySet;
223import android.util.Base64;
224import android.util.DisplayMetrics;
225import android.util.EventLog;
226import android.util.ExceptionUtils;
227import android.util.Log;
228import android.util.LogPrinter;
229import android.util.MathUtils;
230import android.util.PackageUtils;
231import android.util.Pair;
232import android.util.PrintStreamPrinter;
233import android.util.Slog;
234import android.util.SparseArray;
235import android.util.SparseBooleanArray;
236import android.util.SparseIntArray;
237import android.util.Xml;
238import android.util.jar.StrictJarFile;
239import android.util.proto.ProtoOutputStream;
240import android.view.Display;
241
242import com.android.internal.R;
243import com.android.internal.annotations.GuardedBy;
244import com.android.internal.app.IMediaContainerService;
245import com.android.internal.app.ResolverActivity;
246import com.android.internal.content.NativeLibraryHelper;
247import com.android.internal.content.PackageHelper;
248import com.android.internal.logging.MetricsLogger;
249import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
250import com.android.internal.os.IParcelFileDescriptorFactory;
251import com.android.internal.os.RoSystemProperties;
252import com.android.internal.os.SomeArgs;
253import com.android.internal.os.Zygote;
254import com.android.internal.telephony.CarrierAppUtils;
255import com.android.internal.util.ArrayUtils;
256import com.android.internal.util.ConcurrentUtils;
257import com.android.internal.util.FastPrintWriter;
258import com.android.internal.util.FastXmlSerializer;
259import com.android.internal.util.IndentingPrintWriter;
260import com.android.internal.util.Preconditions;
261import com.android.internal.util.XmlUtils;
262import com.android.server.AttributeCache;
263import com.android.server.BackgroundDexOptJobService;
264import com.android.server.DeviceIdleController;
265import com.android.server.EventLogTags;
266import com.android.server.FgThread;
267import com.android.server.IntentResolver;
268import com.android.server.LocalServices;
269import com.android.server.ServiceThread;
270import com.android.server.SystemConfig;
271import com.android.server.SystemServerInitThreadPool;
272import com.android.server.Watchdog;
273import com.android.server.net.NetworkPolicyManagerInternal;
274import com.android.server.pm.Installer.InstallerException;
275import com.android.server.pm.PermissionsState.PermissionState;
276import com.android.server.pm.Settings.DatabaseVersion;
277import com.android.server.pm.Settings.VersionInfo;
278import com.android.server.pm.dex.DexManager;
279import com.android.server.storage.DeviceStorageMonitorInternal;
280
281import dalvik.system.CloseGuard;
282import dalvik.system.DexFile;
283import dalvik.system.VMRuntime;
284
285import libcore.io.IoUtils;
286import libcore.util.EmptyArray;
287
288import org.xmlpull.v1.XmlPullParser;
289import org.xmlpull.v1.XmlPullParserException;
290import org.xmlpull.v1.XmlSerializer;
291
292import java.io.BufferedOutputStream;
293import java.io.BufferedReader;
294import java.io.ByteArrayInputStream;
295import java.io.ByteArrayOutputStream;
296import java.io.File;
297import java.io.FileDescriptor;
298import java.io.FileInputStream;
299import java.io.FileNotFoundException;
300import java.io.FileOutputStream;
301import java.io.FileReader;
302import java.io.FilenameFilter;
303import java.io.IOException;
304import java.io.PrintWriter;
305import java.nio.charset.StandardCharsets;
306import java.security.DigestInputStream;
307import java.security.MessageDigest;
308import java.security.NoSuchAlgorithmException;
309import java.security.PublicKey;
310import java.security.SecureRandom;
311import java.security.cert.Certificate;
312import java.security.cert.CertificateEncodingException;
313import java.security.cert.CertificateException;
314import java.text.SimpleDateFormat;
315import java.util.ArrayList;
316import java.util.Arrays;
317import java.util.Collection;
318import java.util.Collections;
319import java.util.Comparator;
320import java.util.Date;
321import java.util.HashMap;
322import java.util.HashSet;
323import java.util.Iterator;
324import java.util.List;
325import java.util.Map;
326import java.util.Objects;
327import java.util.Set;
328import java.util.concurrent.CountDownLatch;
329import java.util.concurrent.Future;
330import java.util.concurrent.TimeUnit;
331import java.util.concurrent.atomic.AtomicBoolean;
332import java.util.concurrent.atomic.AtomicInteger;
333
334/**
335 * Keep track of all those APKs everywhere.
336 * <p>
337 * Internally there are two important locks:
338 * <ul>
339 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
340 * and other related state. It is a fine-grained lock that should only be held
341 * momentarily, as it's one of the most contended locks in the system.
342 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
343 * operations typically involve heavy lifting of application data on disk. Since
344 * {@code installd} is single-threaded, and it's operations can often be slow,
345 * this lock should never be acquired while already holding {@link #mPackages}.
346 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
347 * holding {@link #mInstallLock}.
348 * </ul>
349 * Many internal methods rely on the caller to hold the appropriate locks, and
350 * this contract is expressed through method name suffixes:
351 * <ul>
352 * <li>fooLI(): the caller must hold {@link #mInstallLock}
353 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
354 * being modified must be frozen
355 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
356 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
357 * </ul>
358 * <p>
359 * Because this class is very central to the platform's security; please run all
360 * CTS and unit tests whenever making modifications:
361 *
362 * <pre>
363 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
364 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
365 * </pre>
366 */
367public class PackageManagerService extends IPackageManager.Stub {
368    static final String TAG = "PackageManager";
369    static final boolean DEBUG_SETTINGS = false;
370    static final boolean DEBUG_PREFERRED = false;
371    static final boolean DEBUG_UPGRADE = false;
372    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
373    private static final boolean DEBUG_BACKUP = false;
374    private static final boolean DEBUG_INSTALL = false;
375    private static final boolean DEBUG_REMOVE = false;
376    private static final boolean DEBUG_BROADCASTS = false;
377    private static final boolean DEBUG_SHOW_INFO = false;
378    private static final boolean DEBUG_PACKAGE_INFO = false;
379    private static final boolean DEBUG_INTENT_MATCHING = false;
380    private static final boolean DEBUG_PACKAGE_SCANNING = false;
381    private static final boolean DEBUG_VERIFY = false;
382    private static final boolean DEBUG_FILTERS = false;
383
384    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
385    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
386    // user, but by default initialize to this.
387    public static final boolean DEBUG_DEXOPT = false;
388
389    private static final boolean DEBUG_ABI_SELECTION = false;
390    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
391    private static final boolean DEBUG_TRIAGED_MISSING = false;
392    private static final boolean DEBUG_APP_DATA = false;
393
394    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
395    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
396
397    private static final boolean DISABLE_EPHEMERAL_APPS = false;
398    private static final boolean HIDE_EPHEMERAL_APIS = false;
399
400    private static final boolean ENABLE_FREE_CACHE_V2 =
401            SystemProperties.getBoolean("fw.free_cache_v2", false);
402
403    private static final int RADIO_UID = Process.PHONE_UID;
404    private static final int LOG_UID = Process.LOG_UID;
405    private static final int NFC_UID = Process.NFC_UID;
406    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
407    private static final int SHELL_UID = Process.SHELL_UID;
408
409    // Cap the size of permission trees that 3rd party apps can define
410    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
411
412    // Suffix used during package installation when copying/moving
413    // package apks to install directory.
414    private static final String INSTALL_PACKAGE_SUFFIX = "-";
415
416    static final int SCAN_NO_DEX = 1<<1;
417    static final int SCAN_FORCE_DEX = 1<<2;
418    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
419    static final int SCAN_NEW_INSTALL = 1<<4;
420    static final int SCAN_UPDATE_TIME = 1<<5;
421    static final int SCAN_BOOTING = 1<<6;
422    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
423    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
424    static final int SCAN_REPLACING = 1<<9;
425    static final int SCAN_REQUIRE_KNOWN = 1<<10;
426    static final int SCAN_MOVE = 1<<11;
427    static final int SCAN_INITIAL = 1<<12;
428    static final int SCAN_CHECK_ONLY = 1<<13;
429    static final int SCAN_DONT_KILL_APP = 1<<14;
430    static final int SCAN_IGNORE_FROZEN = 1<<15;
431    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
432    static final int SCAN_AS_INSTANT_APP = 1<<17;
433    static final int SCAN_AS_FULL_APP = 1<<18;
434    /** Should not be with the scan flags */
435    static final int FLAGS_REMOVE_CHATTY = 1<<31;
436
437    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
438
439    private static final int[] EMPTY_INT_ARRAY = new int[0];
440
441    /**
442     * Timeout (in milliseconds) after which the watchdog should declare that
443     * our handler thread is wedged.  The usual default for such things is one
444     * minute but we sometimes do very lengthy I/O operations on this thread,
445     * such as installing multi-gigabyte applications, so ours needs to be longer.
446     */
447    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
448
449    /**
450     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
451     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
452     * settings entry if available, otherwise we use the hardcoded default.  If it's been
453     * more than this long since the last fstrim, we force one during the boot sequence.
454     *
455     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
456     * one gets run at the next available charging+idle time.  This final mandatory
457     * no-fstrim check kicks in only of the other scheduling criteria is never met.
458     */
459    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
460
461    /**
462     * Whether verification is enabled by default.
463     */
464    private static final boolean DEFAULT_VERIFY_ENABLE = true;
465
466    /**
467     * The default maximum time to wait for the verification agent to return in
468     * milliseconds.
469     */
470    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
471
472    /**
473     * The default response for package verification timeout.
474     *
475     * This can be either PackageManager.VERIFICATION_ALLOW or
476     * PackageManager.VERIFICATION_REJECT.
477     */
478    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
479
480    static final String PLATFORM_PACKAGE_NAME = "android";
481
482    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
483
484    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
485            DEFAULT_CONTAINER_PACKAGE,
486            "com.android.defcontainer.DefaultContainerService");
487
488    private static final String KILL_APP_REASON_GIDS_CHANGED =
489            "permission grant or revoke changed gids";
490
491    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
492            "permissions revoked";
493
494    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
495
496    private static final String PACKAGE_SCHEME = "package";
497
498    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
499    /**
500     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
501     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
502     * VENDOR_OVERLAY_DIR.
503     */
504    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
505    /**
506     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
507     * is in VENDOR_OVERLAY_THEME_PROPERTY.
508     */
509    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
510            = "persist.vendor.overlay.theme";
511
512    /** Permission grant: not grant the permission. */
513    private static final int GRANT_DENIED = 1;
514
515    /** Permission grant: grant the permission as an install permission. */
516    private static final int GRANT_INSTALL = 2;
517
518    /** Permission grant: grant the permission as a runtime one. */
519    private static final int GRANT_RUNTIME = 3;
520
521    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
522    private static final int GRANT_UPGRADE = 4;
523
524    /** Canonical intent used to identify what counts as a "web browser" app */
525    private static final Intent sBrowserIntent;
526    static {
527        sBrowserIntent = new Intent();
528        sBrowserIntent.setAction(Intent.ACTION_VIEW);
529        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
530        sBrowserIntent.setData(Uri.parse("http:"));
531    }
532
533    /**
534     * The set of all protected actions [i.e. those actions for which a high priority
535     * intent filter is disallowed].
536     */
537    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
538    static {
539        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
540        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
541        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
542        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
543    }
544
545    // Compilation reasons.
546    public static final int REASON_FIRST_BOOT = 0;
547    public static final int REASON_BOOT = 1;
548    public static final int REASON_INSTALL = 2;
549    public static final int REASON_BACKGROUND_DEXOPT = 3;
550    public static final int REASON_AB_OTA = 4;
551    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
552    public static final int REASON_SHARED_APK = 6;
553    public static final int REASON_FORCED_DEXOPT = 7;
554    public static final int REASON_CORE_APP = 8;
555
556    public static final int REASON_LAST = REASON_CORE_APP;
557
558    /** All dangerous permission names in the same order as the events in MetricsEvent */
559    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
560            Manifest.permission.READ_CALENDAR,
561            Manifest.permission.WRITE_CALENDAR,
562            Manifest.permission.CAMERA,
563            Manifest.permission.READ_CONTACTS,
564            Manifest.permission.WRITE_CONTACTS,
565            Manifest.permission.GET_ACCOUNTS,
566            Manifest.permission.ACCESS_FINE_LOCATION,
567            Manifest.permission.ACCESS_COARSE_LOCATION,
568            Manifest.permission.RECORD_AUDIO,
569            Manifest.permission.READ_PHONE_STATE,
570            Manifest.permission.CALL_PHONE,
571            Manifest.permission.READ_CALL_LOG,
572            Manifest.permission.WRITE_CALL_LOG,
573            Manifest.permission.ADD_VOICEMAIL,
574            Manifest.permission.USE_SIP,
575            Manifest.permission.PROCESS_OUTGOING_CALLS,
576            Manifest.permission.READ_CELL_BROADCASTS,
577            Manifest.permission.BODY_SENSORS,
578            Manifest.permission.SEND_SMS,
579            Manifest.permission.RECEIVE_SMS,
580            Manifest.permission.READ_SMS,
581            Manifest.permission.RECEIVE_WAP_PUSH,
582            Manifest.permission.RECEIVE_MMS,
583            Manifest.permission.READ_EXTERNAL_STORAGE,
584            Manifest.permission.WRITE_EXTERNAL_STORAGE,
585            Manifest.permission.READ_PHONE_NUMBER);
586
587
588    /**
589     * Version number for the package parser cache. Increment this whenever the format or
590     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
591     */
592    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
593
594    /**
595     * Whether the package parser cache is enabled.
596     */
597    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
598
599    final ServiceThread mHandlerThread;
600
601    final PackageHandler mHandler;
602
603    private final ProcessLoggingHandler mProcessLoggingHandler;
604
605    /**
606     * Messages for {@link #mHandler} that need to wait for system ready before
607     * being dispatched.
608     */
609    private ArrayList<Message> mPostSystemReadyMessages;
610
611    final int mSdkVersion = Build.VERSION.SDK_INT;
612
613    final Context mContext;
614    final boolean mFactoryTest;
615    final boolean mOnlyCore;
616    final DisplayMetrics mMetrics;
617    final int mDefParseFlags;
618    final String[] mSeparateProcesses;
619    final boolean mIsUpgrade;
620    final boolean mIsPreNUpgrade;
621    final boolean mIsPreNMR1Upgrade;
622
623    @GuardedBy("mPackages")
624    private boolean mDexOptDialogShown;
625
626    /** The location for ASEC container files on internal storage. */
627    final String mAsecInternalPath;
628
629    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
630    // LOCK HELD.  Can be called with mInstallLock held.
631    @GuardedBy("mInstallLock")
632    final Installer mInstaller;
633
634    /** Directory where installed third-party apps stored */
635    final File mAppInstallDir;
636
637    /**
638     * Directory to which applications installed internally have their
639     * 32 bit native libraries copied.
640     */
641    private File mAppLib32InstallDir;
642
643    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
644    // apps.
645    final File mDrmAppPrivateInstallDir;
646
647    // ----------------------------------------------------------------
648
649    // Lock for state used when installing and doing other long running
650    // operations.  Methods that must be called with this lock held have
651    // the suffix "LI".
652    final Object mInstallLock = new Object();
653
654    // ----------------------------------------------------------------
655
656    // Keys are String (package name), values are Package.  This also serves
657    // as the lock for the global state.  Methods that must be called with
658    // this lock held have the prefix "LP".
659    @GuardedBy("mPackages")
660    final ArrayMap<String, PackageParser.Package> mPackages =
661            new ArrayMap<String, PackageParser.Package>();
662
663    final ArrayMap<String, Set<String>> mKnownCodebase =
664            new ArrayMap<String, Set<String>>();
665
666    // List of APK paths to load for each user and package. This data is never
667    // persisted by the package manager. Instead, the overlay manager will
668    // ensure the data is up-to-date in runtime.
669    @GuardedBy("mPackages")
670    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
671        new SparseArray<ArrayMap<String, ArrayList<String>>>();
672
673    /**
674     * Tracks new system packages [received in an OTA] that we expect to
675     * find updated user-installed versions. Keys are package name, values
676     * are package location.
677     */
678    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
679    /**
680     * Tracks high priority intent filters for protected actions. During boot, certain
681     * filter actions are protected and should never be allowed to have a high priority
682     * intent filter for them. However, there is one, and only one exception -- the
683     * setup wizard. It must be able to define a high priority intent filter for these
684     * actions to ensure there are no escapes from the wizard. We need to delay processing
685     * of these during boot as we need to look at all of the system packages in order
686     * to know which component is the setup wizard.
687     */
688    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
689    /**
690     * Whether or not processing protected filters should be deferred.
691     */
692    private boolean mDeferProtectedFilters = true;
693
694    /**
695     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
696     */
697    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
698    /**
699     * Whether or not system app permissions should be promoted from install to runtime.
700     */
701    boolean mPromoteSystemApps;
702
703    @GuardedBy("mPackages")
704    final Settings mSettings;
705
706    /**
707     * Set of package names that are currently "frozen", which means active
708     * surgery is being done on the code/data for that package. The platform
709     * will refuse to launch frozen packages to avoid race conditions.
710     *
711     * @see PackageFreezer
712     */
713    @GuardedBy("mPackages")
714    final ArraySet<String> mFrozenPackages = new ArraySet<>();
715
716    final ProtectedPackages mProtectedPackages;
717
718    boolean mFirstBoot;
719
720    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
721
722    // System configuration read by SystemConfig.
723    final int[] mGlobalGids;
724    final SparseArray<ArraySet<String>> mSystemPermissions;
725    @GuardedBy("mAvailableFeatures")
726    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
727
728    // If mac_permissions.xml was found for seinfo labeling.
729    boolean mFoundPolicyFile;
730
731    private final InstantAppRegistry mInstantAppRegistry;
732
733    @GuardedBy("mPackages")
734    int mChangedPackagesSequenceNumber;
735    /**
736     * List of changed [installed, removed or updated] packages.
737     * mapping from user id -> sequence number -> package name
738     */
739    @GuardedBy("mPackages")
740    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
741    /**
742     * The sequence number of the last change to a package.
743     * mapping from user id -> package name -> sequence number
744     */
745    @GuardedBy("mPackages")
746    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
747
748    public static final class SharedLibraryEntry {
749        public final String path;
750        public final String apk;
751        public final SharedLibraryInfo info;
752
753        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
754                String declaringPackageName, int declaringPackageVersionCode) {
755            path = _path;
756            apk = _apk;
757            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
758                    declaringPackageName, declaringPackageVersionCode), null);
759        }
760    }
761
762    // Currently known shared libraries.
763    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
764    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
765            new ArrayMap<>();
766
767    // All available activities, for your resolving pleasure.
768    final ActivityIntentResolver mActivities =
769            new ActivityIntentResolver();
770
771    // All available receivers, for your resolving pleasure.
772    final ActivityIntentResolver mReceivers =
773            new ActivityIntentResolver();
774
775    // All available services, for your resolving pleasure.
776    final ServiceIntentResolver mServices = new ServiceIntentResolver();
777
778    // All available providers, for your resolving pleasure.
779    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
780
781    // Mapping from provider base names (first directory in content URI codePath)
782    // to the provider information.
783    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
784            new ArrayMap<String, PackageParser.Provider>();
785
786    // Mapping from instrumentation class names to info about them.
787    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
788            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
789
790    // Mapping from permission names to info about them.
791    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
792            new ArrayMap<String, PackageParser.PermissionGroup>();
793
794    // Packages whose data we have transfered into another package, thus
795    // should no longer exist.
796    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
797
798    // Broadcast actions that are only available to the system.
799    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
800
801    /** List of packages waiting for verification. */
802    final SparseArray<PackageVerificationState> mPendingVerification
803            = new SparseArray<PackageVerificationState>();
804
805    /** Set of packages associated with each app op permission. */
806    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
807
808    final PackageInstallerService mInstallerService;
809
810    private final PackageDexOptimizer mPackageDexOptimizer;
811    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
812    // is used by other apps).
813    private final DexManager mDexManager;
814
815    private AtomicInteger mNextMoveId = new AtomicInteger();
816    private final MoveCallbacks mMoveCallbacks;
817
818    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
819
820    // Cache of users who need badging.
821    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
822
823    /** Token for keys in mPendingVerification. */
824    private int mPendingVerificationToken = 0;
825
826    volatile boolean mSystemReady;
827    volatile boolean mSafeMode;
828    volatile boolean mHasSystemUidErrors;
829
830    ApplicationInfo mAndroidApplication;
831    final ActivityInfo mResolveActivity = new ActivityInfo();
832    final ResolveInfo mResolveInfo = new ResolveInfo();
833    ComponentName mResolveComponentName;
834    PackageParser.Package mPlatformPackage;
835    ComponentName mCustomResolverComponentName;
836
837    boolean mResolverReplaced = false;
838
839    private final @Nullable ComponentName mIntentFilterVerifierComponent;
840    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
841
842    private int mIntentFilterVerificationToken = 0;
843
844    /** The service connection to the ephemeral resolver */
845    final EphemeralResolverConnection mInstantAppResolverConnection;
846
847    /** Component used to install ephemeral applications */
848    ComponentName mInstantAppInstallerComponent;
849    final ActivityInfo mInstantAppInstallerActivity = new ActivityInfo();
850    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
851
852    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
853            = new SparseArray<IntentFilterVerificationState>();
854
855    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
856
857    // List of packages names to keep cached, even if they are uninstalled for all users
858    private List<String> mKeepUninstalledPackages;
859
860    private UserManagerInternal mUserManagerInternal;
861
862    private DeviceIdleController.LocalService mDeviceIdleController;
863
864    private File mCacheDir;
865
866    private ArraySet<String> mPrivappPermissionsViolations;
867
868    private Future<?> mPrepareAppDataFuture;
869
870    private static class IFVerificationParams {
871        PackageParser.Package pkg;
872        boolean replacing;
873        int userId;
874        int verifierUid;
875
876        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
877                int _userId, int _verifierUid) {
878            pkg = _pkg;
879            replacing = _replacing;
880            userId = _userId;
881            replacing = _replacing;
882            verifierUid = _verifierUid;
883        }
884    }
885
886    private interface IntentFilterVerifier<T extends IntentFilter> {
887        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
888                                               T filter, String packageName);
889        void startVerifications(int userId);
890        void receiveVerificationResponse(int verificationId);
891    }
892
893    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
894        private Context mContext;
895        private ComponentName mIntentFilterVerifierComponent;
896        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
897
898        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
899            mContext = context;
900            mIntentFilterVerifierComponent = verifierComponent;
901        }
902
903        private String getDefaultScheme() {
904            return IntentFilter.SCHEME_HTTPS;
905        }
906
907        @Override
908        public void startVerifications(int userId) {
909            // Launch verifications requests
910            int count = mCurrentIntentFilterVerifications.size();
911            for (int n=0; n<count; n++) {
912                int verificationId = mCurrentIntentFilterVerifications.get(n);
913                final IntentFilterVerificationState ivs =
914                        mIntentFilterVerificationStates.get(verificationId);
915
916                String packageName = ivs.getPackageName();
917
918                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
919                final int filterCount = filters.size();
920                ArraySet<String> domainsSet = new ArraySet<>();
921                for (int m=0; m<filterCount; m++) {
922                    PackageParser.ActivityIntentInfo filter = filters.get(m);
923                    domainsSet.addAll(filter.getHostsList());
924                }
925                synchronized (mPackages) {
926                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
927                            packageName, domainsSet) != null) {
928                        scheduleWriteSettingsLocked();
929                    }
930                }
931                sendVerificationRequest(userId, verificationId, ivs);
932            }
933            mCurrentIntentFilterVerifications.clear();
934        }
935
936        private void sendVerificationRequest(int userId, int verificationId,
937                IntentFilterVerificationState ivs) {
938
939            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
940            verificationIntent.putExtra(
941                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
942                    verificationId);
943            verificationIntent.putExtra(
944                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
945                    getDefaultScheme());
946            verificationIntent.putExtra(
947                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
948                    ivs.getHostsString());
949            verificationIntent.putExtra(
950                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
951                    ivs.getPackageName());
952            verificationIntent.setComponent(mIntentFilterVerifierComponent);
953            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
954
955            UserHandle user = new UserHandle(userId);
956            mContext.sendBroadcastAsUser(verificationIntent, user);
957            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
958                    "Sending IntentFilter verification broadcast");
959        }
960
961        public void receiveVerificationResponse(int verificationId) {
962            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
963
964            final boolean verified = ivs.isVerified();
965
966            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
967            final int count = filters.size();
968            if (DEBUG_DOMAIN_VERIFICATION) {
969                Slog.i(TAG, "Received verification response " + verificationId
970                        + " for " + count + " filters, verified=" + verified);
971            }
972            for (int n=0; n<count; n++) {
973                PackageParser.ActivityIntentInfo filter = filters.get(n);
974                filter.setVerified(verified);
975
976                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
977                        + " verified with result:" + verified + " and hosts:"
978                        + ivs.getHostsString());
979            }
980
981            mIntentFilterVerificationStates.remove(verificationId);
982
983            final String packageName = ivs.getPackageName();
984            IntentFilterVerificationInfo ivi = null;
985
986            synchronized (mPackages) {
987                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
988            }
989            if (ivi == null) {
990                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
991                        + verificationId + " packageName:" + packageName);
992                return;
993            }
994            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
995                    "Updating IntentFilterVerificationInfo for package " + packageName
996                            +" verificationId:" + verificationId);
997
998            synchronized (mPackages) {
999                if (verified) {
1000                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1001                } else {
1002                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1003                }
1004                scheduleWriteSettingsLocked();
1005
1006                final int userId = ivs.getUserId();
1007                if (userId != UserHandle.USER_ALL) {
1008                    final int userStatus =
1009                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1010
1011                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1012                    boolean needUpdate = false;
1013
1014                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1015                    // already been set by the User thru the Disambiguation dialog
1016                    switch (userStatus) {
1017                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1018                            if (verified) {
1019                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1020                            } else {
1021                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1022                            }
1023                            needUpdate = true;
1024                            break;
1025
1026                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1027                            if (verified) {
1028                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1029                                needUpdate = true;
1030                            }
1031                            break;
1032
1033                        default:
1034                            // Nothing to do
1035                    }
1036
1037                    if (needUpdate) {
1038                        mSettings.updateIntentFilterVerificationStatusLPw(
1039                                packageName, updatedStatus, userId);
1040                        scheduleWritePackageRestrictionsLocked(userId);
1041                    }
1042                }
1043            }
1044        }
1045
1046        @Override
1047        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1048                    ActivityIntentInfo filter, String packageName) {
1049            if (!hasValidDomains(filter)) {
1050                return false;
1051            }
1052            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1053            if (ivs == null) {
1054                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1055                        packageName);
1056            }
1057            if (DEBUG_DOMAIN_VERIFICATION) {
1058                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1059            }
1060            ivs.addFilter(filter);
1061            return true;
1062        }
1063
1064        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1065                int userId, int verificationId, String packageName) {
1066            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1067                    verifierUid, userId, packageName);
1068            ivs.setPendingState();
1069            synchronized (mPackages) {
1070                mIntentFilterVerificationStates.append(verificationId, ivs);
1071                mCurrentIntentFilterVerifications.add(verificationId);
1072            }
1073            return ivs;
1074        }
1075    }
1076
1077    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1078        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1079                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1080                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1081    }
1082
1083    // Set of pending broadcasts for aggregating enable/disable of components.
1084    static class PendingPackageBroadcasts {
1085        // for each user id, a map of <package name -> components within that package>
1086        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1087
1088        public PendingPackageBroadcasts() {
1089            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1090        }
1091
1092        public ArrayList<String> get(int userId, String packageName) {
1093            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1094            return packages.get(packageName);
1095        }
1096
1097        public void put(int userId, String packageName, ArrayList<String> components) {
1098            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1099            packages.put(packageName, components);
1100        }
1101
1102        public void remove(int userId, String packageName) {
1103            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1104            if (packages != null) {
1105                packages.remove(packageName);
1106            }
1107        }
1108
1109        public void remove(int userId) {
1110            mUidMap.remove(userId);
1111        }
1112
1113        public int userIdCount() {
1114            return mUidMap.size();
1115        }
1116
1117        public int userIdAt(int n) {
1118            return mUidMap.keyAt(n);
1119        }
1120
1121        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1122            return mUidMap.get(userId);
1123        }
1124
1125        public int size() {
1126            // total number of pending broadcast entries across all userIds
1127            int num = 0;
1128            for (int i = 0; i< mUidMap.size(); i++) {
1129                num += mUidMap.valueAt(i).size();
1130            }
1131            return num;
1132        }
1133
1134        public void clear() {
1135            mUidMap.clear();
1136        }
1137
1138        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1139            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1140            if (map == null) {
1141                map = new ArrayMap<String, ArrayList<String>>();
1142                mUidMap.put(userId, map);
1143            }
1144            return map;
1145        }
1146    }
1147    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1148
1149    // Service Connection to remote media container service to copy
1150    // package uri's from external media onto secure containers
1151    // or internal storage.
1152    private IMediaContainerService mContainerService = null;
1153
1154    static final int SEND_PENDING_BROADCAST = 1;
1155    static final int MCS_BOUND = 3;
1156    static final int END_COPY = 4;
1157    static final int INIT_COPY = 5;
1158    static final int MCS_UNBIND = 6;
1159    static final int START_CLEANING_PACKAGE = 7;
1160    static final int FIND_INSTALL_LOC = 8;
1161    static final int POST_INSTALL = 9;
1162    static final int MCS_RECONNECT = 10;
1163    static final int MCS_GIVE_UP = 11;
1164    static final int UPDATED_MEDIA_STATUS = 12;
1165    static final int WRITE_SETTINGS = 13;
1166    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1167    static final int PACKAGE_VERIFIED = 15;
1168    static final int CHECK_PENDING_VERIFICATION = 16;
1169    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1170    static final int INTENT_FILTER_VERIFIED = 18;
1171    static final int WRITE_PACKAGE_LIST = 19;
1172    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1173
1174    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1175
1176    // Delay time in millisecs
1177    static final int BROADCAST_DELAY = 10 * 1000;
1178
1179    static UserManagerService sUserManager;
1180
1181    // Stores a list of users whose package restrictions file needs to be updated
1182    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1183
1184    final private DefaultContainerConnection mDefContainerConn =
1185            new DefaultContainerConnection();
1186    class DefaultContainerConnection implements ServiceConnection {
1187        public void onServiceConnected(ComponentName name, IBinder service) {
1188            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1189            final IMediaContainerService imcs = IMediaContainerService.Stub
1190                    .asInterface(Binder.allowBlocking(service));
1191            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1192        }
1193
1194        public void onServiceDisconnected(ComponentName name) {
1195            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1196        }
1197    }
1198
1199    // Recordkeeping of restore-after-install operations that are currently in flight
1200    // between the Package Manager and the Backup Manager
1201    static class PostInstallData {
1202        public InstallArgs args;
1203        public PackageInstalledInfo res;
1204
1205        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1206            args = _a;
1207            res = _r;
1208        }
1209    }
1210
1211    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1212    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1213
1214    // XML tags for backup/restore of various bits of state
1215    private static final String TAG_PREFERRED_BACKUP = "pa";
1216    private static final String TAG_DEFAULT_APPS = "da";
1217    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1218
1219    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1220    private static final String TAG_ALL_GRANTS = "rt-grants";
1221    private static final String TAG_GRANT = "grant";
1222    private static final String ATTR_PACKAGE_NAME = "pkg";
1223
1224    private static final String TAG_PERMISSION = "perm";
1225    private static final String ATTR_PERMISSION_NAME = "name";
1226    private static final String ATTR_IS_GRANTED = "g";
1227    private static final String ATTR_USER_SET = "set";
1228    private static final String ATTR_USER_FIXED = "fixed";
1229    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1230
1231    // System/policy permission grants are not backed up
1232    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1233            FLAG_PERMISSION_POLICY_FIXED
1234            | FLAG_PERMISSION_SYSTEM_FIXED
1235            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1236
1237    // And we back up these user-adjusted states
1238    private static final int USER_RUNTIME_GRANT_MASK =
1239            FLAG_PERMISSION_USER_SET
1240            | FLAG_PERMISSION_USER_FIXED
1241            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1242
1243    final @Nullable String mRequiredVerifierPackage;
1244    final @NonNull String mRequiredInstallerPackage;
1245    final @NonNull String mRequiredUninstallerPackage;
1246    final @Nullable String mSetupWizardPackage;
1247    final @Nullable String mStorageManagerPackage;
1248    final @NonNull String mServicesSystemSharedLibraryPackageName;
1249    final @NonNull String mSharedSystemSharedLibraryPackageName;
1250
1251    final boolean mPermissionReviewRequired;
1252
1253    private final PackageUsage mPackageUsage = new PackageUsage();
1254    private final CompilerStats mCompilerStats = new CompilerStats();
1255
1256    class PackageHandler extends Handler {
1257        private boolean mBound = false;
1258        final ArrayList<HandlerParams> mPendingInstalls =
1259            new ArrayList<HandlerParams>();
1260
1261        private boolean connectToService() {
1262            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1263                    " DefaultContainerService");
1264            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1265            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1266            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1267                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1268                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1269                mBound = true;
1270                return true;
1271            }
1272            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1273            return false;
1274        }
1275
1276        private void disconnectService() {
1277            mContainerService = null;
1278            mBound = false;
1279            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1280            mContext.unbindService(mDefContainerConn);
1281            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1282        }
1283
1284        PackageHandler(Looper looper) {
1285            super(looper);
1286        }
1287
1288        public void handleMessage(Message msg) {
1289            try {
1290                doHandleMessage(msg);
1291            } finally {
1292                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1293            }
1294        }
1295
1296        void doHandleMessage(Message msg) {
1297            switch (msg.what) {
1298                case INIT_COPY: {
1299                    HandlerParams params = (HandlerParams) msg.obj;
1300                    int idx = mPendingInstalls.size();
1301                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1302                    // If a bind was already initiated we dont really
1303                    // need to do anything. The pending install
1304                    // will be processed later on.
1305                    if (!mBound) {
1306                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1307                                System.identityHashCode(mHandler));
1308                        // If this is the only one pending we might
1309                        // have to bind to the service again.
1310                        if (!connectToService()) {
1311                            Slog.e(TAG, "Failed to bind to media container service");
1312                            params.serviceError();
1313                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1314                                    System.identityHashCode(mHandler));
1315                            if (params.traceMethod != null) {
1316                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1317                                        params.traceCookie);
1318                            }
1319                            return;
1320                        } else {
1321                            // Once we bind to the service, the first
1322                            // pending request will be processed.
1323                            mPendingInstalls.add(idx, params);
1324                        }
1325                    } else {
1326                        mPendingInstalls.add(idx, params);
1327                        // Already bound to the service. Just make
1328                        // sure we trigger off processing the first request.
1329                        if (idx == 0) {
1330                            mHandler.sendEmptyMessage(MCS_BOUND);
1331                        }
1332                    }
1333                    break;
1334                }
1335                case MCS_BOUND: {
1336                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1337                    if (msg.obj != null) {
1338                        mContainerService = (IMediaContainerService) msg.obj;
1339                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1340                                System.identityHashCode(mHandler));
1341                    }
1342                    if (mContainerService == null) {
1343                        if (!mBound) {
1344                            // Something seriously wrong since we are not bound and we are not
1345                            // waiting for connection. Bail out.
1346                            Slog.e(TAG, "Cannot bind to media container service");
1347                            for (HandlerParams params : mPendingInstalls) {
1348                                // Indicate service bind error
1349                                params.serviceError();
1350                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1351                                        System.identityHashCode(params));
1352                                if (params.traceMethod != null) {
1353                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1354                                            params.traceMethod, params.traceCookie);
1355                                }
1356                                return;
1357                            }
1358                            mPendingInstalls.clear();
1359                        } else {
1360                            Slog.w(TAG, "Waiting to connect to media container service");
1361                        }
1362                    } else if (mPendingInstalls.size() > 0) {
1363                        HandlerParams params = mPendingInstalls.get(0);
1364                        if (params != null) {
1365                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1366                                    System.identityHashCode(params));
1367                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1368                            if (params.startCopy()) {
1369                                // We are done...  look for more work or to
1370                                // go idle.
1371                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1372                                        "Checking for more work or unbind...");
1373                                // Delete pending install
1374                                if (mPendingInstalls.size() > 0) {
1375                                    mPendingInstalls.remove(0);
1376                                }
1377                                if (mPendingInstalls.size() == 0) {
1378                                    if (mBound) {
1379                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1380                                                "Posting delayed MCS_UNBIND");
1381                                        removeMessages(MCS_UNBIND);
1382                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1383                                        // Unbind after a little delay, to avoid
1384                                        // continual thrashing.
1385                                        sendMessageDelayed(ubmsg, 10000);
1386                                    }
1387                                } else {
1388                                    // There are more pending requests in queue.
1389                                    // Just post MCS_BOUND message to trigger processing
1390                                    // of next pending install.
1391                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1392                                            "Posting MCS_BOUND for next work");
1393                                    mHandler.sendEmptyMessage(MCS_BOUND);
1394                                }
1395                            }
1396                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1397                        }
1398                    } else {
1399                        // Should never happen ideally.
1400                        Slog.w(TAG, "Empty queue");
1401                    }
1402                    break;
1403                }
1404                case MCS_RECONNECT: {
1405                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1406                    if (mPendingInstalls.size() > 0) {
1407                        if (mBound) {
1408                            disconnectService();
1409                        }
1410                        if (!connectToService()) {
1411                            Slog.e(TAG, "Failed to bind to media container service");
1412                            for (HandlerParams params : mPendingInstalls) {
1413                                // Indicate service bind error
1414                                params.serviceError();
1415                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1416                                        System.identityHashCode(params));
1417                            }
1418                            mPendingInstalls.clear();
1419                        }
1420                    }
1421                    break;
1422                }
1423                case MCS_UNBIND: {
1424                    // If there is no actual work left, then time to unbind.
1425                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1426
1427                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1428                        if (mBound) {
1429                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1430
1431                            disconnectService();
1432                        }
1433                    } else if (mPendingInstalls.size() > 0) {
1434                        // There are more pending requests in queue.
1435                        // Just post MCS_BOUND message to trigger processing
1436                        // of next pending install.
1437                        mHandler.sendEmptyMessage(MCS_BOUND);
1438                    }
1439
1440                    break;
1441                }
1442                case MCS_GIVE_UP: {
1443                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1444                    HandlerParams params = mPendingInstalls.remove(0);
1445                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1446                            System.identityHashCode(params));
1447                    break;
1448                }
1449                case SEND_PENDING_BROADCAST: {
1450                    String packages[];
1451                    ArrayList<String> components[];
1452                    int size = 0;
1453                    int uids[];
1454                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1455                    synchronized (mPackages) {
1456                        if (mPendingBroadcasts == null) {
1457                            return;
1458                        }
1459                        size = mPendingBroadcasts.size();
1460                        if (size <= 0) {
1461                            // Nothing to be done. Just return
1462                            return;
1463                        }
1464                        packages = new String[size];
1465                        components = new ArrayList[size];
1466                        uids = new int[size];
1467                        int i = 0;  // filling out the above arrays
1468
1469                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1470                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1471                            Iterator<Map.Entry<String, ArrayList<String>>> it
1472                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1473                                            .entrySet().iterator();
1474                            while (it.hasNext() && i < size) {
1475                                Map.Entry<String, ArrayList<String>> ent = it.next();
1476                                packages[i] = ent.getKey();
1477                                components[i] = ent.getValue();
1478                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1479                                uids[i] = (ps != null)
1480                                        ? UserHandle.getUid(packageUserId, ps.appId)
1481                                        : -1;
1482                                i++;
1483                            }
1484                        }
1485                        size = i;
1486                        mPendingBroadcasts.clear();
1487                    }
1488                    // Send broadcasts
1489                    for (int i = 0; i < size; i++) {
1490                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1491                    }
1492                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1493                    break;
1494                }
1495                case START_CLEANING_PACKAGE: {
1496                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1497                    final String packageName = (String)msg.obj;
1498                    final int userId = msg.arg1;
1499                    final boolean andCode = msg.arg2 != 0;
1500                    synchronized (mPackages) {
1501                        if (userId == UserHandle.USER_ALL) {
1502                            int[] users = sUserManager.getUserIds();
1503                            for (int user : users) {
1504                                mSettings.addPackageToCleanLPw(
1505                                        new PackageCleanItem(user, packageName, andCode));
1506                            }
1507                        } else {
1508                            mSettings.addPackageToCleanLPw(
1509                                    new PackageCleanItem(userId, packageName, andCode));
1510                        }
1511                    }
1512                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1513                    startCleaningPackages();
1514                } break;
1515                case POST_INSTALL: {
1516                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1517
1518                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1519                    final boolean didRestore = (msg.arg2 != 0);
1520                    mRunningInstalls.delete(msg.arg1);
1521
1522                    if (data != null) {
1523                        InstallArgs args = data.args;
1524                        PackageInstalledInfo parentRes = data.res;
1525
1526                        final boolean grantPermissions = (args.installFlags
1527                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1528                        final boolean killApp = (args.installFlags
1529                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1530                        final String[] grantedPermissions = args.installGrantPermissions;
1531
1532                        // Handle the parent package
1533                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1534                                grantedPermissions, didRestore, args.installerPackageName,
1535                                args.observer);
1536
1537                        // Handle the child packages
1538                        final int childCount = (parentRes.addedChildPackages != null)
1539                                ? parentRes.addedChildPackages.size() : 0;
1540                        for (int i = 0; i < childCount; i++) {
1541                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1542                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1543                                    grantedPermissions, false, args.installerPackageName,
1544                                    args.observer);
1545                        }
1546
1547                        // Log tracing if needed
1548                        if (args.traceMethod != null) {
1549                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1550                                    args.traceCookie);
1551                        }
1552                    } else {
1553                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1554                    }
1555
1556                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1557                } break;
1558                case UPDATED_MEDIA_STATUS: {
1559                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1560                    boolean reportStatus = msg.arg1 == 1;
1561                    boolean doGc = msg.arg2 == 1;
1562                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1563                    if (doGc) {
1564                        // Force a gc to clear up stale containers.
1565                        Runtime.getRuntime().gc();
1566                    }
1567                    if (msg.obj != null) {
1568                        @SuppressWarnings("unchecked")
1569                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1570                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1571                        // Unload containers
1572                        unloadAllContainers(args);
1573                    }
1574                    if (reportStatus) {
1575                        try {
1576                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1577                                    "Invoking StorageManagerService call back");
1578                            PackageHelper.getStorageManager().finishMediaUpdate();
1579                        } catch (RemoteException e) {
1580                            Log.e(TAG, "StorageManagerService not running?");
1581                        }
1582                    }
1583                } break;
1584                case WRITE_SETTINGS: {
1585                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1586                    synchronized (mPackages) {
1587                        removeMessages(WRITE_SETTINGS);
1588                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1589                        mSettings.writeLPr();
1590                        mDirtyUsers.clear();
1591                    }
1592                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1593                } break;
1594                case WRITE_PACKAGE_RESTRICTIONS: {
1595                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1596                    synchronized (mPackages) {
1597                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1598                        for (int userId : mDirtyUsers) {
1599                            mSettings.writePackageRestrictionsLPr(userId);
1600                        }
1601                        mDirtyUsers.clear();
1602                    }
1603                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1604                } break;
1605                case WRITE_PACKAGE_LIST: {
1606                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1607                    synchronized (mPackages) {
1608                        removeMessages(WRITE_PACKAGE_LIST);
1609                        mSettings.writePackageListLPr(msg.arg1);
1610                    }
1611                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1612                } break;
1613                case CHECK_PENDING_VERIFICATION: {
1614                    final int verificationId = msg.arg1;
1615                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1616
1617                    if ((state != null) && !state.timeoutExtended()) {
1618                        final InstallArgs args = state.getInstallArgs();
1619                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1620
1621                        Slog.i(TAG, "Verification timed out for " + originUri);
1622                        mPendingVerification.remove(verificationId);
1623
1624                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1625
1626                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1627                            Slog.i(TAG, "Continuing with installation of " + originUri);
1628                            state.setVerifierResponse(Binder.getCallingUid(),
1629                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1630                            broadcastPackageVerified(verificationId, originUri,
1631                                    PackageManager.VERIFICATION_ALLOW,
1632                                    state.getInstallArgs().getUser());
1633                            try {
1634                                ret = args.copyApk(mContainerService, true);
1635                            } catch (RemoteException e) {
1636                                Slog.e(TAG, "Could not contact the ContainerService");
1637                            }
1638                        } else {
1639                            broadcastPackageVerified(verificationId, originUri,
1640                                    PackageManager.VERIFICATION_REJECT,
1641                                    state.getInstallArgs().getUser());
1642                        }
1643
1644                        Trace.asyncTraceEnd(
1645                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1646
1647                        processPendingInstall(args, ret);
1648                        mHandler.sendEmptyMessage(MCS_UNBIND);
1649                    }
1650                    break;
1651                }
1652                case PACKAGE_VERIFIED: {
1653                    final int verificationId = msg.arg1;
1654
1655                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1656                    if (state == null) {
1657                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1658                        break;
1659                    }
1660
1661                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1662
1663                    state.setVerifierResponse(response.callerUid, response.code);
1664
1665                    if (state.isVerificationComplete()) {
1666                        mPendingVerification.remove(verificationId);
1667
1668                        final InstallArgs args = state.getInstallArgs();
1669                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1670
1671                        int ret;
1672                        if (state.isInstallAllowed()) {
1673                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1674                            broadcastPackageVerified(verificationId, originUri,
1675                                    response.code, state.getInstallArgs().getUser());
1676                            try {
1677                                ret = args.copyApk(mContainerService, true);
1678                            } catch (RemoteException e) {
1679                                Slog.e(TAG, "Could not contact the ContainerService");
1680                            }
1681                        } else {
1682                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1683                        }
1684
1685                        Trace.asyncTraceEnd(
1686                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1687
1688                        processPendingInstall(args, ret);
1689                        mHandler.sendEmptyMessage(MCS_UNBIND);
1690                    }
1691
1692                    break;
1693                }
1694                case START_INTENT_FILTER_VERIFICATIONS: {
1695                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1696                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1697                            params.replacing, params.pkg);
1698                    break;
1699                }
1700                case INTENT_FILTER_VERIFIED: {
1701                    final int verificationId = msg.arg1;
1702
1703                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1704                            verificationId);
1705                    if (state == null) {
1706                        Slog.w(TAG, "Invalid IntentFilter verification token "
1707                                + verificationId + " received");
1708                        break;
1709                    }
1710
1711                    final int userId = state.getUserId();
1712
1713                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1714                            "Processing IntentFilter verification with token:"
1715                            + verificationId + " and userId:" + userId);
1716
1717                    final IntentFilterVerificationResponse response =
1718                            (IntentFilterVerificationResponse) msg.obj;
1719
1720                    state.setVerifierResponse(response.callerUid, response.code);
1721
1722                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1723                            "IntentFilter verification with token:" + verificationId
1724                            + " and userId:" + userId
1725                            + " is settings verifier response with response code:"
1726                            + response.code);
1727
1728                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1729                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1730                                + response.getFailedDomainsString());
1731                    }
1732
1733                    if (state.isVerificationComplete()) {
1734                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1735                    } else {
1736                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1737                                "IntentFilter verification with token:" + verificationId
1738                                + " was not said to be complete");
1739                    }
1740
1741                    break;
1742                }
1743                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1744                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1745                            mInstantAppResolverConnection,
1746                            (EphemeralRequest) msg.obj,
1747                            mInstantAppInstallerActivity,
1748                            mHandler);
1749                }
1750            }
1751        }
1752    }
1753
1754    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1755            boolean killApp, String[] grantedPermissions,
1756            boolean launchedForRestore, String installerPackage,
1757            IPackageInstallObserver2 installObserver) {
1758        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1759            // Send the removed broadcasts
1760            if (res.removedInfo != null) {
1761                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1762            }
1763
1764            // Now that we successfully installed the package, grant runtime
1765            // permissions if requested before broadcasting the install. Also
1766            // for legacy apps in permission review mode we clear the permission
1767            // review flag which is used to emulate runtime permissions for
1768            // legacy apps.
1769            if (grantPermissions) {
1770                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1771            }
1772
1773            final boolean update = res.removedInfo != null
1774                    && res.removedInfo.removedPackage != null;
1775
1776            // If this is the first time we have child packages for a disabled privileged
1777            // app that had no children, we grant requested runtime permissions to the new
1778            // children if the parent on the system image had them already granted.
1779            if (res.pkg.parentPackage != null) {
1780                synchronized (mPackages) {
1781                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1782                }
1783            }
1784
1785            synchronized (mPackages) {
1786                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1787            }
1788
1789            final String packageName = res.pkg.applicationInfo.packageName;
1790
1791            // Determine the set of users who are adding this package for
1792            // the first time vs. those who are seeing an update.
1793            int[] firstUsers = EMPTY_INT_ARRAY;
1794            int[] updateUsers = EMPTY_INT_ARRAY;
1795            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1796            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1797            for (int newUser : res.newUsers) {
1798                if (ps.getInstantApp(newUser)) {
1799                    continue;
1800                }
1801                if (allNewUsers) {
1802                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1803                    continue;
1804                }
1805                boolean isNew = true;
1806                for (int origUser : res.origUsers) {
1807                    if (origUser == newUser) {
1808                        isNew = false;
1809                        break;
1810                    }
1811                }
1812                if (isNew) {
1813                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1814                } else {
1815                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1816                }
1817            }
1818
1819            // Send installed broadcasts if the package is not a static shared lib.
1820            if (res.pkg.staticSharedLibName == null) {
1821                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1822
1823                // Send added for users that see the package for the first time
1824                // sendPackageAddedForNewUsers also deals with system apps
1825                int appId = UserHandle.getAppId(res.uid);
1826                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1827                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1828
1829                // Send added for users that don't see the package for the first time
1830                Bundle extras = new Bundle(1);
1831                extras.putInt(Intent.EXTRA_UID, res.uid);
1832                if (update) {
1833                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1834                }
1835                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1836                        extras, 0 /*flags*/, null /*targetPackage*/,
1837                        null /*finishedReceiver*/, updateUsers);
1838
1839                // Send replaced for users that don't see the package for the first time
1840                if (update) {
1841                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1842                            packageName, extras, 0 /*flags*/,
1843                            null /*targetPackage*/, null /*finishedReceiver*/,
1844                            updateUsers);
1845                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1846                            null /*package*/, null /*extras*/, 0 /*flags*/,
1847                            packageName /*targetPackage*/,
1848                            null /*finishedReceiver*/, updateUsers);
1849                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1850                    // First-install and we did a restore, so we're responsible for the
1851                    // first-launch broadcast.
1852                    if (DEBUG_BACKUP) {
1853                        Slog.i(TAG, "Post-restore of " + packageName
1854                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1855                    }
1856                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1857                }
1858
1859                // Send broadcast package appeared if forward locked/external for all users
1860                // treat asec-hosted packages like removable media on upgrade
1861                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1862                    if (DEBUG_INSTALL) {
1863                        Slog.i(TAG, "upgrading pkg " + res.pkg
1864                                + " is ASEC-hosted -> AVAILABLE");
1865                    }
1866                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1867                    ArrayList<String> pkgList = new ArrayList<>(1);
1868                    pkgList.add(packageName);
1869                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1870                }
1871            }
1872
1873            // Work that needs to happen on first install within each user
1874            if (firstUsers != null && firstUsers.length > 0) {
1875                synchronized (mPackages) {
1876                    for (int userId : firstUsers) {
1877                        // If this app is a browser and it's newly-installed for some
1878                        // users, clear any default-browser state in those users. The
1879                        // app's nature doesn't depend on the user, so we can just check
1880                        // its browser nature in any user and generalize.
1881                        if (packageIsBrowser(packageName, userId)) {
1882                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1883                        }
1884
1885                        // We may also need to apply pending (restored) runtime
1886                        // permission grants within these users.
1887                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1888                    }
1889                }
1890            }
1891
1892            // Log current value of "unknown sources" setting
1893            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1894                    getUnknownSourcesSettings());
1895
1896            // Force a gc to clear up things
1897            Runtime.getRuntime().gc();
1898
1899            // Remove the replaced package's older resources safely now
1900            // We delete after a gc for applications  on sdcard.
1901            if (res.removedInfo != null && res.removedInfo.args != null) {
1902                synchronized (mInstallLock) {
1903                    res.removedInfo.args.doPostDeleteLI(true);
1904                }
1905            }
1906
1907            // Notify DexManager that the package was installed for new users.
1908            // The updated users should already be indexed and the package code paths
1909            // should not change.
1910            // Don't notify the manager for ephemeral apps as they are not expected to
1911            // survive long enough to benefit of background optimizations.
1912            for (int userId : firstUsers) {
1913                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1914                mDexManager.notifyPackageInstalled(info, userId);
1915            }
1916        }
1917
1918        // If someone is watching installs - notify them
1919        if (installObserver != null) {
1920            try {
1921                Bundle extras = extrasForInstallResult(res);
1922                installObserver.onPackageInstalled(res.name, res.returnCode,
1923                        res.returnMsg, extras);
1924            } catch (RemoteException e) {
1925                Slog.i(TAG, "Observer no longer exists.");
1926            }
1927        }
1928    }
1929
1930    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1931            PackageParser.Package pkg) {
1932        if (pkg.parentPackage == null) {
1933            return;
1934        }
1935        if (pkg.requestedPermissions == null) {
1936            return;
1937        }
1938        final PackageSetting disabledSysParentPs = mSettings
1939                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1940        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1941                || !disabledSysParentPs.isPrivileged()
1942                || (disabledSysParentPs.childPackageNames != null
1943                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1944            return;
1945        }
1946        final int[] allUserIds = sUserManager.getUserIds();
1947        final int permCount = pkg.requestedPermissions.size();
1948        for (int i = 0; i < permCount; i++) {
1949            String permission = pkg.requestedPermissions.get(i);
1950            BasePermission bp = mSettings.mPermissions.get(permission);
1951            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1952                continue;
1953            }
1954            for (int userId : allUserIds) {
1955                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1956                        permission, userId)) {
1957                    grantRuntimePermission(pkg.packageName, permission, userId);
1958                }
1959            }
1960        }
1961    }
1962
1963    private StorageEventListener mStorageListener = new StorageEventListener() {
1964        @Override
1965        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1966            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1967                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1968                    final String volumeUuid = vol.getFsUuid();
1969
1970                    // Clean up any users or apps that were removed or recreated
1971                    // while this volume was missing
1972                    sUserManager.reconcileUsers(volumeUuid);
1973                    reconcileApps(volumeUuid);
1974
1975                    // Clean up any install sessions that expired or were
1976                    // cancelled while this volume was missing
1977                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1978
1979                    loadPrivatePackages(vol);
1980
1981                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1982                    unloadPrivatePackages(vol);
1983                }
1984            }
1985
1986            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1987                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1988                    updateExternalMediaStatus(true, false);
1989                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1990                    updateExternalMediaStatus(false, false);
1991                }
1992            }
1993        }
1994
1995        @Override
1996        public void onVolumeForgotten(String fsUuid) {
1997            if (TextUtils.isEmpty(fsUuid)) {
1998                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1999                return;
2000            }
2001
2002            // Remove any apps installed on the forgotten volume
2003            synchronized (mPackages) {
2004                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2005                for (PackageSetting ps : packages) {
2006                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2007                    deletePackageVersioned(new VersionedPackage(ps.name,
2008                            PackageManager.VERSION_CODE_HIGHEST),
2009                            new LegacyPackageDeleteObserver(null).getBinder(),
2010                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2011                    // Try very hard to release any references to this package
2012                    // so we don't risk the system server being killed due to
2013                    // open FDs
2014                    AttributeCache.instance().removePackage(ps.name);
2015                }
2016
2017                mSettings.onVolumeForgotten(fsUuid);
2018                mSettings.writeLPr();
2019            }
2020        }
2021    };
2022
2023    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2024            String[] grantedPermissions) {
2025        for (int userId : userIds) {
2026            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2027        }
2028    }
2029
2030    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2031            String[] grantedPermissions) {
2032        SettingBase sb = (SettingBase) pkg.mExtras;
2033        if (sb == null) {
2034            return;
2035        }
2036
2037        PermissionsState permissionsState = sb.getPermissionsState();
2038
2039        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2040                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2041
2042        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2043                >= Build.VERSION_CODES.M;
2044
2045        for (String permission : pkg.requestedPermissions) {
2046            final BasePermission bp;
2047            synchronized (mPackages) {
2048                bp = mSettings.mPermissions.get(permission);
2049            }
2050            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2051                    && (grantedPermissions == null
2052                           || ArrayUtils.contains(grantedPermissions, permission))) {
2053                final int flags = permissionsState.getPermissionFlags(permission, userId);
2054                if (supportsRuntimePermissions) {
2055                    // Installer cannot change immutable permissions.
2056                    if ((flags & immutableFlags) == 0) {
2057                        grantRuntimePermission(pkg.packageName, permission, userId);
2058                    }
2059                } else if (mPermissionReviewRequired) {
2060                    // In permission review mode we clear the review flag when we
2061                    // are asked to install the app with all permissions granted.
2062                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2063                        updatePermissionFlags(permission, pkg.packageName,
2064                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2065                    }
2066                }
2067            }
2068        }
2069    }
2070
2071    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2072        Bundle extras = null;
2073        switch (res.returnCode) {
2074            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2075                extras = new Bundle();
2076                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2077                        res.origPermission);
2078                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2079                        res.origPackage);
2080                break;
2081            }
2082            case PackageManager.INSTALL_SUCCEEDED: {
2083                extras = new Bundle();
2084                extras.putBoolean(Intent.EXTRA_REPLACING,
2085                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2086                break;
2087            }
2088        }
2089        return extras;
2090    }
2091
2092    void scheduleWriteSettingsLocked() {
2093        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2094            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2095        }
2096    }
2097
2098    void scheduleWritePackageListLocked(int userId) {
2099        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2100            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2101            msg.arg1 = userId;
2102            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2103        }
2104    }
2105
2106    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2107        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2108        scheduleWritePackageRestrictionsLocked(userId);
2109    }
2110
2111    void scheduleWritePackageRestrictionsLocked(int userId) {
2112        final int[] userIds = (userId == UserHandle.USER_ALL)
2113                ? sUserManager.getUserIds() : new int[]{userId};
2114        for (int nextUserId : userIds) {
2115            if (!sUserManager.exists(nextUserId)) return;
2116            mDirtyUsers.add(nextUserId);
2117            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2118                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2119            }
2120        }
2121    }
2122
2123    public static PackageManagerService main(Context context, Installer installer,
2124            boolean factoryTest, boolean onlyCore) {
2125        // Self-check for initial settings.
2126        PackageManagerServiceCompilerMapping.checkProperties();
2127
2128        PackageManagerService m = new PackageManagerService(context, installer,
2129                factoryTest, onlyCore);
2130        m.enableSystemUserPackages();
2131        ServiceManager.addService("package", m);
2132        return m;
2133    }
2134
2135    private void enableSystemUserPackages() {
2136        if (!UserManager.isSplitSystemUser()) {
2137            return;
2138        }
2139        // For system user, enable apps based on the following conditions:
2140        // - app is whitelisted or belong to one of these groups:
2141        //   -- system app which has no launcher icons
2142        //   -- system app which has INTERACT_ACROSS_USERS permission
2143        //   -- system IME app
2144        // - app is not in the blacklist
2145        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2146        Set<String> enableApps = new ArraySet<>();
2147        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2148                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2149                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2150        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2151        enableApps.addAll(wlApps);
2152        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2153                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2154        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2155        enableApps.removeAll(blApps);
2156        Log.i(TAG, "Applications installed for system user: " + enableApps);
2157        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2158                UserHandle.SYSTEM);
2159        final int allAppsSize = allAps.size();
2160        synchronized (mPackages) {
2161            for (int i = 0; i < allAppsSize; i++) {
2162                String pName = allAps.get(i);
2163                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2164                // Should not happen, but we shouldn't be failing if it does
2165                if (pkgSetting == null) {
2166                    continue;
2167                }
2168                boolean install = enableApps.contains(pName);
2169                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2170                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2171                            + " for system user");
2172                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2173                }
2174            }
2175            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2176        }
2177    }
2178
2179    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2180        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2181                Context.DISPLAY_SERVICE);
2182        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2183    }
2184
2185    /**
2186     * Requests that files preopted on a secondary system partition be copied to the data partition
2187     * if possible.  Note that the actual copying of the files is accomplished by init for security
2188     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2189     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2190     */
2191    private static void requestCopyPreoptedFiles() {
2192        final int WAIT_TIME_MS = 100;
2193        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2194        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2195            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2196            // We will wait for up to 100 seconds.
2197            final long timeStart = SystemClock.uptimeMillis();
2198            final long timeEnd = timeStart + 100 * 1000;
2199            long timeNow = timeStart;
2200            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2201                try {
2202                    Thread.sleep(WAIT_TIME_MS);
2203                } catch (InterruptedException e) {
2204                    // Do nothing
2205                }
2206                timeNow = SystemClock.uptimeMillis();
2207                if (timeNow > timeEnd) {
2208                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2209                    Slog.wtf(TAG, "cppreopt did not finish!");
2210                    break;
2211                }
2212            }
2213
2214            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2215        }
2216    }
2217
2218    public PackageManagerService(Context context, Installer installer,
2219            boolean factoryTest, boolean onlyCore) {
2220        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2221        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2222                SystemClock.uptimeMillis());
2223
2224        if (mSdkVersion <= 0) {
2225            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2226        }
2227
2228        mContext = context;
2229
2230        mPermissionReviewRequired = context.getResources().getBoolean(
2231                R.bool.config_permissionReviewRequired);
2232
2233        mFactoryTest = factoryTest;
2234        mOnlyCore = onlyCore;
2235        mMetrics = new DisplayMetrics();
2236        mSettings = new Settings(mPackages);
2237        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2238                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2239        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2240                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2241        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2242                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2243        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2244                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2245        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2246                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2247        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2248                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2249
2250        String separateProcesses = SystemProperties.get("debug.separate_processes");
2251        if (separateProcesses != null && separateProcesses.length() > 0) {
2252            if ("*".equals(separateProcesses)) {
2253                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2254                mSeparateProcesses = null;
2255                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2256            } else {
2257                mDefParseFlags = 0;
2258                mSeparateProcesses = separateProcesses.split(",");
2259                Slog.w(TAG, "Running with debug.separate_processes: "
2260                        + separateProcesses);
2261            }
2262        } else {
2263            mDefParseFlags = 0;
2264            mSeparateProcesses = null;
2265        }
2266
2267        mInstaller = installer;
2268        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2269                "*dexopt*");
2270        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2271        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2272
2273        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2274                FgThread.get().getLooper());
2275
2276        getDefaultDisplayMetrics(context, mMetrics);
2277
2278        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2279        SystemConfig systemConfig = SystemConfig.getInstance();
2280        mGlobalGids = systemConfig.getGlobalGids();
2281        mSystemPermissions = systemConfig.getSystemPermissions();
2282        mAvailableFeatures = systemConfig.getAvailableFeatures();
2283        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2284
2285        mProtectedPackages = new ProtectedPackages(mContext);
2286
2287        synchronized (mInstallLock) {
2288        // writer
2289        synchronized (mPackages) {
2290            mHandlerThread = new ServiceThread(TAG,
2291                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2292            mHandlerThread.start();
2293            mHandler = new PackageHandler(mHandlerThread.getLooper());
2294            mProcessLoggingHandler = new ProcessLoggingHandler();
2295            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2296
2297            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2298            mInstantAppRegistry = new InstantAppRegistry(this);
2299
2300            File dataDir = Environment.getDataDirectory();
2301            mAppInstallDir = new File(dataDir, "app");
2302            mAppLib32InstallDir = new File(dataDir, "app-lib");
2303            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2304            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2305            sUserManager = new UserManagerService(context, this,
2306                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2307
2308            // Propagate permission configuration in to package manager.
2309            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2310                    = systemConfig.getPermissions();
2311            for (int i=0; i<permConfig.size(); i++) {
2312                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2313                BasePermission bp = mSettings.mPermissions.get(perm.name);
2314                if (bp == null) {
2315                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2316                    mSettings.mPermissions.put(perm.name, bp);
2317                }
2318                if (perm.gids != null) {
2319                    bp.setGids(perm.gids, perm.perUser);
2320                }
2321            }
2322
2323            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2324            final int builtInLibCount = libConfig.size();
2325            for (int i = 0; i < builtInLibCount; i++) {
2326                String name = libConfig.keyAt(i);
2327                String path = libConfig.valueAt(i);
2328                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2329                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2330            }
2331
2332            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2333
2334            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2335            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2336            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2337
2338            // Clean up orphaned packages for which the code path doesn't exist
2339            // and they are an update to a system app - caused by bug/32321269
2340            final int packageSettingCount = mSettings.mPackages.size();
2341            for (int i = packageSettingCount - 1; i >= 0; i--) {
2342                PackageSetting ps = mSettings.mPackages.valueAt(i);
2343                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2344                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2345                    mSettings.mPackages.removeAt(i);
2346                    mSettings.enableSystemPackageLPw(ps.name);
2347                }
2348            }
2349
2350            if (mFirstBoot) {
2351                requestCopyPreoptedFiles();
2352            }
2353
2354            String customResolverActivity = Resources.getSystem().getString(
2355                    R.string.config_customResolverActivity);
2356            if (TextUtils.isEmpty(customResolverActivity)) {
2357                customResolverActivity = null;
2358            } else {
2359                mCustomResolverComponentName = ComponentName.unflattenFromString(
2360                        customResolverActivity);
2361            }
2362
2363            long startTime = SystemClock.uptimeMillis();
2364
2365            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2366                    startTime);
2367
2368            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2369            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2370
2371            if (bootClassPath == null) {
2372                Slog.w(TAG, "No BOOTCLASSPATH found!");
2373            }
2374
2375            if (systemServerClassPath == null) {
2376                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2377            }
2378
2379            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2380            final String[] dexCodeInstructionSets =
2381                    getDexCodeInstructionSets(
2382                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2383
2384            /**
2385             * Ensure all external libraries have had dexopt run on them.
2386             */
2387            if (mSharedLibraries.size() > 0) {
2388                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2389                // NOTE: For now, we're compiling these system "shared libraries"
2390                // (and framework jars) into all available architectures. It's possible
2391                // to compile them only when we come across an app that uses them (there's
2392                // already logic for that in scanPackageLI) but that adds some complexity.
2393                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2394                    final int libCount = mSharedLibraries.size();
2395                    for (int i = 0; i < libCount; i++) {
2396                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2397                        final int versionCount = versionedLib.size();
2398                        for (int j = 0; j < versionCount; j++) {
2399                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2400                            final String libPath = libEntry.path != null
2401                                    ? libEntry.path : libEntry.apk;
2402                            if (libPath == null) {
2403                                continue;
2404                            }
2405                            try {
2406                                // Shared libraries do not have profiles so we perform a full
2407                                // AOT compilation (if needed).
2408                                int dexoptNeeded = DexFile.getDexOptNeeded(
2409                                        libPath, dexCodeInstructionSet,
2410                                        getCompilerFilterForReason(REASON_SHARED_APK),
2411                                        false /* newProfile */);
2412                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2413                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2414                                            dexCodeInstructionSet, dexoptNeeded, null,
2415                                            DEXOPT_PUBLIC,
2416                                            getCompilerFilterForReason(REASON_SHARED_APK),
2417                                            StorageManager.UUID_PRIVATE_INTERNAL,
2418                                            PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK);
2419                                }
2420                            } catch (FileNotFoundException e) {
2421                                Slog.w(TAG, "Library not found: " + libPath);
2422                            } catch (IOException | InstallerException e) {
2423                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2424                                        + e.getMessage());
2425                            }
2426                        }
2427                    }
2428                }
2429                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2430            }
2431
2432            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2433
2434            final VersionInfo ver = mSettings.getInternalVersion();
2435            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2436
2437            // when upgrading from pre-M, promote system app permissions from install to runtime
2438            mPromoteSystemApps =
2439                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2440
2441            // When upgrading from pre-N, we need to handle package extraction like first boot,
2442            // as there is no profiling data available.
2443            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2444
2445            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2446
2447            // save off the names of pre-existing system packages prior to scanning; we don't
2448            // want to automatically grant runtime permissions for new system apps
2449            if (mPromoteSystemApps) {
2450                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2451                while (pkgSettingIter.hasNext()) {
2452                    PackageSetting ps = pkgSettingIter.next();
2453                    if (isSystemApp(ps)) {
2454                        mExistingSystemPackages.add(ps.name);
2455                    }
2456                }
2457            }
2458
2459            mCacheDir = preparePackageParserCache(mIsUpgrade);
2460
2461            // Set flag to monitor and not change apk file paths when
2462            // scanning install directories.
2463            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2464
2465            if (mIsUpgrade || mFirstBoot) {
2466                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2467            }
2468
2469            // Collect vendor overlay packages. (Do this before scanning any apps.)
2470            // For security and version matching reason, only consider
2471            // overlay packages if they reside in the right directory.
2472            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2473            if (overlayThemeDir.isEmpty()) {
2474                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2475            }
2476            if (!overlayThemeDir.isEmpty()) {
2477                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2478                        | PackageParser.PARSE_IS_SYSTEM
2479                        | PackageParser.PARSE_IS_SYSTEM_DIR
2480                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2481            }
2482            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2483                    | PackageParser.PARSE_IS_SYSTEM
2484                    | PackageParser.PARSE_IS_SYSTEM_DIR
2485                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2486
2487            // Find base frameworks (resource packages without code).
2488            scanDirTracedLI(frameworkDir, mDefParseFlags
2489                    | PackageParser.PARSE_IS_SYSTEM
2490                    | PackageParser.PARSE_IS_SYSTEM_DIR
2491                    | PackageParser.PARSE_IS_PRIVILEGED,
2492                    scanFlags | SCAN_NO_DEX, 0);
2493
2494            // Collected privileged system packages.
2495            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2496            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2497                    | PackageParser.PARSE_IS_SYSTEM
2498                    | PackageParser.PARSE_IS_SYSTEM_DIR
2499                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2500
2501            // Collect ordinary system packages.
2502            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2503            scanDirTracedLI(systemAppDir, mDefParseFlags
2504                    | PackageParser.PARSE_IS_SYSTEM
2505                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2506
2507            // Collect all vendor packages.
2508            File vendorAppDir = new File("/vendor/app");
2509            try {
2510                vendorAppDir = vendorAppDir.getCanonicalFile();
2511            } catch (IOException e) {
2512                // failed to look up canonical path, continue with original one
2513            }
2514            scanDirTracedLI(vendorAppDir, mDefParseFlags
2515                    | PackageParser.PARSE_IS_SYSTEM
2516                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2517
2518            // Collect all OEM packages.
2519            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2520            scanDirTracedLI(oemAppDir, mDefParseFlags
2521                    | PackageParser.PARSE_IS_SYSTEM
2522                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2523
2524            // Prune any system packages that no longer exist.
2525            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2526            if (!mOnlyCore) {
2527                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2528                while (psit.hasNext()) {
2529                    PackageSetting ps = psit.next();
2530
2531                    /*
2532                     * If this is not a system app, it can't be a
2533                     * disable system app.
2534                     */
2535                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2536                        continue;
2537                    }
2538
2539                    /*
2540                     * If the package is scanned, it's not erased.
2541                     */
2542                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2543                    if (scannedPkg != null) {
2544                        /*
2545                         * If the system app is both scanned and in the
2546                         * disabled packages list, then it must have been
2547                         * added via OTA. Remove it from the currently
2548                         * scanned package so the previously user-installed
2549                         * application can be scanned.
2550                         */
2551                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2552                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2553                                    + ps.name + "; removing system app.  Last known codePath="
2554                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2555                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2556                                    + scannedPkg.mVersionCode);
2557                            removePackageLI(scannedPkg, true);
2558                            mExpectingBetter.put(ps.name, ps.codePath);
2559                        }
2560
2561                        continue;
2562                    }
2563
2564                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2565                        psit.remove();
2566                        logCriticalInfo(Log.WARN, "System package " + ps.name
2567                                + " no longer exists; it's data will be wiped");
2568                        // Actual deletion of code and data will be handled by later
2569                        // reconciliation step
2570                    } else {
2571                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2572                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2573                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2574                        }
2575                    }
2576                }
2577            }
2578
2579            //look for any incomplete package installations
2580            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2581            for (int i = 0; i < deletePkgsList.size(); i++) {
2582                // Actual deletion of code and data will be handled by later
2583                // reconciliation step
2584                final String packageName = deletePkgsList.get(i).name;
2585                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2586                synchronized (mPackages) {
2587                    mSettings.removePackageLPw(packageName);
2588                }
2589            }
2590
2591            //delete tmp files
2592            deleteTempPackageFiles();
2593
2594            // Remove any shared userIDs that have no associated packages
2595            mSettings.pruneSharedUsersLPw();
2596
2597            if (!mOnlyCore) {
2598                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2599                        SystemClock.uptimeMillis());
2600                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2601
2602                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2603                        | PackageParser.PARSE_FORWARD_LOCK,
2604                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2605
2606                /**
2607                 * Remove disable package settings for any updated system
2608                 * apps that were removed via an OTA. If they're not a
2609                 * previously-updated app, remove them completely.
2610                 * Otherwise, just revoke their system-level permissions.
2611                 */
2612                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2613                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2614                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2615
2616                    String msg;
2617                    if (deletedPkg == null) {
2618                        msg = "Updated system package " + deletedAppName
2619                                + " no longer exists; it's data will be wiped";
2620                        // Actual deletion of code and data will be handled by later
2621                        // reconciliation step
2622                    } else {
2623                        msg = "Updated system app + " + deletedAppName
2624                                + " no longer present; removing system privileges for "
2625                                + deletedAppName;
2626
2627                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2628
2629                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2630                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2631                    }
2632                    logCriticalInfo(Log.WARN, msg);
2633                }
2634
2635                /**
2636                 * Make sure all system apps that we expected to appear on
2637                 * the userdata partition actually showed up. If they never
2638                 * appeared, crawl back and revive the system version.
2639                 */
2640                for (int i = 0; i < mExpectingBetter.size(); i++) {
2641                    final String packageName = mExpectingBetter.keyAt(i);
2642                    if (!mPackages.containsKey(packageName)) {
2643                        final File scanFile = mExpectingBetter.valueAt(i);
2644
2645                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2646                                + " but never showed up; reverting to system");
2647
2648                        int reparseFlags = mDefParseFlags;
2649                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2650                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2651                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2652                                    | PackageParser.PARSE_IS_PRIVILEGED;
2653                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2654                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2655                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2656                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2657                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2658                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2659                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2660                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2661                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2662                        } else {
2663                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2664                            continue;
2665                        }
2666
2667                        mSettings.enableSystemPackageLPw(packageName);
2668
2669                        try {
2670                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2671                        } catch (PackageManagerException e) {
2672                            Slog.e(TAG, "Failed to parse original system package: "
2673                                    + e.getMessage());
2674                        }
2675                    }
2676                }
2677            }
2678            mExpectingBetter.clear();
2679
2680            // Resolve the storage manager.
2681            mStorageManagerPackage = getStorageManagerPackageName();
2682
2683            // Resolve protected action filters. Only the setup wizard is allowed to
2684            // have a high priority filter for these actions.
2685            mSetupWizardPackage = getSetupWizardPackageName();
2686            if (mProtectedFilters.size() > 0) {
2687                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2688                    Slog.i(TAG, "No setup wizard;"
2689                        + " All protected intents capped to priority 0");
2690                }
2691                for (ActivityIntentInfo filter : mProtectedFilters) {
2692                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2693                        if (DEBUG_FILTERS) {
2694                            Slog.i(TAG, "Found setup wizard;"
2695                                + " allow priority " + filter.getPriority() + ";"
2696                                + " package: " + filter.activity.info.packageName
2697                                + " activity: " + filter.activity.className
2698                                + " priority: " + filter.getPriority());
2699                        }
2700                        // skip setup wizard; allow it to keep the high priority filter
2701                        continue;
2702                    }
2703                    Slog.w(TAG, "Protected action; cap priority to 0;"
2704                            + " package: " + filter.activity.info.packageName
2705                            + " activity: " + filter.activity.className
2706                            + " origPrio: " + filter.getPriority());
2707                    filter.setPriority(0);
2708                }
2709            }
2710            mDeferProtectedFilters = false;
2711            mProtectedFilters.clear();
2712
2713            // Now that we know all of the shared libraries, update all clients to have
2714            // the correct library paths.
2715            updateAllSharedLibrariesLPw(null);
2716
2717            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2718                // NOTE: We ignore potential failures here during a system scan (like
2719                // the rest of the commands above) because there's precious little we
2720                // can do about it. A settings error is reported, though.
2721                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2722            }
2723
2724            // Now that we know all the packages we are keeping,
2725            // read and update their last usage times.
2726            mPackageUsage.read(mPackages);
2727            mCompilerStats.read();
2728
2729            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2730                    SystemClock.uptimeMillis());
2731            Slog.i(TAG, "Time to scan packages: "
2732                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2733                    + " seconds");
2734
2735            // If the platform SDK has changed since the last time we booted,
2736            // we need to re-grant app permission to catch any new ones that
2737            // appear.  This is really a hack, and means that apps can in some
2738            // cases get permissions that the user didn't initially explicitly
2739            // allow...  it would be nice to have some better way to handle
2740            // this situation.
2741            int updateFlags = UPDATE_PERMISSIONS_ALL;
2742            if (ver.sdkVersion != mSdkVersion) {
2743                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2744                        + mSdkVersion + "; regranting permissions for internal storage");
2745                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2746            }
2747            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2748            ver.sdkVersion = mSdkVersion;
2749
2750            // If this is the first boot or an update from pre-M, and it is a normal
2751            // boot, then we need to initialize the default preferred apps across
2752            // all defined users.
2753            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2754                for (UserInfo user : sUserManager.getUsers(true)) {
2755                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2756                    applyFactoryDefaultBrowserLPw(user.id);
2757                    primeDomainVerificationsLPw(user.id);
2758                }
2759            }
2760
2761            // Prepare storage for system user really early during boot,
2762            // since core system apps like SettingsProvider and SystemUI
2763            // can't wait for user to start
2764            final int storageFlags;
2765            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2766                storageFlags = StorageManager.FLAG_STORAGE_DE;
2767            } else {
2768                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2769            }
2770            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2771                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2772                    true /* onlyCoreApps */);
2773            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2774                if (deferPackages == null || deferPackages.isEmpty()) {
2775                    return;
2776                }
2777                int count = 0;
2778                for (String pkgName : deferPackages) {
2779                    PackageParser.Package pkg = null;
2780                    synchronized (mPackages) {
2781                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2782                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2783                            pkg = ps.pkg;
2784                        }
2785                    }
2786                    if (pkg != null) {
2787                        synchronized (mInstallLock) {
2788                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2789                                    true /* maybeMigrateAppData */);
2790                        }
2791                        count++;
2792                    }
2793                }
2794                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2795            }, "prepareAppData");
2796
2797            // If this is first boot after an OTA, and a normal boot, then
2798            // we need to clear code cache directories.
2799            // Note that we do *not* clear the application profiles. These remain valid
2800            // across OTAs and are used to drive profile verification (post OTA) and
2801            // profile compilation (without waiting to collect a fresh set of profiles).
2802            if (mIsUpgrade && !onlyCore) {
2803                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2804                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2805                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2806                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2807                        // No apps are running this early, so no need to freeze
2808                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2809                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2810                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2811                    }
2812                }
2813                ver.fingerprint = Build.FINGERPRINT;
2814            }
2815
2816            checkDefaultBrowser();
2817
2818            // clear only after permissions and other defaults have been updated
2819            mExistingSystemPackages.clear();
2820            mPromoteSystemApps = false;
2821
2822            // All the changes are done during package scanning.
2823            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2824
2825            // can downgrade to reader
2826            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2827            mSettings.writeLPr();
2828            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2829
2830            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2831            // early on (before the package manager declares itself as early) because other
2832            // components in the system server might ask for package contexts for these apps.
2833            //
2834            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2835            // (i.e, that the data partition is unavailable).
2836            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2837                long start = System.nanoTime();
2838                List<PackageParser.Package> coreApps = new ArrayList<>();
2839                for (PackageParser.Package pkg : mPackages.values()) {
2840                    if (pkg.coreApp) {
2841                        coreApps.add(pkg);
2842                    }
2843                }
2844
2845                int[] stats = performDexOptUpgrade(coreApps, false,
2846                        getCompilerFilterForReason(REASON_CORE_APP));
2847
2848                final int elapsedTimeSeconds =
2849                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2850                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2851
2852                if (DEBUG_DEXOPT) {
2853                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2854                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2855                }
2856
2857
2858                // TODO: Should we log these stats to tron too ?
2859                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2860                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2861                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2862                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2863            }
2864
2865            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2866                    SystemClock.uptimeMillis());
2867
2868            if (!mOnlyCore) {
2869                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2870                mRequiredInstallerPackage = getRequiredInstallerLPr();
2871                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2872                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2873                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2874                        mIntentFilterVerifierComponent);
2875                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2876                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2877                        SharedLibraryInfo.VERSION_UNDEFINED);
2878                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2879                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2880                        SharedLibraryInfo.VERSION_UNDEFINED);
2881            } else {
2882                mRequiredVerifierPackage = null;
2883                mRequiredInstallerPackage = null;
2884                mRequiredUninstallerPackage = null;
2885                mIntentFilterVerifierComponent = null;
2886                mIntentFilterVerifier = null;
2887                mServicesSystemSharedLibraryPackageName = null;
2888                mSharedSystemSharedLibraryPackageName = null;
2889            }
2890
2891            mInstallerService = new PackageInstallerService(context, this);
2892
2893            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2894            if (ephemeralResolverComponent != null) {
2895                if (DEBUG_EPHEMERAL) {
2896                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2897                }
2898                mInstantAppResolverConnection =
2899                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2900            } else {
2901                mInstantAppResolverConnection = null;
2902            }
2903            mInstantAppInstallerComponent = getEphemeralInstallerLPr();
2904            if (mInstantAppInstallerComponent != null) {
2905                if (DEBUG_EPHEMERAL) {
2906                    Slog.i(TAG, "Ephemeral installer: " + mInstantAppInstallerComponent);
2907                }
2908                setUpInstantAppInstallerActivityLP(mInstantAppInstallerComponent);
2909            }
2910
2911            // Read and update the usage of dex files.
2912            // Do this at the end of PM init so that all the packages have their
2913            // data directory reconciled.
2914            // At this point we know the code paths of the packages, so we can validate
2915            // the disk file and build the internal cache.
2916            // The usage file is expected to be small so loading and verifying it
2917            // should take a fairly small time compare to the other activities (e.g. package
2918            // scanning).
2919            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2920            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2921            for (int userId : currentUserIds) {
2922                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2923            }
2924            mDexManager.load(userPackages);
2925        } // synchronized (mPackages)
2926        } // synchronized (mInstallLock)
2927
2928        // Now after opening every single application zip, make sure they
2929        // are all flushed.  Not really needed, but keeps things nice and
2930        // tidy.
2931        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2932        Runtime.getRuntime().gc();
2933        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2934
2935        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2936        FallbackCategoryProvider.loadFallbacks();
2937        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2938
2939        // The initial scanning above does many calls into installd while
2940        // holding the mPackages lock, but we're mostly interested in yelling
2941        // once we have a booted system.
2942        mInstaller.setWarnIfHeld(mPackages);
2943
2944        // Expose private service for system components to use.
2945        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2946        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2947    }
2948
2949    private static File preparePackageParserCache(boolean isUpgrade) {
2950        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2951            return null;
2952        }
2953
2954        // Disable package parsing on eng builds to allow for faster incremental development.
2955        if ("eng".equals(Build.TYPE)) {
2956            return null;
2957        }
2958
2959        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2960            Slog.i(TAG, "Disabling package parser cache due to system property.");
2961            return null;
2962        }
2963
2964        // The base directory for the package parser cache lives under /data/system/.
2965        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2966                "package_cache");
2967        if (cacheBaseDir == null) {
2968            return null;
2969        }
2970
2971        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2972        // This also serves to "GC" unused entries when the package cache version changes (which
2973        // can only happen during upgrades).
2974        if (isUpgrade) {
2975            FileUtils.deleteContents(cacheBaseDir);
2976        }
2977
2978
2979        // Return the versioned package cache directory. This is something like
2980        // "/data/system/package_cache/1"
2981        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2982
2983        // The following is a workaround to aid development on non-numbered userdebug
2984        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2985        // the system partition is newer.
2986        //
2987        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2988        // that starts with "eng." to signify that this is an engineering build and not
2989        // destined for release.
2990        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2991            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2992
2993            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2994            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2995            // in general and should not be used for production changes. In this specific case,
2996            // we know that they will work.
2997            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2998            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2999                FileUtils.deleteContents(cacheBaseDir);
3000                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3001            }
3002        }
3003
3004        return cacheDir;
3005    }
3006
3007    @Override
3008    public boolean isFirstBoot() {
3009        return mFirstBoot;
3010    }
3011
3012    @Override
3013    public boolean isOnlyCoreApps() {
3014        return mOnlyCore;
3015    }
3016
3017    @Override
3018    public boolean isUpgrade() {
3019        return mIsUpgrade;
3020    }
3021
3022    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3023        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3024
3025        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3026                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3027                UserHandle.USER_SYSTEM);
3028        if (matches.size() == 1) {
3029            return matches.get(0).getComponentInfo().packageName;
3030        } else if (matches.size() == 0) {
3031            Log.e(TAG, "There should probably be a verifier, but, none were found");
3032            return null;
3033        }
3034        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3035    }
3036
3037    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3038        synchronized (mPackages) {
3039            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3040            if (libraryEntry == null) {
3041                throw new IllegalStateException("Missing required shared library:" + name);
3042            }
3043            return libraryEntry.apk;
3044        }
3045    }
3046
3047    private @NonNull String getRequiredInstallerLPr() {
3048        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3049        intent.addCategory(Intent.CATEGORY_DEFAULT);
3050        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3051
3052        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3053                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3054                UserHandle.USER_SYSTEM);
3055        if (matches.size() == 1) {
3056            ResolveInfo resolveInfo = matches.get(0);
3057            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3058                throw new RuntimeException("The installer must be a privileged app");
3059            }
3060            return matches.get(0).getComponentInfo().packageName;
3061        } else {
3062            throw new RuntimeException("There must be exactly one installer; found " + matches);
3063        }
3064    }
3065
3066    private @NonNull String getRequiredUninstallerLPr() {
3067        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3068        intent.addCategory(Intent.CATEGORY_DEFAULT);
3069        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3070
3071        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3072                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3073                UserHandle.USER_SYSTEM);
3074        if (resolveInfo == null ||
3075                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3076            throw new RuntimeException("There must be exactly one uninstaller; found "
3077                    + resolveInfo);
3078        }
3079        return resolveInfo.getComponentInfo().packageName;
3080    }
3081
3082    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3083        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3084
3085        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3086                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3087                UserHandle.USER_SYSTEM);
3088        ResolveInfo best = null;
3089        final int N = matches.size();
3090        for (int i = 0; i < N; i++) {
3091            final ResolveInfo cur = matches.get(i);
3092            final String packageName = cur.getComponentInfo().packageName;
3093            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3094                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3095                continue;
3096            }
3097
3098            if (best == null || cur.priority > best.priority) {
3099                best = cur;
3100            }
3101        }
3102
3103        if (best != null) {
3104            return best.getComponentInfo().getComponentName();
3105        } else {
3106            throw new RuntimeException("There must be at least one intent filter verifier");
3107        }
3108    }
3109
3110    private @Nullable ComponentName getEphemeralResolverLPr() {
3111        final String[] packageArray =
3112                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3113        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3114            if (DEBUG_EPHEMERAL) {
3115                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3116            }
3117            return null;
3118        }
3119
3120        final int resolveFlags =
3121                MATCH_DIRECT_BOOT_AWARE
3122                | MATCH_DIRECT_BOOT_UNAWARE
3123                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3124        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3125        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3126                resolveFlags, UserHandle.USER_SYSTEM);
3127
3128        final int N = resolvers.size();
3129        if (N == 0) {
3130            if (DEBUG_EPHEMERAL) {
3131                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3132            }
3133            return null;
3134        }
3135
3136        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3137        for (int i = 0; i < N; i++) {
3138            final ResolveInfo info = resolvers.get(i);
3139
3140            if (info.serviceInfo == null) {
3141                continue;
3142            }
3143
3144            final String packageName = info.serviceInfo.packageName;
3145            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3146                if (DEBUG_EPHEMERAL) {
3147                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3148                            + " pkg: " + packageName + ", info:" + info);
3149                }
3150                continue;
3151            }
3152
3153            if (DEBUG_EPHEMERAL) {
3154                Slog.v(TAG, "Ephemeral resolver found;"
3155                        + " pkg: " + packageName + ", info:" + info);
3156            }
3157            return new ComponentName(packageName, info.serviceInfo.name);
3158        }
3159        if (DEBUG_EPHEMERAL) {
3160            Slog.v(TAG, "Ephemeral resolver NOT found");
3161        }
3162        return null;
3163    }
3164
3165    private @Nullable ComponentName getEphemeralInstallerLPr() {
3166        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3167        intent.addCategory(Intent.CATEGORY_DEFAULT);
3168        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3169
3170        final int resolveFlags =
3171                MATCH_DIRECT_BOOT_AWARE
3172                | MATCH_DIRECT_BOOT_UNAWARE
3173                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3174        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3175                resolveFlags, UserHandle.USER_SYSTEM);
3176        Iterator<ResolveInfo> iter = matches.iterator();
3177        while (iter.hasNext()) {
3178            final ResolveInfo rInfo = iter.next();
3179            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3180            if (ps != null) {
3181                final PermissionsState permissionsState = ps.getPermissionsState();
3182                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3183                    continue;
3184                }
3185            }
3186            iter.remove();
3187        }
3188        if (matches.size() == 0) {
3189            return null;
3190        } else if (matches.size() == 1) {
3191            return matches.get(0).getComponentInfo().getComponentName();
3192        } else {
3193            throw new RuntimeException(
3194                    "There must be at most one ephemeral installer; found " + matches);
3195        }
3196    }
3197
3198    private void primeDomainVerificationsLPw(int userId) {
3199        if (DEBUG_DOMAIN_VERIFICATION) {
3200            Slog.d(TAG, "Priming domain verifications in user " + userId);
3201        }
3202
3203        SystemConfig systemConfig = SystemConfig.getInstance();
3204        ArraySet<String> packages = systemConfig.getLinkedApps();
3205
3206        for (String packageName : packages) {
3207            PackageParser.Package pkg = mPackages.get(packageName);
3208            if (pkg != null) {
3209                if (!pkg.isSystemApp()) {
3210                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3211                    continue;
3212                }
3213
3214                ArraySet<String> domains = null;
3215                for (PackageParser.Activity a : pkg.activities) {
3216                    for (ActivityIntentInfo filter : a.intents) {
3217                        if (hasValidDomains(filter)) {
3218                            if (domains == null) {
3219                                domains = new ArraySet<String>();
3220                            }
3221                            domains.addAll(filter.getHostsList());
3222                        }
3223                    }
3224                }
3225
3226                if (domains != null && domains.size() > 0) {
3227                    if (DEBUG_DOMAIN_VERIFICATION) {
3228                        Slog.v(TAG, "      + " + packageName);
3229                    }
3230                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3231                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3232                    // and then 'always' in the per-user state actually used for intent resolution.
3233                    final IntentFilterVerificationInfo ivi;
3234                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3235                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3236                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3237                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3238                } else {
3239                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3240                            + "' does not handle web links");
3241                }
3242            } else {
3243                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3244            }
3245        }
3246
3247        scheduleWritePackageRestrictionsLocked(userId);
3248        scheduleWriteSettingsLocked();
3249    }
3250
3251    private void applyFactoryDefaultBrowserLPw(int userId) {
3252        // The default browser app's package name is stored in a string resource,
3253        // with a product-specific overlay used for vendor customization.
3254        String browserPkg = mContext.getResources().getString(
3255                com.android.internal.R.string.default_browser);
3256        if (!TextUtils.isEmpty(browserPkg)) {
3257            // non-empty string => required to be a known package
3258            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3259            if (ps == null) {
3260                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3261                browserPkg = null;
3262            } else {
3263                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3264            }
3265        }
3266
3267        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3268        // default.  If there's more than one, just leave everything alone.
3269        if (browserPkg == null) {
3270            calculateDefaultBrowserLPw(userId);
3271        }
3272    }
3273
3274    private void calculateDefaultBrowserLPw(int userId) {
3275        List<String> allBrowsers = resolveAllBrowserApps(userId);
3276        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3277        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3278    }
3279
3280    private List<String> resolveAllBrowserApps(int userId) {
3281        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3282        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3283                PackageManager.MATCH_ALL, userId);
3284
3285        final int count = list.size();
3286        List<String> result = new ArrayList<String>(count);
3287        for (int i=0; i<count; i++) {
3288            ResolveInfo info = list.get(i);
3289            if (info.activityInfo == null
3290                    || !info.handleAllWebDataURI
3291                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3292                    || result.contains(info.activityInfo.packageName)) {
3293                continue;
3294            }
3295            result.add(info.activityInfo.packageName);
3296        }
3297
3298        return result;
3299    }
3300
3301    private boolean packageIsBrowser(String packageName, int userId) {
3302        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3303                PackageManager.MATCH_ALL, userId);
3304        final int N = list.size();
3305        for (int i = 0; i < N; i++) {
3306            ResolveInfo info = list.get(i);
3307            if (packageName.equals(info.activityInfo.packageName)) {
3308                return true;
3309            }
3310        }
3311        return false;
3312    }
3313
3314    private void checkDefaultBrowser() {
3315        final int myUserId = UserHandle.myUserId();
3316        final String packageName = getDefaultBrowserPackageName(myUserId);
3317        if (packageName != null) {
3318            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3319            if (info == null) {
3320                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3321                synchronized (mPackages) {
3322                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3323                }
3324            }
3325        }
3326    }
3327
3328    @Override
3329    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3330            throws RemoteException {
3331        try {
3332            return super.onTransact(code, data, reply, flags);
3333        } catch (RuntimeException e) {
3334            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3335                Slog.wtf(TAG, "Package Manager Crash", e);
3336            }
3337            throw e;
3338        }
3339    }
3340
3341    static int[] appendInts(int[] cur, int[] add) {
3342        if (add == null) return cur;
3343        if (cur == null) return add;
3344        final int N = add.length;
3345        for (int i=0; i<N; i++) {
3346            cur = appendInt(cur, add[i]);
3347        }
3348        return cur;
3349    }
3350
3351    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3352        if (!sUserManager.exists(userId)) return null;
3353        if (ps == null) {
3354            return null;
3355        }
3356        final PackageParser.Package p = ps.pkg;
3357        if (p == null) {
3358            return null;
3359        }
3360        // Filter out ephemeral app metadata:
3361        //   * The system/shell/root can see metadata for any app
3362        //   * An installed app can see metadata for 1) other installed apps
3363        //     and 2) ephemeral apps that have explicitly interacted with it
3364        //   * Ephemeral apps can only see their own metadata
3365        //   * Holding a signature permission allows seeing instant apps
3366        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3367        if (callingAppId != Process.SYSTEM_UID
3368                && callingAppId != Process.SHELL_UID
3369                && callingAppId != Process.ROOT_UID
3370                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3371                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3372            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3373            if (instantAppPackageName != null) {
3374                // ephemeral apps can only get information on themselves
3375                if (!instantAppPackageName.equals(p.packageName)) {
3376                    return null;
3377                }
3378            } else {
3379                if (ps.getInstantApp(userId)) {
3380                    // only get access to the ephemeral app if we've been granted access
3381                    if (!mInstantAppRegistry.isInstantAccessGranted(
3382                            userId, callingAppId, ps.appId)) {
3383                        return null;
3384                    }
3385                }
3386            }
3387        }
3388
3389        final PermissionsState permissionsState = ps.getPermissionsState();
3390
3391        // Compute GIDs only if requested
3392        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3393                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3394        // Compute granted permissions only if package has requested permissions
3395        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3396                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3397        final PackageUserState state = ps.readUserState(userId);
3398
3399        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3400                && ps.isSystem()) {
3401            flags |= MATCH_ANY_USER;
3402        }
3403
3404        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3405                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3406
3407        if (packageInfo == null) {
3408            return null;
3409        }
3410
3411        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3412                resolveExternalPackageNameLPr(p);
3413
3414        return packageInfo;
3415    }
3416
3417    @Override
3418    public void checkPackageStartable(String packageName, int userId) {
3419        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3420
3421        synchronized (mPackages) {
3422            final PackageSetting ps = mSettings.mPackages.get(packageName);
3423            if (ps == null) {
3424                throw new SecurityException("Package " + packageName + " was not found!");
3425            }
3426
3427            if (!ps.getInstalled(userId)) {
3428                throw new SecurityException(
3429                        "Package " + packageName + " was not installed for user " + userId + "!");
3430            }
3431
3432            if (mSafeMode && !ps.isSystem()) {
3433                throw new SecurityException("Package " + packageName + " not a system app!");
3434            }
3435
3436            if (mFrozenPackages.contains(packageName)) {
3437                throw new SecurityException("Package " + packageName + " is currently frozen!");
3438            }
3439
3440            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3441                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3442                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3443            }
3444        }
3445    }
3446
3447    @Override
3448    public boolean isPackageAvailable(String packageName, int userId) {
3449        if (!sUserManager.exists(userId)) return false;
3450        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3451                false /* requireFullPermission */, false /* checkShell */, "is package available");
3452        synchronized (mPackages) {
3453            PackageParser.Package p = mPackages.get(packageName);
3454            if (p != null) {
3455                final PackageSetting ps = (PackageSetting) p.mExtras;
3456                if (ps != null) {
3457                    final PackageUserState state = ps.readUserState(userId);
3458                    if (state != null) {
3459                        return PackageParser.isAvailable(state);
3460                    }
3461                }
3462            }
3463        }
3464        return false;
3465    }
3466
3467    @Override
3468    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3469        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3470                flags, userId);
3471    }
3472
3473    @Override
3474    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3475            int flags, int userId) {
3476        return getPackageInfoInternal(versionedPackage.getPackageName(),
3477                // TODO: We will change version code to long, so in the new API it is long
3478                (int) versionedPackage.getVersionCode(), flags, userId);
3479    }
3480
3481    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3482            int flags, int userId) {
3483        if (!sUserManager.exists(userId)) return null;
3484        flags = updateFlagsForPackage(flags, userId, packageName);
3485        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3486                false /* requireFullPermission */, false /* checkShell */, "get package info");
3487
3488        // reader
3489        synchronized (mPackages) {
3490            // Normalize package name to handle renamed packages and static libs
3491            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3492
3493            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3494            if (matchFactoryOnly) {
3495                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3496                if (ps != null) {
3497                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3498                        return null;
3499                    }
3500                    return generatePackageInfo(ps, flags, userId);
3501                }
3502            }
3503
3504            PackageParser.Package p = mPackages.get(packageName);
3505            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3506                return null;
3507            }
3508            if (DEBUG_PACKAGE_INFO)
3509                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3510            if (p != null) {
3511                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3512                        Binder.getCallingUid(), userId)) {
3513                    return null;
3514                }
3515                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3516            }
3517            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3518                final PackageSetting ps = mSettings.mPackages.get(packageName);
3519                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3520                    return null;
3521                }
3522                return generatePackageInfo(ps, flags, userId);
3523            }
3524        }
3525        return null;
3526    }
3527
3528
3529    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3530        // System/shell/root get to see all static libs
3531        final int appId = UserHandle.getAppId(uid);
3532        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3533                || appId == Process.ROOT_UID) {
3534            return false;
3535        }
3536
3537        // No package means no static lib as it is always on internal storage
3538        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3539            return false;
3540        }
3541
3542        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3543                ps.pkg.staticSharedLibVersion);
3544        if (libEntry == null) {
3545            return false;
3546        }
3547
3548        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3549        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3550        if (uidPackageNames == null) {
3551            return true;
3552        }
3553
3554        for (String uidPackageName : uidPackageNames) {
3555            if (ps.name.equals(uidPackageName)) {
3556                return false;
3557            }
3558            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3559            if (uidPs != null) {
3560                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3561                        libEntry.info.getName());
3562                if (index < 0) {
3563                    continue;
3564                }
3565                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3566                    return false;
3567                }
3568            }
3569        }
3570        return true;
3571    }
3572
3573    @Override
3574    public String[] currentToCanonicalPackageNames(String[] names) {
3575        String[] out = new String[names.length];
3576        // reader
3577        synchronized (mPackages) {
3578            for (int i=names.length-1; i>=0; i--) {
3579                PackageSetting ps = mSettings.mPackages.get(names[i]);
3580                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3581            }
3582        }
3583        return out;
3584    }
3585
3586    @Override
3587    public String[] canonicalToCurrentPackageNames(String[] names) {
3588        String[] out = new String[names.length];
3589        // reader
3590        synchronized (mPackages) {
3591            for (int i=names.length-1; i>=0; i--) {
3592                String cur = mSettings.getRenamedPackageLPr(names[i]);
3593                out[i] = cur != null ? cur : names[i];
3594            }
3595        }
3596        return out;
3597    }
3598
3599    @Override
3600    public int getPackageUid(String packageName, int flags, int userId) {
3601        if (!sUserManager.exists(userId)) return -1;
3602        flags = updateFlagsForPackage(flags, userId, packageName);
3603        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3604                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3605
3606        // reader
3607        synchronized (mPackages) {
3608            final PackageParser.Package p = mPackages.get(packageName);
3609            if (p != null && p.isMatch(flags)) {
3610                return UserHandle.getUid(userId, p.applicationInfo.uid);
3611            }
3612            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3613                final PackageSetting ps = mSettings.mPackages.get(packageName);
3614                if (ps != null && ps.isMatch(flags)) {
3615                    return UserHandle.getUid(userId, ps.appId);
3616                }
3617            }
3618        }
3619
3620        return -1;
3621    }
3622
3623    @Override
3624    public int[] getPackageGids(String packageName, int flags, int userId) {
3625        if (!sUserManager.exists(userId)) return null;
3626        flags = updateFlagsForPackage(flags, userId, packageName);
3627        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3628                false /* requireFullPermission */, false /* checkShell */,
3629                "getPackageGids");
3630
3631        // reader
3632        synchronized (mPackages) {
3633            final PackageParser.Package p = mPackages.get(packageName);
3634            if (p != null && p.isMatch(flags)) {
3635                PackageSetting ps = (PackageSetting) p.mExtras;
3636                // TODO: Shouldn't this be checking for package installed state for userId and
3637                // return null?
3638                return ps.getPermissionsState().computeGids(userId);
3639            }
3640            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3641                final PackageSetting ps = mSettings.mPackages.get(packageName);
3642                if (ps != null && ps.isMatch(flags)) {
3643                    return ps.getPermissionsState().computeGids(userId);
3644                }
3645            }
3646        }
3647
3648        return null;
3649    }
3650
3651    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3652        if (bp.perm != null) {
3653            return PackageParser.generatePermissionInfo(bp.perm, flags);
3654        }
3655        PermissionInfo pi = new PermissionInfo();
3656        pi.name = bp.name;
3657        pi.packageName = bp.sourcePackage;
3658        pi.nonLocalizedLabel = bp.name;
3659        pi.protectionLevel = bp.protectionLevel;
3660        return pi;
3661    }
3662
3663    @Override
3664    public PermissionInfo getPermissionInfo(String name, int flags) {
3665        // reader
3666        synchronized (mPackages) {
3667            final BasePermission p = mSettings.mPermissions.get(name);
3668            if (p != null) {
3669                return generatePermissionInfo(p, flags);
3670            }
3671            return null;
3672        }
3673    }
3674
3675    @Override
3676    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3677            int flags) {
3678        // reader
3679        synchronized (mPackages) {
3680            if (group != null && !mPermissionGroups.containsKey(group)) {
3681                // This is thrown as NameNotFoundException
3682                return null;
3683            }
3684
3685            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3686            for (BasePermission p : mSettings.mPermissions.values()) {
3687                if (group == null) {
3688                    if (p.perm == null || p.perm.info.group == null) {
3689                        out.add(generatePermissionInfo(p, flags));
3690                    }
3691                } else {
3692                    if (p.perm != null && group.equals(p.perm.info.group)) {
3693                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3694                    }
3695                }
3696            }
3697            return new ParceledListSlice<>(out);
3698        }
3699    }
3700
3701    @Override
3702    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3703        // reader
3704        synchronized (mPackages) {
3705            return PackageParser.generatePermissionGroupInfo(
3706                    mPermissionGroups.get(name), flags);
3707        }
3708    }
3709
3710    @Override
3711    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3712        // reader
3713        synchronized (mPackages) {
3714            final int N = mPermissionGroups.size();
3715            ArrayList<PermissionGroupInfo> out
3716                    = new ArrayList<PermissionGroupInfo>(N);
3717            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3718                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3719            }
3720            return new ParceledListSlice<>(out);
3721        }
3722    }
3723
3724    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3725            int uid, int userId) {
3726        if (!sUserManager.exists(userId)) return null;
3727        PackageSetting ps = mSettings.mPackages.get(packageName);
3728        if (ps != null) {
3729            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3730                return null;
3731            }
3732            if (ps.pkg == null) {
3733                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3734                if (pInfo != null) {
3735                    return pInfo.applicationInfo;
3736                }
3737                return null;
3738            }
3739            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3740                    ps.readUserState(userId), userId);
3741            if (ai != null) {
3742                rebaseEnabledOverlays(ai, userId);
3743                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3744            }
3745            return ai;
3746        }
3747        return null;
3748    }
3749
3750    @Override
3751    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3752        if (!sUserManager.exists(userId)) return null;
3753        flags = updateFlagsForApplication(flags, userId, packageName);
3754        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3755                false /* requireFullPermission */, false /* checkShell */, "get application info");
3756
3757        // writer
3758        synchronized (mPackages) {
3759            // Normalize package name to handle renamed packages and static libs
3760            packageName = resolveInternalPackageNameLPr(packageName,
3761                    PackageManager.VERSION_CODE_HIGHEST);
3762
3763            PackageParser.Package p = mPackages.get(packageName);
3764            if (DEBUG_PACKAGE_INFO) Log.v(
3765                    TAG, "getApplicationInfo " + packageName
3766                    + ": " + p);
3767            if (p != null) {
3768                PackageSetting ps = mSettings.mPackages.get(packageName);
3769                if (ps == null) return null;
3770                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3771                    return null;
3772                }
3773                // Note: isEnabledLP() does not apply here - always return info
3774                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3775                        p, flags, ps.readUserState(userId), userId);
3776                if (ai != null) {
3777                    rebaseEnabledOverlays(ai, userId);
3778                    ai.packageName = resolveExternalPackageNameLPr(p);
3779                }
3780                return ai;
3781            }
3782            if ("android".equals(packageName)||"system".equals(packageName)) {
3783                return mAndroidApplication;
3784            }
3785            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3786                // Already generates the external package name
3787                return generateApplicationInfoFromSettingsLPw(packageName,
3788                        Binder.getCallingUid(), flags, userId);
3789            }
3790        }
3791        return null;
3792    }
3793
3794    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3795        List<String> paths = new ArrayList<>();
3796        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3797            mEnabledOverlayPaths.get(userId);
3798        if (userSpecificOverlays != null) {
3799            if (!"android".equals(ai.packageName)) {
3800                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3801                if (frameworkOverlays != null) {
3802                    paths.addAll(frameworkOverlays);
3803                }
3804            }
3805
3806            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3807            if (appOverlays != null) {
3808                paths.addAll(appOverlays);
3809            }
3810        }
3811        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3812    }
3813
3814    private String normalizePackageNameLPr(String packageName) {
3815        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3816        return normalizedPackageName != null ? normalizedPackageName : packageName;
3817    }
3818
3819    @Override
3820    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3821            final IPackageDataObserver observer) {
3822        mContext.enforceCallingOrSelfPermission(
3823                android.Manifest.permission.CLEAR_APP_CACHE, null);
3824        mHandler.post(() -> {
3825            boolean success = false;
3826            try {
3827                freeStorage(volumeUuid, freeStorageSize, 0);
3828                success = true;
3829            } catch (IOException e) {
3830                Slog.w(TAG, e);
3831            }
3832            if (observer != null) {
3833                try {
3834                    observer.onRemoveCompleted(null, success);
3835                } catch (RemoteException e) {
3836                    Slog.w(TAG, e);
3837                }
3838            }
3839        });
3840    }
3841
3842    @Override
3843    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3844            final IntentSender pi) {
3845        mContext.enforceCallingOrSelfPermission(
3846                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3847        mHandler.post(() -> {
3848            boolean success = false;
3849            try {
3850                freeStorage(volumeUuid, freeStorageSize, 0);
3851                success = true;
3852            } catch (IOException e) {
3853                Slog.w(TAG, e);
3854            }
3855            if (pi != null) {
3856                try {
3857                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3858                } catch (SendIntentException e) {
3859                    Slog.w(TAG, e);
3860                }
3861            }
3862        });
3863    }
3864
3865    /**
3866     * Blocking call to clear various types of cached data across the system
3867     * until the requested bytes are available.
3868     */
3869    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3870        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3871        final File file = storage.findPathForUuid(volumeUuid);
3872
3873        if (ENABLE_FREE_CACHE_V2) {
3874            final boolean aggressive = (storageFlags
3875                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3876
3877            // 1. Pre-flight to determine if we have any chance to succeed
3878            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3879
3880            // 3. Consider parsed APK data (aggressive only)
3881            if (aggressive) {
3882                FileUtils.deleteContents(mCacheDir);
3883            }
3884            if (file.getUsableSpace() >= bytes) return;
3885
3886            // 4. Consider cached app data (above quotas)
3887            try {
3888                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3889            } catch (InstallerException ignored) {
3890            }
3891            if (file.getUsableSpace() >= bytes) return;
3892
3893            // 5. Consider shared libraries with refcount=0 and age>2h
3894            // 6. Consider dexopt output (aggressive only)
3895            // 7. Consider ephemeral apps not used in last week
3896
3897            // 8. Consider cached app data (below quotas)
3898            try {
3899                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3900                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3901            } catch (InstallerException ignored) {
3902            }
3903            if (file.getUsableSpace() >= bytes) return;
3904
3905            // 9. Consider DropBox entries
3906            // 10. Consider ephemeral cookies
3907
3908        } else {
3909            try {
3910                mInstaller.freeCache(volumeUuid, bytes, 0);
3911            } catch (InstallerException ignored) {
3912            }
3913            if (file.getUsableSpace() >= bytes) return;
3914        }
3915
3916        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3917    }
3918
3919    /**
3920     * Update given flags based on encryption status of current user.
3921     */
3922    private int updateFlags(int flags, int userId) {
3923        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3924                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3925            // Caller expressed an explicit opinion about what encryption
3926            // aware/unaware components they want to see, so fall through and
3927            // give them what they want
3928        } else {
3929            // Caller expressed no opinion, so match based on user state
3930            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3931                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3932            } else {
3933                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3934            }
3935        }
3936        return flags;
3937    }
3938
3939    private UserManagerInternal getUserManagerInternal() {
3940        if (mUserManagerInternal == null) {
3941            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3942        }
3943        return mUserManagerInternal;
3944    }
3945
3946    private DeviceIdleController.LocalService getDeviceIdleController() {
3947        if (mDeviceIdleController == null) {
3948            mDeviceIdleController =
3949                    LocalServices.getService(DeviceIdleController.LocalService.class);
3950        }
3951        return mDeviceIdleController;
3952    }
3953
3954    /**
3955     * Update given flags when being used to request {@link PackageInfo}.
3956     */
3957    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3958        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3959        boolean triaged = true;
3960        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3961                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3962            // Caller is asking for component details, so they'd better be
3963            // asking for specific encryption matching behavior, or be triaged
3964            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3965                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3966                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3967                triaged = false;
3968            }
3969        }
3970        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3971                | PackageManager.MATCH_SYSTEM_ONLY
3972                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3973            triaged = false;
3974        }
3975        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3976            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3977                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3978                    + Debug.getCallers(5));
3979        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3980                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3981            // If the caller wants all packages and has a restricted profile associated with it,
3982            // then match all users. This is to make sure that launchers that need to access work
3983            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3984            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3985            flags |= PackageManager.MATCH_ANY_USER;
3986        }
3987        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3988            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3989                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3990        }
3991        return updateFlags(flags, userId);
3992    }
3993
3994    /**
3995     * Update given flags when being used to request {@link ApplicationInfo}.
3996     */
3997    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3998        return updateFlagsForPackage(flags, userId, cookie);
3999    }
4000
4001    /**
4002     * Update given flags when being used to request {@link ComponentInfo}.
4003     */
4004    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4005        if (cookie instanceof Intent) {
4006            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4007                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4008            }
4009        }
4010
4011        boolean triaged = true;
4012        // Caller is asking for component details, so they'd better be
4013        // asking for specific encryption matching behavior, or be triaged
4014        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4015                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4016                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4017            triaged = false;
4018        }
4019        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4020            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4021                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4022        }
4023
4024        return updateFlags(flags, userId);
4025    }
4026
4027    /**
4028     * Update given intent when being used to request {@link ResolveInfo}.
4029     */
4030    private Intent updateIntentForResolve(Intent intent) {
4031        if (intent.getSelector() != null) {
4032            intent = intent.getSelector();
4033        }
4034        if (DEBUG_PREFERRED) {
4035            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4036        }
4037        return intent;
4038    }
4039
4040    /**
4041     * Update given flags when being used to request {@link ResolveInfo}.
4042     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4043     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4044     * flag set. However, this flag is only honoured in three circumstances:
4045     * <ul>
4046     * <li>when called from a system process</li>
4047     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4048     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4049     * action and a {@code android.intent.category.BROWSABLE} category</li>
4050     * </ul>
4051     */
4052    int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) {
4053        // Safe mode means we shouldn't match any third-party components
4054        if (mSafeMode) {
4055            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4056        }
4057        final int callingUid = Binder.getCallingUid();
4058        if (getInstantAppPackageName(callingUid) != null) {
4059            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4060            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4061            flags |= PackageManager.MATCH_INSTANT;
4062        } else {
4063            // Otherwise, prevent leaking ephemeral components
4064            final boolean isSpecialProcess =
4065                    callingUid == Process.SYSTEM_UID
4066                    || callingUid == Process.SHELL_UID
4067                    || callingUid == 0;
4068            final boolean allowMatchInstant =
4069                    (includeInstantApp
4070                            && Intent.ACTION_VIEW.equals(intent.getAction())
4071                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4072                            && hasWebURI(intent))
4073                    || isSpecialProcess
4074                    || mContext.checkCallingOrSelfPermission(
4075                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4076            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4077            if (!allowMatchInstant) {
4078                flags &= ~PackageManager.MATCH_INSTANT;
4079            }
4080        }
4081        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4082    }
4083
4084    @Override
4085    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4086        if (!sUserManager.exists(userId)) return null;
4087        flags = updateFlagsForComponent(flags, userId, component);
4088        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4089                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4090        synchronized (mPackages) {
4091            PackageParser.Activity a = mActivities.mActivities.get(component);
4092
4093            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4094            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4095                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4096                if (ps == null) return null;
4097                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4098                        userId);
4099            }
4100            if (mResolveComponentName.equals(component)) {
4101                return PackageParser.generateActivityInfo(mResolveActivity, flags,
4102                        new PackageUserState(), userId);
4103            }
4104        }
4105        return null;
4106    }
4107
4108    @Override
4109    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4110            String resolvedType) {
4111        synchronized (mPackages) {
4112            if (component.equals(mResolveComponentName)) {
4113                // The resolver supports EVERYTHING!
4114                return true;
4115            }
4116            PackageParser.Activity a = mActivities.mActivities.get(component);
4117            if (a == null) {
4118                return false;
4119            }
4120            for (int i=0; i<a.intents.size(); i++) {
4121                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4122                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4123                    return true;
4124                }
4125            }
4126            return false;
4127        }
4128    }
4129
4130    @Override
4131    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4132        if (!sUserManager.exists(userId)) return null;
4133        flags = updateFlagsForComponent(flags, userId, component);
4134        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4135                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4136        synchronized (mPackages) {
4137            PackageParser.Activity a = mReceivers.mActivities.get(component);
4138            if (DEBUG_PACKAGE_INFO) Log.v(
4139                TAG, "getReceiverInfo " + component + ": " + a);
4140            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4141                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4142                if (ps == null) return null;
4143                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4144                        userId);
4145            }
4146        }
4147        return null;
4148    }
4149
4150    @Override
4151    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4152        if (!sUserManager.exists(userId)) return null;
4153        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4154
4155        flags = updateFlagsForPackage(flags, userId, null);
4156
4157        final boolean canSeeStaticLibraries =
4158                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4159                        == PERMISSION_GRANTED
4160                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4161                        == PERMISSION_GRANTED
4162                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4163                        == PERMISSION_GRANTED
4164                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4165                        == PERMISSION_GRANTED;
4166
4167        synchronized (mPackages) {
4168            List<SharedLibraryInfo> result = null;
4169
4170            final int libCount = mSharedLibraries.size();
4171            for (int i = 0; i < libCount; i++) {
4172                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4173                if (versionedLib == null) {
4174                    continue;
4175                }
4176
4177                final int versionCount = versionedLib.size();
4178                for (int j = 0; j < versionCount; j++) {
4179                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4180                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4181                        break;
4182                    }
4183                    final long identity = Binder.clearCallingIdentity();
4184                    try {
4185                        // TODO: We will change version code to long, so in the new API it is long
4186                        PackageInfo packageInfo = getPackageInfoVersioned(
4187                                libInfo.getDeclaringPackage(), flags, userId);
4188                        if (packageInfo == null) {
4189                            continue;
4190                        }
4191                    } finally {
4192                        Binder.restoreCallingIdentity(identity);
4193                    }
4194
4195                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4196                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4197                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4198
4199                    if (result == null) {
4200                        result = new ArrayList<>();
4201                    }
4202                    result.add(resLibInfo);
4203                }
4204            }
4205
4206            return result != null ? new ParceledListSlice<>(result) : null;
4207        }
4208    }
4209
4210    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4211            SharedLibraryInfo libInfo, int flags, int userId) {
4212        List<VersionedPackage> versionedPackages = null;
4213        final int packageCount = mSettings.mPackages.size();
4214        for (int i = 0; i < packageCount; i++) {
4215            PackageSetting ps = mSettings.mPackages.valueAt(i);
4216
4217            if (ps == null) {
4218                continue;
4219            }
4220
4221            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4222                continue;
4223            }
4224
4225            final String libName = libInfo.getName();
4226            if (libInfo.isStatic()) {
4227                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4228                if (libIdx < 0) {
4229                    continue;
4230                }
4231                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4232                    continue;
4233                }
4234                if (versionedPackages == null) {
4235                    versionedPackages = new ArrayList<>();
4236                }
4237                // If the dependent is a static shared lib, use the public package name
4238                String dependentPackageName = ps.name;
4239                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4240                    dependentPackageName = ps.pkg.manifestPackageName;
4241                }
4242                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4243            } else if (ps.pkg != null) {
4244                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4245                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4246                    if (versionedPackages == null) {
4247                        versionedPackages = new ArrayList<>();
4248                    }
4249                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4250                }
4251            }
4252        }
4253
4254        return versionedPackages;
4255    }
4256
4257    @Override
4258    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4259        if (!sUserManager.exists(userId)) return null;
4260        flags = updateFlagsForComponent(flags, userId, component);
4261        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4262                false /* requireFullPermission */, false /* checkShell */, "get service info");
4263        synchronized (mPackages) {
4264            PackageParser.Service s = mServices.mServices.get(component);
4265            if (DEBUG_PACKAGE_INFO) Log.v(
4266                TAG, "getServiceInfo " + component + ": " + s);
4267            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4268                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4269                if (ps == null) return null;
4270                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
4271                        userId);
4272            }
4273        }
4274        return null;
4275    }
4276
4277    @Override
4278    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4279        if (!sUserManager.exists(userId)) return null;
4280        flags = updateFlagsForComponent(flags, userId, component);
4281        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4282                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4283        synchronized (mPackages) {
4284            PackageParser.Provider p = mProviders.mProviders.get(component);
4285            if (DEBUG_PACKAGE_INFO) Log.v(
4286                TAG, "getProviderInfo " + component + ": " + p);
4287            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4288                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4289                if (ps == null) return null;
4290                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
4291                        userId);
4292            }
4293        }
4294        return null;
4295    }
4296
4297    @Override
4298    public String[] getSystemSharedLibraryNames() {
4299        synchronized (mPackages) {
4300            Set<String> libs = null;
4301            final int libCount = mSharedLibraries.size();
4302            for (int i = 0; i < libCount; i++) {
4303                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4304                if (versionedLib == null) {
4305                    continue;
4306                }
4307                final int versionCount = versionedLib.size();
4308                for (int j = 0; j < versionCount; j++) {
4309                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4310                    if (!libEntry.info.isStatic()) {
4311                        if (libs == null) {
4312                            libs = new ArraySet<>();
4313                        }
4314                        libs.add(libEntry.info.getName());
4315                        break;
4316                    }
4317                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4318                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4319                            UserHandle.getUserId(Binder.getCallingUid()))) {
4320                        if (libs == null) {
4321                            libs = new ArraySet<>();
4322                        }
4323                        libs.add(libEntry.info.getName());
4324                        break;
4325                    }
4326                }
4327            }
4328
4329            if (libs != null) {
4330                String[] libsArray = new String[libs.size()];
4331                libs.toArray(libsArray);
4332                return libsArray;
4333            }
4334
4335            return null;
4336        }
4337    }
4338
4339    @Override
4340    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4341        synchronized (mPackages) {
4342            return mServicesSystemSharedLibraryPackageName;
4343        }
4344    }
4345
4346    @Override
4347    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4348        synchronized (mPackages) {
4349            return mSharedSystemSharedLibraryPackageName;
4350        }
4351    }
4352
4353    private void updateSequenceNumberLP(String packageName, int[] userList) {
4354        for (int i = userList.length - 1; i >= 0; --i) {
4355            final int userId = userList[i];
4356            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4357            if (changedPackages == null) {
4358                changedPackages = new SparseArray<>();
4359                mChangedPackages.put(userId, changedPackages);
4360            }
4361            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4362            if (sequenceNumbers == null) {
4363                sequenceNumbers = new HashMap<>();
4364                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4365            }
4366            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4367            if (sequenceNumber != null) {
4368                changedPackages.remove(sequenceNumber);
4369            }
4370            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4371            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4372        }
4373        mChangedPackagesSequenceNumber++;
4374    }
4375
4376    @Override
4377    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4378        synchronized (mPackages) {
4379            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4380                return null;
4381            }
4382            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4383            if (changedPackages == null) {
4384                return null;
4385            }
4386            final List<String> packageNames =
4387                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4388            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4389                final String packageName = changedPackages.get(i);
4390                if (packageName != null) {
4391                    packageNames.add(packageName);
4392                }
4393            }
4394            return packageNames.isEmpty()
4395                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4396        }
4397    }
4398
4399    @Override
4400    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4401        ArrayList<FeatureInfo> res;
4402        synchronized (mAvailableFeatures) {
4403            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4404            res.addAll(mAvailableFeatures.values());
4405        }
4406        final FeatureInfo fi = new FeatureInfo();
4407        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4408                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4409        res.add(fi);
4410
4411        return new ParceledListSlice<>(res);
4412    }
4413
4414    @Override
4415    public boolean hasSystemFeature(String name, int version) {
4416        synchronized (mAvailableFeatures) {
4417            final FeatureInfo feat = mAvailableFeatures.get(name);
4418            if (feat == null) {
4419                return false;
4420            } else {
4421                return feat.version >= version;
4422            }
4423        }
4424    }
4425
4426    @Override
4427    public int checkPermission(String permName, String pkgName, int userId) {
4428        if (!sUserManager.exists(userId)) {
4429            return PackageManager.PERMISSION_DENIED;
4430        }
4431
4432        synchronized (mPackages) {
4433            final PackageParser.Package p = mPackages.get(pkgName);
4434            if (p != null && p.mExtras != null) {
4435                final PackageSetting ps = (PackageSetting) p.mExtras;
4436                final PermissionsState permissionsState = ps.getPermissionsState();
4437                if (permissionsState.hasPermission(permName, userId)) {
4438                    return PackageManager.PERMISSION_GRANTED;
4439                }
4440                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4441                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4442                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4443                    return PackageManager.PERMISSION_GRANTED;
4444                }
4445            }
4446        }
4447
4448        return PackageManager.PERMISSION_DENIED;
4449    }
4450
4451    @Override
4452    public int checkUidPermission(String permName, int uid) {
4453        final int userId = UserHandle.getUserId(uid);
4454
4455        if (!sUserManager.exists(userId)) {
4456            return PackageManager.PERMISSION_DENIED;
4457        }
4458
4459        synchronized (mPackages) {
4460            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4461            if (obj != null) {
4462                final SettingBase ps = (SettingBase) obj;
4463                final PermissionsState permissionsState = ps.getPermissionsState();
4464                if (permissionsState.hasPermission(permName, userId)) {
4465                    return PackageManager.PERMISSION_GRANTED;
4466                }
4467                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4468                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4469                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4470                    return PackageManager.PERMISSION_GRANTED;
4471                }
4472            } else {
4473                ArraySet<String> perms = mSystemPermissions.get(uid);
4474                if (perms != null) {
4475                    if (perms.contains(permName)) {
4476                        return PackageManager.PERMISSION_GRANTED;
4477                    }
4478                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4479                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4480                        return PackageManager.PERMISSION_GRANTED;
4481                    }
4482                }
4483            }
4484        }
4485
4486        return PackageManager.PERMISSION_DENIED;
4487    }
4488
4489    @Override
4490    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4491        if (UserHandle.getCallingUserId() != userId) {
4492            mContext.enforceCallingPermission(
4493                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4494                    "isPermissionRevokedByPolicy for user " + userId);
4495        }
4496
4497        if (checkPermission(permission, packageName, userId)
4498                == PackageManager.PERMISSION_GRANTED) {
4499            return false;
4500        }
4501
4502        final long identity = Binder.clearCallingIdentity();
4503        try {
4504            final int flags = getPermissionFlags(permission, packageName, userId);
4505            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4506        } finally {
4507            Binder.restoreCallingIdentity(identity);
4508        }
4509    }
4510
4511    @Override
4512    public String getPermissionControllerPackageName() {
4513        synchronized (mPackages) {
4514            return mRequiredInstallerPackage;
4515        }
4516    }
4517
4518    /**
4519     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4520     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4521     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4522     * @param message the message to log on security exception
4523     */
4524    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4525            boolean checkShell, String message) {
4526        if (userId < 0) {
4527            throw new IllegalArgumentException("Invalid userId " + userId);
4528        }
4529        if (checkShell) {
4530            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4531        }
4532        if (userId == UserHandle.getUserId(callingUid)) return;
4533        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4534            if (requireFullPermission) {
4535                mContext.enforceCallingOrSelfPermission(
4536                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4537            } else {
4538                try {
4539                    mContext.enforceCallingOrSelfPermission(
4540                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4541                } catch (SecurityException se) {
4542                    mContext.enforceCallingOrSelfPermission(
4543                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4544                }
4545            }
4546        }
4547    }
4548
4549    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4550        if (callingUid == Process.SHELL_UID) {
4551            if (userHandle >= 0
4552                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4553                throw new SecurityException("Shell does not have permission to access user "
4554                        + userHandle);
4555            } else if (userHandle < 0) {
4556                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4557                        + Debug.getCallers(3));
4558            }
4559        }
4560    }
4561
4562    private BasePermission findPermissionTreeLP(String permName) {
4563        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4564            if (permName.startsWith(bp.name) &&
4565                    permName.length() > bp.name.length() &&
4566                    permName.charAt(bp.name.length()) == '.') {
4567                return bp;
4568            }
4569        }
4570        return null;
4571    }
4572
4573    private BasePermission checkPermissionTreeLP(String permName) {
4574        if (permName != null) {
4575            BasePermission bp = findPermissionTreeLP(permName);
4576            if (bp != null) {
4577                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4578                    return bp;
4579                }
4580                throw new SecurityException("Calling uid "
4581                        + Binder.getCallingUid()
4582                        + " is not allowed to add to permission tree "
4583                        + bp.name + " owned by uid " + bp.uid);
4584            }
4585        }
4586        throw new SecurityException("No permission tree found for " + permName);
4587    }
4588
4589    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4590        if (s1 == null) {
4591            return s2 == null;
4592        }
4593        if (s2 == null) {
4594            return false;
4595        }
4596        if (s1.getClass() != s2.getClass()) {
4597            return false;
4598        }
4599        return s1.equals(s2);
4600    }
4601
4602    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4603        if (pi1.icon != pi2.icon) return false;
4604        if (pi1.logo != pi2.logo) return false;
4605        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4606        if (!compareStrings(pi1.name, pi2.name)) return false;
4607        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4608        // We'll take care of setting this one.
4609        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4610        // These are not currently stored in settings.
4611        //if (!compareStrings(pi1.group, pi2.group)) return false;
4612        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4613        //if (pi1.labelRes != pi2.labelRes) return false;
4614        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4615        return true;
4616    }
4617
4618    int permissionInfoFootprint(PermissionInfo info) {
4619        int size = info.name.length();
4620        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4621        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4622        return size;
4623    }
4624
4625    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4626        int size = 0;
4627        for (BasePermission perm : mSettings.mPermissions.values()) {
4628            if (perm.uid == tree.uid) {
4629                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4630            }
4631        }
4632        return size;
4633    }
4634
4635    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4636        // We calculate the max size of permissions defined by this uid and throw
4637        // if that plus the size of 'info' would exceed our stated maximum.
4638        if (tree.uid != Process.SYSTEM_UID) {
4639            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4640            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4641                throw new SecurityException("Permission tree size cap exceeded");
4642            }
4643        }
4644    }
4645
4646    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4647        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4648            throw new SecurityException("Label must be specified in permission");
4649        }
4650        BasePermission tree = checkPermissionTreeLP(info.name);
4651        BasePermission bp = mSettings.mPermissions.get(info.name);
4652        boolean added = bp == null;
4653        boolean changed = true;
4654        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4655        if (added) {
4656            enforcePermissionCapLocked(info, tree);
4657            bp = new BasePermission(info.name, tree.sourcePackage,
4658                    BasePermission.TYPE_DYNAMIC);
4659        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4660            throw new SecurityException(
4661                    "Not allowed to modify non-dynamic permission "
4662                    + info.name);
4663        } else {
4664            if (bp.protectionLevel == fixedLevel
4665                    && bp.perm.owner.equals(tree.perm.owner)
4666                    && bp.uid == tree.uid
4667                    && comparePermissionInfos(bp.perm.info, info)) {
4668                changed = false;
4669            }
4670        }
4671        bp.protectionLevel = fixedLevel;
4672        info = new PermissionInfo(info);
4673        info.protectionLevel = fixedLevel;
4674        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4675        bp.perm.info.packageName = tree.perm.info.packageName;
4676        bp.uid = tree.uid;
4677        if (added) {
4678            mSettings.mPermissions.put(info.name, bp);
4679        }
4680        if (changed) {
4681            if (!async) {
4682                mSettings.writeLPr();
4683            } else {
4684                scheduleWriteSettingsLocked();
4685            }
4686        }
4687        return added;
4688    }
4689
4690    @Override
4691    public boolean addPermission(PermissionInfo info) {
4692        synchronized (mPackages) {
4693            return addPermissionLocked(info, false);
4694        }
4695    }
4696
4697    @Override
4698    public boolean addPermissionAsync(PermissionInfo info) {
4699        synchronized (mPackages) {
4700            return addPermissionLocked(info, true);
4701        }
4702    }
4703
4704    @Override
4705    public void removePermission(String name) {
4706        synchronized (mPackages) {
4707            checkPermissionTreeLP(name);
4708            BasePermission bp = mSettings.mPermissions.get(name);
4709            if (bp != null) {
4710                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4711                    throw new SecurityException(
4712                            "Not allowed to modify non-dynamic permission "
4713                            + name);
4714                }
4715                mSettings.mPermissions.remove(name);
4716                mSettings.writeLPr();
4717            }
4718        }
4719    }
4720
4721    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4722            BasePermission bp) {
4723        int index = pkg.requestedPermissions.indexOf(bp.name);
4724        if (index == -1) {
4725            throw new SecurityException("Package " + pkg.packageName
4726                    + " has not requested permission " + bp.name);
4727        }
4728        if (!bp.isRuntime() && !bp.isDevelopment()) {
4729            throw new SecurityException("Permission " + bp.name
4730                    + " is not a changeable permission type");
4731        }
4732    }
4733
4734    @Override
4735    public void grantRuntimePermission(String packageName, String name, final int userId) {
4736        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4737    }
4738
4739    private void grantRuntimePermission(String packageName, String name, final int userId,
4740            boolean overridePolicy) {
4741        if (!sUserManager.exists(userId)) {
4742            Log.e(TAG, "No such user:" + userId);
4743            return;
4744        }
4745
4746        mContext.enforceCallingOrSelfPermission(
4747                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4748                "grantRuntimePermission");
4749
4750        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4751                true /* requireFullPermission */, true /* checkShell */,
4752                "grantRuntimePermission");
4753
4754        final int uid;
4755        final SettingBase sb;
4756
4757        synchronized (mPackages) {
4758            final PackageParser.Package pkg = mPackages.get(packageName);
4759            if (pkg == null) {
4760                throw new IllegalArgumentException("Unknown package: " + packageName);
4761            }
4762
4763            final BasePermission bp = mSettings.mPermissions.get(name);
4764            if (bp == null) {
4765                throw new IllegalArgumentException("Unknown permission: " + name);
4766            }
4767
4768            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4769
4770            // If a permission review is required for legacy apps we represent
4771            // their permissions as always granted runtime ones since we need
4772            // to keep the review required permission flag per user while an
4773            // install permission's state is shared across all users.
4774            if (mPermissionReviewRequired
4775                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4776                    && bp.isRuntime()) {
4777                return;
4778            }
4779
4780            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4781            sb = (SettingBase) pkg.mExtras;
4782            if (sb == null) {
4783                throw new IllegalArgumentException("Unknown package: " + packageName);
4784            }
4785
4786            final PermissionsState permissionsState = sb.getPermissionsState();
4787
4788            final int flags = permissionsState.getPermissionFlags(name, userId);
4789            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4790                throw new SecurityException("Cannot grant system fixed permission "
4791                        + name + " for package " + packageName);
4792            }
4793            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4794                throw new SecurityException("Cannot grant policy fixed permission "
4795                        + name + " for package " + packageName);
4796            }
4797
4798            if (bp.isDevelopment()) {
4799                // Development permissions must be handled specially, since they are not
4800                // normal runtime permissions.  For now they apply to all users.
4801                if (permissionsState.grantInstallPermission(bp) !=
4802                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4803                    scheduleWriteSettingsLocked();
4804                }
4805                return;
4806            }
4807
4808            final PackageSetting ps = mSettings.mPackages.get(packageName);
4809            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4810                throw new SecurityException("Cannot grant non-ephemeral permission"
4811                        + name + " for package " + packageName);
4812            }
4813
4814            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4815                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4816                return;
4817            }
4818
4819            final int result = permissionsState.grantRuntimePermission(bp, userId);
4820            switch (result) {
4821                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4822                    return;
4823                }
4824
4825                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4826                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4827                    mHandler.post(new Runnable() {
4828                        @Override
4829                        public void run() {
4830                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4831                        }
4832                    });
4833                }
4834                break;
4835            }
4836
4837            if (bp.isRuntime()) {
4838                logPermissionGranted(mContext, name, packageName);
4839            }
4840
4841            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4842
4843            // Not critical if that is lost - app has to request again.
4844            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4845        }
4846
4847        // Only need to do this if user is initialized. Otherwise it's a new user
4848        // and there are no processes running as the user yet and there's no need
4849        // to make an expensive call to remount processes for the changed permissions.
4850        if (READ_EXTERNAL_STORAGE.equals(name)
4851                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4852            final long token = Binder.clearCallingIdentity();
4853            try {
4854                if (sUserManager.isInitialized(userId)) {
4855                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4856                            StorageManagerInternal.class);
4857                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4858                }
4859            } finally {
4860                Binder.restoreCallingIdentity(token);
4861            }
4862        }
4863    }
4864
4865    @Override
4866    public void revokeRuntimePermission(String packageName, String name, int userId) {
4867        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4868    }
4869
4870    private void revokeRuntimePermission(String packageName, String name, int userId,
4871            boolean overridePolicy) {
4872        if (!sUserManager.exists(userId)) {
4873            Log.e(TAG, "No such user:" + userId);
4874            return;
4875        }
4876
4877        mContext.enforceCallingOrSelfPermission(
4878                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4879                "revokeRuntimePermission");
4880
4881        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4882                true /* requireFullPermission */, true /* checkShell */,
4883                "revokeRuntimePermission");
4884
4885        final int appId;
4886
4887        synchronized (mPackages) {
4888            final PackageParser.Package pkg = mPackages.get(packageName);
4889            if (pkg == null) {
4890                throw new IllegalArgumentException("Unknown package: " + packageName);
4891            }
4892
4893            final BasePermission bp = mSettings.mPermissions.get(name);
4894            if (bp == null) {
4895                throw new IllegalArgumentException("Unknown permission: " + name);
4896            }
4897
4898            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4899
4900            // If a permission review is required for legacy apps we represent
4901            // their permissions as always granted runtime ones since we need
4902            // to keep the review required permission flag per user while an
4903            // install permission's state is shared across all users.
4904            if (mPermissionReviewRequired
4905                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4906                    && bp.isRuntime()) {
4907                return;
4908            }
4909
4910            SettingBase sb = (SettingBase) pkg.mExtras;
4911            if (sb == null) {
4912                throw new IllegalArgumentException("Unknown package: " + packageName);
4913            }
4914
4915            final PermissionsState permissionsState = sb.getPermissionsState();
4916
4917            final int flags = permissionsState.getPermissionFlags(name, userId);
4918            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4919                throw new SecurityException("Cannot revoke system fixed permission "
4920                        + name + " for package " + packageName);
4921            }
4922            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4923                throw new SecurityException("Cannot revoke policy fixed permission "
4924                        + name + " for package " + packageName);
4925            }
4926
4927            if (bp.isDevelopment()) {
4928                // Development permissions must be handled specially, since they are not
4929                // normal runtime permissions.  For now they apply to all users.
4930                if (permissionsState.revokeInstallPermission(bp) !=
4931                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4932                    scheduleWriteSettingsLocked();
4933                }
4934                return;
4935            }
4936
4937            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4938                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4939                return;
4940            }
4941
4942            if (bp.isRuntime()) {
4943                logPermissionRevoked(mContext, name, packageName);
4944            }
4945
4946            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4947
4948            // Critical, after this call app should never have the permission.
4949            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4950
4951            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4952        }
4953
4954        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4955    }
4956
4957    /**
4958     * Get the first event id for the permission.
4959     *
4960     * <p>There are four events for each permission: <ul>
4961     *     <li>Request permission: first id + 0</li>
4962     *     <li>Grant permission: first id + 1</li>
4963     *     <li>Request for permission denied: first id + 2</li>
4964     *     <li>Revoke permission: first id + 3</li>
4965     * </ul></p>
4966     *
4967     * @param name name of the permission
4968     *
4969     * @return The first event id for the permission
4970     */
4971    private static int getBaseEventId(@NonNull String name) {
4972        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4973
4974        if (eventIdIndex == -1) {
4975            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4976                    || "user".equals(Build.TYPE)) {
4977                Log.i(TAG, "Unknown permission " + name);
4978
4979                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4980            } else {
4981                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4982                //
4983                // Also update
4984                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4985                // - metrics_constants.proto
4986                throw new IllegalStateException("Unknown permission " + name);
4987            }
4988        }
4989
4990        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4991    }
4992
4993    /**
4994     * Log that a permission was revoked.
4995     *
4996     * @param context Context of the caller
4997     * @param name name of the permission
4998     * @param packageName package permission if for
4999     */
5000    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5001            @NonNull String packageName) {
5002        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5003    }
5004
5005    /**
5006     * Log that a permission request was granted.
5007     *
5008     * @param context Context of the caller
5009     * @param name name of the permission
5010     * @param packageName package permission if for
5011     */
5012    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5013            @NonNull String packageName) {
5014        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5015    }
5016
5017    @Override
5018    public void resetRuntimePermissions() {
5019        mContext.enforceCallingOrSelfPermission(
5020                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5021                "revokeRuntimePermission");
5022
5023        int callingUid = Binder.getCallingUid();
5024        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5025            mContext.enforceCallingOrSelfPermission(
5026                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5027                    "resetRuntimePermissions");
5028        }
5029
5030        synchronized (mPackages) {
5031            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5032            for (int userId : UserManagerService.getInstance().getUserIds()) {
5033                final int packageCount = mPackages.size();
5034                for (int i = 0; i < packageCount; i++) {
5035                    PackageParser.Package pkg = mPackages.valueAt(i);
5036                    if (!(pkg.mExtras instanceof PackageSetting)) {
5037                        continue;
5038                    }
5039                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5040                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5041                }
5042            }
5043        }
5044    }
5045
5046    @Override
5047    public int getPermissionFlags(String name, String packageName, int userId) {
5048        if (!sUserManager.exists(userId)) {
5049            return 0;
5050        }
5051
5052        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5053
5054        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5055                true /* requireFullPermission */, false /* checkShell */,
5056                "getPermissionFlags");
5057
5058        synchronized (mPackages) {
5059            final PackageParser.Package pkg = mPackages.get(packageName);
5060            if (pkg == null) {
5061                return 0;
5062            }
5063
5064            final BasePermission bp = mSettings.mPermissions.get(name);
5065            if (bp == null) {
5066                return 0;
5067            }
5068
5069            SettingBase sb = (SettingBase) pkg.mExtras;
5070            if (sb == null) {
5071                return 0;
5072            }
5073
5074            PermissionsState permissionsState = sb.getPermissionsState();
5075            return permissionsState.getPermissionFlags(name, userId);
5076        }
5077    }
5078
5079    @Override
5080    public void updatePermissionFlags(String name, String packageName, int flagMask,
5081            int flagValues, int userId) {
5082        if (!sUserManager.exists(userId)) {
5083            return;
5084        }
5085
5086        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5087
5088        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5089                true /* requireFullPermission */, true /* checkShell */,
5090                "updatePermissionFlags");
5091
5092        // Only the system can change these flags and nothing else.
5093        if (getCallingUid() != Process.SYSTEM_UID) {
5094            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5095            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5096            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5097            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5098            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5099        }
5100
5101        synchronized (mPackages) {
5102            final PackageParser.Package pkg = mPackages.get(packageName);
5103            if (pkg == null) {
5104                throw new IllegalArgumentException("Unknown package: " + packageName);
5105            }
5106
5107            final BasePermission bp = mSettings.mPermissions.get(name);
5108            if (bp == null) {
5109                throw new IllegalArgumentException("Unknown permission: " + name);
5110            }
5111
5112            SettingBase sb = (SettingBase) pkg.mExtras;
5113            if (sb == null) {
5114                throw new IllegalArgumentException("Unknown package: " + packageName);
5115            }
5116
5117            PermissionsState permissionsState = sb.getPermissionsState();
5118
5119            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5120
5121            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5122                // Install and runtime permissions are stored in different places,
5123                // so figure out what permission changed and persist the change.
5124                if (permissionsState.getInstallPermissionState(name) != null) {
5125                    scheduleWriteSettingsLocked();
5126                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5127                        || hadState) {
5128                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5129                }
5130            }
5131        }
5132    }
5133
5134    /**
5135     * Update the permission flags for all packages and runtime permissions of a user in order
5136     * to allow device or profile owner to remove POLICY_FIXED.
5137     */
5138    @Override
5139    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5140        if (!sUserManager.exists(userId)) {
5141            return;
5142        }
5143
5144        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5145
5146        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5147                true /* requireFullPermission */, true /* checkShell */,
5148                "updatePermissionFlagsForAllApps");
5149
5150        // Only the system can change system fixed flags.
5151        if (getCallingUid() != Process.SYSTEM_UID) {
5152            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5153            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5154        }
5155
5156        synchronized (mPackages) {
5157            boolean changed = false;
5158            final int packageCount = mPackages.size();
5159            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5160                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5161                SettingBase sb = (SettingBase) pkg.mExtras;
5162                if (sb == null) {
5163                    continue;
5164                }
5165                PermissionsState permissionsState = sb.getPermissionsState();
5166                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5167                        userId, flagMask, flagValues);
5168            }
5169            if (changed) {
5170                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5171            }
5172        }
5173    }
5174
5175    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5176        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5177                != PackageManager.PERMISSION_GRANTED
5178            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5179                != PackageManager.PERMISSION_GRANTED) {
5180            throw new SecurityException(message + " requires "
5181                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5182                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5183        }
5184    }
5185
5186    @Override
5187    public boolean shouldShowRequestPermissionRationale(String permissionName,
5188            String packageName, int userId) {
5189        if (UserHandle.getCallingUserId() != userId) {
5190            mContext.enforceCallingPermission(
5191                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5192                    "canShowRequestPermissionRationale for user " + userId);
5193        }
5194
5195        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5196        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5197            return false;
5198        }
5199
5200        if (checkPermission(permissionName, packageName, userId)
5201                == PackageManager.PERMISSION_GRANTED) {
5202            return false;
5203        }
5204
5205        final int flags;
5206
5207        final long identity = Binder.clearCallingIdentity();
5208        try {
5209            flags = getPermissionFlags(permissionName,
5210                    packageName, userId);
5211        } finally {
5212            Binder.restoreCallingIdentity(identity);
5213        }
5214
5215        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5216                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5217                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5218
5219        if ((flags & fixedFlags) != 0) {
5220            return false;
5221        }
5222
5223        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5224    }
5225
5226    @Override
5227    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5228        mContext.enforceCallingOrSelfPermission(
5229                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5230                "addOnPermissionsChangeListener");
5231
5232        synchronized (mPackages) {
5233            mOnPermissionChangeListeners.addListenerLocked(listener);
5234        }
5235    }
5236
5237    @Override
5238    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5239        synchronized (mPackages) {
5240            mOnPermissionChangeListeners.removeListenerLocked(listener);
5241        }
5242    }
5243
5244    @Override
5245    public boolean isProtectedBroadcast(String actionName) {
5246        synchronized (mPackages) {
5247            if (mProtectedBroadcasts.contains(actionName)) {
5248                return true;
5249            } else if (actionName != null) {
5250                // TODO: remove these terrible hacks
5251                if (actionName.startsWith("android.net.netmon.lingerExpired")
5252                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5253                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5254                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5255                    return true;
5256                }
5257            }
5258        }
5259        return false;
5260    }
5261
5262    @Override
5263    public int checkSignatures(String pkg1, String pkg2) {
5264        synchronized (mPackages) {
5265            final PackageParser.Package p1 = mPackages.get(pkg1);
5266            final PackageParser.Package p2 = mPackages.get(pkg2);
5267            if (p1 == null || p1.mExtras == null
5268                    || p2 == null || p2.mExtras == null) {
5269                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5270            }
5271            return compareSignatures(p1.mSignatures, p2.mSignatures);
5272        }
5273    }
5274
5275    @Override
5276    public int checkUidSignatures(int uid1, int uid2) {
5277        // Map to base uids.
5278        uid1 = UserHandle.getAppId(uid1);
5279        uid2 = UserHandle.getAppId(uid2);
5280        // reader
5281        synchronized (mPackages) {
5282            Signature[] s1;
5283            Signature[] s2;
5284            Object obj = mSettings.getUserIdLPr(uid1);
5285            if (obj != null) {
5286                if (obj instanceof SharedUserSetting) {
5287                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5288                } else if (obj instanceof PackageSetting) {
5289                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5290                } else {
5291                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5292                }
5293            } else {
5294                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5295            }
5296            obj = mSettings.getUserIdLPr(uid2);
5297            if (obj != null) {
5298                if (obj instanceof SharedUserSetting) {
5299                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5300                } else if (obj instanceof PackageSetting) {
5301                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5302                } else {
5303                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5304                }
5305            } else {
5306                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5307            }
5308            return compareSignatures(s1, s2);
5309        }
5310    }
5311
5312    /**
5313     * This method should typically only be used when granting or revoking
5314     * permissions, since the app may immediately restart after this call.
5315     * <p>
5316     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5317     * guard your work against the app being relaunched.
5318     */
5319    private void killUid(int appId, int userId, String reason) {
5320        final long identity = Binder.clearCallingIdentity();
5321        try {
5322            IActivityManager am = ActivityManager.getService();
5323            if (am != null) {
5324                try {
5325                    am.killUid(appId, userId, reason);
5326                } catch (RemoteException e) {
5327                    /* ignore - same process */
5328                }
5329            }
5330        } finally {
5331            Binder.restoreCallingIdentity(identity);
5332        }
5333    }
5334
5335    /**
5336     * Compares two sets of signatures. Returns:
5337     * <br />
5338     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5339     * <br />
5340     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5341     * <br />
5342     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5343     * <br />
5344     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5345     * <br />
5346     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5347     */
5348    static int compareSignatures(Signature[] s1, Signature[] s2) {
5349        if (s1 == null) {
5350            return s2 == null
5351                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5352                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5353        }
5354
5355        if (s2 == null) {
5356            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5357        }
5358
5359        if (s1.length != s2.length) {
5360            return PackageManager.SIGNATURE_NO_MATCH;
5361        }
5362
5363        // Since both signature sets are of size 1, we can compare without HashSets.
5364        if (s1.length == 1) {
5365            return s1[0].equals(s2[0]) ?
5366                    PackageManager.SIGNATURE_MATCH :
5367                    PackageManager.SIGNATURE_NO_MATCH;
5368        }
5369
5370        ArraySet<Signature> set1 = new ArraySet<Signature>();
5371        for (Signature sig : s1) {
5372            set1.add(sig);
5373        }
5374        ArraySet<Signature> set2 = new ArraySet<Signature>();
5375        for (Signature sig : s2) {
5376            set2.add(sig);
5377        }
5378        // Make sure s2 contains all signatures in s1.
5379        if (set1.equals(set2)) {
5380            return PackageManager.SIGNATURE_MATCH;
5381        }
5382        return PackageManager.SIGNATURE_NO_MATCH;
5383    }
5384
5385    /**
5386     * If the database version for this type of package (internal storage or
5387     * external storage) is less than the version where package signatures
5388     * were updated, return true.
5389     */
5390    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5391        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5392        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5393    }
5394
5395    /**
5396     * Used for backward compatibility to make sure any packages with
5397     * certificate chains get upgraded to the new style. {@code existingSigs}
5398     * will be in the old format (since they were stored on disk from before the
5399     * system upgrade) and {@code scannedSigs} will be in the newer format.
5400     */
5401    private int compareSignaturesCompat(PackageSignatures existingSigs,
5402            PackageParser.Package scannedPkg) {
5403        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5404            return PackageManager.SIGNATURE_NO_MATCH;
5405        }
5406
5407        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5408        for (Signature sig : existingSigs.mSignatures) {
5409            existingSet.add(sig);
5410        }
5411        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5412        for (Signature sig : scannedPkg.mSignatures) {
5413            try {
5414                Signature[] chainSignatures = sig.getChainSignatures();
5415                for (Signature chainSig : chainSignatures) {
5416                    scannedCompatSet.add(chainSig);
5417                }
5418            } catch (CertificateEncodingException e) {
5419                scannedCompatSet.add(sig);
5420            }
5421        }
5422        /*
5423         * Make sure the expanded scanned set contains all signatures in the
5424         * existing one.
5425         */
5426        if (scannedCompatSet.equals(existingSet)) {
5427            // Migrate the old signatures to the new scheme.
5428            existingSigs.assignSignatures(scannedPkg.mSignatures);
5429            // The new KeySets will be re-added later in the scanning process.
5430            synchronized (mPackages) {
5431                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5432            }
5433            return PackageManager.SIGNATURE_MATCH;
5434        }
5435        return PackageManager.SIGNATURE_NO_MATCH;
5436    }
5437
5438    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5439        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5440        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5441    }
5442
5443    private int compareSignaturesRecover(PackageSignatures existingSigs,
5444            PackageParser.Package scannedPkg) {
5445        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5446            return PackageManager.SIGNATURE_NO_MATCH;
5447        }
5448
5449        String msg = null;
5450        try {
5451            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5452                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5453                        + scannedPkg.packageName);
5454                return PackageManager.SIGNATURE_MATCH;
5455            }
5456        } catch (CertificateException e) {
5457            msg = e.getMessage();
5458        }
5459
5460        logCriticalInfo(Log.INFO,
5461                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5462        return PackageManager.SIGNATURE_NO_MATCH;
5463    }
5464
5465    @Override
5466    public List<String> getAllPackages() {
5467        synchronized (mPackages) {
5468            return new ArrayList<String>(mPackages.keySet());
5469        }
5470    }
5471
5472    @Override
5473    public String[] getPackagesForUid(int uid) {
5474        final int userId = UserHandle.getUserId(uid);
5475        uid = UserHandle.getAppId(uid);
5476        // reader
5477        synchronized (mPackages) {
5478            Object obj = mSettings.getUserIdLPr(uid);
5479            if (obj instanceof SharedUserSetting) {
5480                final SharedUserSetting sus = (SharedUserSetting) obj;
5481                final int N = sus.packages.size();
5482                String[] res = new String[N];
5483                final Iterator<PackageSetting> it = sus.packages.iterator();
5484                int i = 0;
5485                while (it.hasNext()) {
5486                    PackageSetting ps = it.next();
5487                    if (ps.getInstalled(userId)) {
5488                        res[i++] = ps.name;
5489                    } else {
5490                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5491                    }
5492                }
5493                return res;
5494            } else if (obj instanceof PackageSetting) {
5495                final PackageSetting ps = (PackageSetting) obj;
5496                if (ps.getInstalled(userId)) {
5497                    return new String[]{ps.name};
5498                }
5499            }
5500        }
5501        return null;
5502    }
5503
5504    @Override
5505    public String getNameForUid(int uid) {
5506        // reader
5507        synchronized (mPackages) {
5508            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5509            if (obj instanceof SharedUserSetting) {
5510                final SharedUserSetting sus = (SharedUserSetting) obj;
5511                return sus.name + ":" + sus.userId;
5512            } else if (obj instanceof PackageSetting) {
5513                final PackageSetting ps = (PackageSetting) obj;
5514                return ps.name;
5515            }
5516        }
5517        return null;
5518    }
5519
5520    @Override
5521    public int getUidForSharedUser(String sharedUserName) {
5522        if(sharedUserName == null) {
5523            return -1;
5524        }
5525        // reader
5526        synchronized (mPackages) {
5527            SharedUserSetting suid;
5528            try {
5529                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5530                if (suid != null) {
5531                    return suid.userId;
5532                }
5533            } catch (PackageManagerException ignore) {
5534                // can't happen, but, still need to catch it
5535            }
5536            return -1;
5537        }
5538    }
5539
5540    @Override
5541    public int getFlagsForUid(int uid) {
5542        synchronized (mPackages) {
5543            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5544            if (obj instanceof SharedUserSetting) {
5545                final SharedUserSetting sus = (SharedUserSetting) obj;
5546                return sus.pkgFlags;
5547            } else if (obj instanceof PackageSetting) {
5548                final PackageSetting ps = (PackageSetting) obj;
5549                return ps.pkgFlags;
5550            }
5551        }
5552        return 0;
5553    }
5554
5555    @Override
5556    public int getPrivateFlagsForUid(int uid) {
5557        synchronized (mPackages) {
5558            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5559            if (obj instanceof SharedUserSetting) {
5560                final SharedUserSetting sus = (SharedUserSetting) obj;
5561                return sus.pkgPrivateFlags;
5562            } else if (obj instanceof PackageSetting) {
5563                final PackageSetting ps = (PackageSetting) obj;
5564                return ps.pkgPrivateFlags;
5565            }
5566        }
5567        return 0;
5568    }
5569
5570    @Override
5571    public boolean isUidPrivileged(int uid) {
5572        uid = UserHandle.getAppId(uid);
5573        // reader
5574        synchronized (mPackages) {
5575            Object obj = mSettings.getUserIdLPr(uid);
5576            if (obj instanceof SharedUserSetting) {
5577                final SharedUserSetting sus = (SharedUserSetting) obj;
5578                final Iterator<PackageSetting> it = sus.packages.iterator();
5579                while (it.hasNext()) {
5580                    if (it.next().isPrivileged()) {
5581                        return true;
5582                    }
5583                }
5584            } else if (obj instanceof PackageSetting) {
5585                final PackageSetting ps = (PackageSetting) obj;
5586                return ps.isPrivileged();
5587            }
5588        }
5589        return false;
5590    }
5591
5592    @Override
5593    public String[] getAppOpPermissionPackages(String permissionName) {
5594        synchronized (mPackages) {
5595            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5596            if (pkgs == null) {
5597                return null;
5598            }
5599            return pkgs.toArray(new String[pkgs.size()]);
5600        }
5601    }
5602
5603    @Override
5604    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5605            int flags, int userId) {
5606        return resolveIntentInternal(
5607                intent, resolvedType, flags, userId, false /*includeInstantApp*/);
5608    }
5609
5610    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5611            int flags, int userId, boolean includeInstantApp) {
5612        try {
5613            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5614
5615            if (!sUserManager.exists(userId)) return null;
5616            flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
5617            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5618                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5619
5620            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5621            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5622                    flags, userId, includeInstantApp);
5623            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5624
5625            final ResolveInfo bestChoice =
5626                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5627            return bestChoice;
5628        } finally {
5629            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5630        }
5631    }
5632
5633    @Override
5634    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5635        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5636            throw new SecurityException(
5637                    "findPersistentPreferredActivity can only be run by the system");
5638        }
5639        if (!sUserManager.exists(userId)) {
5640            return null;
5641        }
5642        intent = updateIntentForResolve(intent);
5643        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5644        final int flags = updateFlagsForResolve(0, userId, intent, false);
5645        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5646                userId);
5647        synchronized (mPackages) {
5648            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5649                    userId);
5650        }
5651    }
5652
5653    @Override
5654    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5655            IntentFilter filter, int match, ComponentName activity) {
5656        final int userId = UserHandle.getCallingUserId();
5657        if (DEBUG_PREFERRED) {
5658            Log.v(TAG, "setLastChosenActivity intent=" + intent
5659                + " resolvedType=" + resolvedType
5660                + " flags=" + flags
5661                + " filter=" + filter
5662                + " match=" + match
5663                + " activity=" + activity);
5664            filter.dump(new PrintStreamPrinter(System.out), "    ");
5665        }
5666        intent.setComponent(null);
5667        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5668                userId);
5669        // Find any earlier preferred or last chosen entries and nuke them
5670        findPreferredActivity(intent, resolvedType,
5671                flags, query, 0, false, true, false, userId);
5672        // Add the new activity as the last chosen for this filter
5673        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5674                "Setting last chosen");
5675    }
5676
5677    @Override
5678    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5679        final int userId = UserHandle.getCallingUserId();
5680        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5681        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5682                userId);
5683        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5684                false, false, false, userId);
5685    }
5686
5687    /**
5688     * Returns whether or not instant apps have been disabled remotely.
5689     * <p><em>IMPORTANT</em> This should not be called with the package manager lock
5690     * held. Otherwise we run the risk of deadlock.
5691     */
5692    private boolean isEphemeralDisabled() {
5693        // ephemeral apps have been disabled across the board
5694        if (DISABLE_EPHEMERAL_APPS) {
5695            return true;
5696        }
5697        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5698        if (!mSystemReady) {
5699            return true;
5700        }
5701        // we can't get a content resolver until the system is ready; these checks must happen last
5702        final ContentResolver resolver = mContext.getContentResolver();
5703        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5704            return true;
5705        }
5706        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5707    }
5708
5709    private boolean isEphemeralAllowed(
5710            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5711            boolean skipPackageCheck) {
5712        final int callingUser = UserHandle.getCallingUserId();
5713        if (callingUser != UserHandle.USER_SYSTEM) {
5714            return false;
5715        }
5716        if (mInstantAppResolverConnection == null) {
5717            return false;
5718        }
5719        if (mInstantAppInstallerComponent == null) {
5720            return false;
5721        }
5722        if (intent.getComponent() != null) {
5723            return false;
5724        }
5725        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5726            return false;
5727        }
5728        if (!skipPackageCheck && intent.getPackage() != null) {
5729            return false;
5730        }
5731        final boolean isWebUri = hasWebURI(intent);
5732        if (!isWebUri || intent.getData().getHost() == null) {
5733            return false;
5734        }
5735        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5736        // Or if there's already an ephemeral app installed that handles the action
5737        synchronized (mPackages) {
5738            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5739            for (int n = 0; n < count; n++) {
5740                ResolveInfo info = resolvedActivities.get(n);
5741                String packageName = info.activityInfo.packageName;
5742                PackageSetting ps = mSettings.mPackages.get(packageName);
5743                if (ps != null) {
5744                    // Try to get the status from User settings first
5745                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5746                    int status = (int) (packedStatus >> 32);
5747                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5748                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5749                        if (DEBUG_EPHEMERAL) {
5750                            Slog.v(TAG, "DENY ephemeral apps;"
5751                                + " pkg: " + packageName + ", status: " + status);
5752                        }
5753                        return false;
5754                    }
5755                    if (ps.getInstantApp(userId)) {
5756                        return false;
5757                    }
5758                }
5759            }
5760        }
5761        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5762        return true;
5763    }
5764
5765    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5766            Intent origIntent, String resolvedType, String callingPackage,
5767            int userId) {
5768        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5769                new EphemeralRequest(responseObj, origIntent, resolvedType,
5770                        callingPackage, userId));
5771        mHandler.sendMessage(msg);
5772    }
5773
5774    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5775            int flags, List<ResolveInfo> query, int userId) {
5776        if (query != null) {
5777            final int N = query.size();
5778            if (N == 1) {
5779                return query.get(0);
5780            } else if (N > 1) {
5781                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5782                // If there is more than one activity with the same priority,
5783                // then let the user decide between them.
5784                ResolveInfo r0 = query.get(0);
5785                ResolveInfo r1 = query.get(1);
5786                if (DEBUG_INTENT_MATCHING || debug) {
5787                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5788                            + r1.activityInfo.name + "=" + r1.priority);
5789                }
5790                // If the first activity has a higher priority, or a different
5791                // default, then it is always desirable to pick it.
5792                if (r0.priority != r1.priority
5793                        || r0.preferredOrder != r1.preferredOrder
5794                        || r0.isDefault != r1.isDefault) {
5795                    return query.get(0);
5796                }
5797                // If we have saved a preference for a preferred activity for
5798                // this Intent, use that.
5799                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5800                        flags, query, r0.priority, true, false, debug, userId);
5801                if (ri != null) {
5802                    return ri;
5803                }
5804                // If we have an ephemeral app, use it
5805                for (int i = 0; i < N; i++) {
5806                    ri = query.get(i);
5807                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5808                        return ri;
5809                    }
5810                }
5811                ri = new ResolveInfo(mResolveInfo);
5812                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5813                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5814                // If all of the options come from the same package, show the application's
5815                // label and icon instead of the generic resolver's.
5816                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5817                // and then throw away the ResolveInfo itself, meaning that the caller loses
5818                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5819                // a fallback for this case; we only set the target package's resources on
5820                // the ResolveInfo, not the ActivityInfo.
5821                final String intentPackage = intent.getPackage();
5822                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5823                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5824                    ri.resolvePackageName = intentPackage;
5825                    if (userNeedsBadging(userId)) {
5826                        ri.noResourceId = true;
5827                    } else {
5828                        ri.icon = appi.icon;
5829                    }
5830                    ri.iconResourceId = appi.icon;
5831                    ri.labelRes = appi.labelRes;
5832                }
5833                ri.activityInfo.applicationInfo = new ApplicationInfo(
5834                        ri.activityInfo.applicationInfo);
5835                if (userId != 0) {
5836                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5837                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5838                }
5839                // Make sure that the resolver is displayable in car mode
5840                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5841                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5842                return ri;
5843            }
5844        }
5845        return null;
5846    }
5847
5848    /**
5849     * Return true if the given list is not empty and all of its contents have
5850     * an activityInfo with the given package name.
5851     */
5852    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5853        if (ArrayUtils.isEmpty(list)) {
5854            return false;
5855        }
5856        for (int i = 0, N = list.size(); i < N; i++) {
5857            final ResolveInfo ri = list.get(i);
5858            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5859            if (ai == null || !packageName.equals(ai.packageName)) {
5860                return false;
5861            }
5862        }
5863        return true;
5864    }
5865
5866    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5867            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5868        final int N = query.size();
5869        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5870                .get(userId);
5871        // Get the list of persistent preferred activities that handle the intent
5872        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5873        List<PersistentPreferredActivity> pprefs = ppir != null
5874                ? ppir.queryIntent(intent, resolvedType,
5875                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5876                        userId)
5877                : null;
5878        if (pprefs != null && pprefs.size() > 0) {
5879            final int M = pprefs.size();
5880            for (int i=0; i<M; i++) {
5881                final PersistentPreferredActivity ppa = pprefs.get(i);
5882                if (DEBUG_PREFERRED || debug) {
5883                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5884                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5885                            + "\n  component=" + ppa.mComponent);
5886                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5887                }
5888                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5889                        flags | MATCH_DISABLED_COMPONENTS, userId);
5890                if (DEBUG_PREFERRED || debug) {
5891                    Slog.v(TAG, "Found persistent preferred activity:");
5892                    if (ai != null) {
5893                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5894                    } else {
5895                        Slog.v(TAG, "  null");
5896                    }
5897                }
5898                if (ai == null) {
5899                    // This previously registered persistent preferred activity
5900                    // component is no longer known. Ignore it and do NOT remove it.
5901                    continue;
5902                }
5903                for (int j=0; j<N; j++) {
5904                    final ResolveInfo ri = query.get(j);
5905                    if (!ri.activityInfo.applicationInfo.packageName
5906                            .equals(ai.applicationInfo.packageName)) {
5907                        continue;
5908                    }
5909                    if (!ri.activityInfo.name.equals(ai.name)) {
5910                        continue;
5911                    }
5912                    //  Found a persistent preference that can handle the intent.
5913                    if (DEBUG_PREFERRED || debug) {
5914                        Slog.v(TAG, "Returning persistent preferred activity: " +
5915                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5916                    }
5917                    return ri;
5918                }
5919            }
5920        }
5921        return null;
5922    }
5923
5924    // TODO: handle preferred activities missing while user has amnesia
5925    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5926            List<ResolveInfo> query, int priority, boolean always,
5927            boolean removeMatches, boolean debug, int userId) {
5928        if (!sUserManager.exists(userId)) return null;
5929        flags = updateFlagsForResolve(flags, userId, intent, false);
5930        intent = updateIntentForResolve(intent);
5931        // writer
5932        synchronized (mPackages) {
5933            // Try to find a matching persistent preferred activity.
5934            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5935                    debug, userId);
5936
5937            // If a persistent preferred activity matched, use it.
5938            if (pri != null) {
5939                return pri;
5940            }
5941
5942            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5943            // Get the list of preferred activities that handle the intent
5944            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5945            List<PreferredActivity> prefs = pir != null
5946                    ? pir.queryIntent(intent, resolvedType,
5947                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5948                            userId)
5949                    : null;
5950            if (prefs != null && prefs.size() > 0) {
5951                boolean changed = false;
5952                try {
5953                    // First figure out how good the original match set is.
5954                    // We will only allow preferred activities that came
5955                    // from the same match quality.
5956                    int match = 0;
5957
5958                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5959
5960                    final int N = query.size();
5961                    for (int j=0; j<N; j++) {
5962                        final ResolveInfo ri = query.get(j);
5963                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5964                                + ": 0x" + Integer.toHexString(match));
5965                        if (ri.match > match) {
5966                            match = ri.match;
5967                        }
5968                    }
5969
5970                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5971                            + Integer.toHexString(match));
5972
5973                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5974                    final int M = prefs.size();
5975                    for (int i=0; i<M; i++) {
5976                        final PreferredActivity pa = prefs.get(i);
5977                        if (DEBUG_PREFERRED || debug) {
5978                            Slog.v(TAG, "Checking PreferredActivity ds="
5979                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5980                                    + "\n  component=" + pa.mPref.mComponent);
5981                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5982                        }
5983                        if (pa.mPref.mMatch != match) {
5984                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5985                                    + Integer.toHexString(pa.mPref.mMatch));
5986                            continue;
5987                        }
5988                        // If it's not an "always" type preferred activity and that's what we're
5989                        // looking for, skip it.
5990                        if (always && !pa.mPref.mAlways) {
5991                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5992                            continue;
5993                        }
5994                        final ActivityInfo ai = getActivityInfo(
5995                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5996                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5997                                userId);
5998                        if (DEBUG_PREFERRED || debug) {
5999                            Slog.v(TAG, "Found preferred activity:");
6000                            if (ai != null) {
6001                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6002                            } else {
6003                                Slog.v(TAG, "  null");
6004                            }
6005                        }
6006                        if (ai == null) {
6007                            // This previously registered preferred activity
6008                            // component is no longer known.  Most likely an update
6009                            // to the app was installed and in the new version this
6010                            // component no longer exists.  Clean it up by removing
6011                            // it from the preferred activities list, and skip it.
6012                            Slog.w(TAG, "Removing dangling preferred activity: "
6013                                    + pa.mPref.mComponent);
6014                            pir.removeFilter(pa);
6015                            changed = true;
6016                            continue;
6017                        }
6018                        for (int j=0; j<N; j++) {
6019                            final ResolveInfo ri = query.get(j);
6020                            if (!ri.activityInfo.applicationInfo.packageName
6021                                    .equals(ai.applicationInfo.packageName)) {
6022                                continue;
6023                            }
6024                            if (!ri.activityInfo.name.equals(ai.name)) {
6025                                continue;
6026                            }
6027
6028                            if (removeMatches) {
6029                                pir.removeFilter(pa);
6030                                changed = true;
6031                                if (DEBUG_PREFERRED) {
6032                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6033                                }
6034                                break;
6035                            }
6036
6037                            // Okay we found a previously set preferred or last chosen app.
6038                            // If the result set is different from when this
6039                            // was created, we need to clear it and re-ask the
6040                            // user their preference, if we're looking for an "always" type entry.
6041                            if (always && !pa.mPref.sameSet(query)) {
6042                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6043                                        + intent + " type " + resolvedType);
6044                                if (DEBUG_PREFERRED) {
6045                                    Slog.v(TAG, "Removing preferred activity since set changed "
6046                                            + pa.mPref.mComponent);
6047                                }
6048                                pir.removeFilter(pa);
6049                                // Re-add the filter as a "last chosen" entry (!always)
6050                                PreferredActivity lastChosen = new PreferredActivity(
6051                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6052                                pir.addFilter(lastChosen);
6053                                changed = true;
6054                                return null;
6055                            }
6056
6057                            // Yay! Either the set matched or we're looking for the last chosen
6058                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6059                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6060                            return ri;
6061                        }
6062                    }
6063                } finally {
6064                    if (changed) {
6065                        if (DEBUG_PREFERRED) {
6066                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6067                        }
6068                        scheduleWritePackageRestrictionsLocked(userId);
6069                    }
6070                }
6071            }
6072        }
6073        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6074        return null;
6075    }
6076
6077    /*
6078     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6079     */
6080    @Override
6081    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6082            int targetUserId) {
6083        mContext.enforceCallingOrSelfPermission(
6084                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6085        List<CrossProfileIntentFilter> matches =
6086                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6087        if (matches != null) {
6088            int size = matches.size();
6089            for (int i = 0; i < size; i++) {
6090                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6091            }
6092        }
6093        if (hasWebURI(intent)) {
6094            // cross-profile app linking works only towards the parent.
6095            final UserInfo parent = getProfileParent(sourceUserId);
6096            synchronized(mPackages) {
6097                int flags = updateFlagsForResolve(0, parent.id, intent, false);
6098                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6099                        intent, resolvedType, flags, sourceUserId, parent.id);
6100                return xpDomainInfo != null;
6101            }
6102        }
6103        return false;
6104    }
6105
6106    private UserInfo getProfileParent(int userId) {
6107        final long identity = Binder.clearCallingIdentity();
6108        try {
6109            return sUserManager.getProfileParent(userId);
6110        } finally {
6111            Binder.restoreCallingIdentity(identity);
6112        }
6113    }
6114
6115    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6116            String resolvedType, int userId) {
6117        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6118        if (resolver != null) {
6119            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6120        }
6121        return null;
6122    }
6123
6124    @Override
6125    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6126            String resolvedType, int flags, int userId) {
6127        try {
6128            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6129
6130            return new ParceledListSlice<>(
6131                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6132        } finally {
6133            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6134        }
6135    }
6136
6137    /**
6138     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6139     * instant, returns {@code null}.
6140     */
6141    private String getInstantAppPackageName(int callingUid) {
6142        final int appId = UserHandle.getAppId(callingUid);
6143        synchronized (mPackages) {
6144            final Object obj = mSettings.getUserIdLPr(appId);
6145            if (obj instanceof PackageSetting) {
6146                final PackageSetting ps = (PackageSetting) obj;
6147                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6148                return isInstantApp ? ps.pkg.packageName : null;
6149            }
6150        }
6151        return null;
6152    }
6153
6154    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6155            String resolvedType, int flags, int userId) {
6156        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6157    }
6158
6159    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6160            String resolvedType, int flags, int userId, boolean includeInstantApp) {
6161        if (!sUserManager.exists(userId)) return Collections.emptyList();
6162        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
6163        flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
6164        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6165                false /* requireFullPermission */, false /* checkShell */,
6166                "query intent activities");
6167        ComponentName comp = intent.getComponent();
6168        if (comp == null) {
6169            if (intent.getSelector() != null) {
6170                intent = intent.getSelector();
6171                comp = intent.getComponent();
6172            }
6173        }
6174
6175        if (comp != null) {
6176            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6177            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6178            if (ai != null) {
6179                // When specifying an explicit component, we prevent the activity from being
6180                // used when either 1) the calling package is normal and the activity is within
6181                // an ephemeral application or 2) the calling package is ephemeral and the
6182                // activity is not visible to ephemeral applications.
6183                final boolean matchInstantApp =
6184                        (flags & PackageManager.MATCH_INSTANT) != 0;
6185                final boolean matchVisibleToInstantAppOnly =
6186                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6187                final boolean isCallerInstantApp =
6188                        instantAppPkgName != null;
6189                final boolean isTargetSameInstantApp =
6190                        comp.getPackageName().equals(instantAppPkgName);
6191                final boolean isTargetInstantApp =
6192                        (ai.applicationInfo.privateFlags
6193                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6194                final boolean isTargetHiddenFromInstantApp =
6195                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6196                final boolean blockResolution =
6197                        !isTargetSameInstantApp
6198                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6199                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6200                                        && isTargetHiddenFromInstantApp));
6201                if (!blockResolution) {
6202                    final ResolveInfo ri = new ResolveInfo();
6203                    ri.activityInfo = ai;
6204                    list.add(ri);
6205                }
6206            }
6207            return applyPostResolutionFilter(list, instantAppPkgName);
6208        }
6209
6210        // reader
6211        boolean sortResult = false;
6212        boolean addEphemeral = false;
6213        List<ResolveInfo> result;
6214        final String pkgName = intent.getPackage();
6215        final boolean ephemeralDisabled = isEphemeralDisabled();
6216        synchronized (mPackages) {
6217            if (pkgName == null) {
6218                List<CrossProfileIntentFilter> matchingFilters =
6219                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6220                // Check for results that need to skip the current profile.
6221                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6222                        resolvedType, flags, userId);
6223                if (xpResolveInfo != null) {
6224                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6225                    xpResult.add(xpResolveInfo);
6226                    return applyPostResolutionFilter(
6227                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6228                }
6229
6230                // Check for results in the current profile.
6231                result = filterIfNotSystemUser(mActivities.queryIntent(
6232                        intent, resolvedType, flags, userId), userId);
6233                addEphemeral = !ephemeralDisabled
6234                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6235
6236                // Check for cross profile results.
6237                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6238                xpResolveInfo = queryCrossProfileIntents(
6239                        matchingFilters, intent, resolvedType, flags, userId,
6240                        hasNonNegativePriorityResult);
6241                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6242                    boolean isVisibleToUser = filterIfNotSystemUser(
6243                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6244                    if (isVisibleToUser) {
6245                        result.add(xpResolveInfo);
6246                        sortResult = true;
6247                    }
6248                }
6249                if (hasWebURI(intent)) {
6250                    CrossProfileDomainInfo xpDomainInfo = null;
6251                    final UserInfo parent = getProfileParent(userId);
6252                    if (parent != null) {
6253                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6254                                flags, userId, parent.id);
6255                    }
6256                    if (xpDomainInfo != null) {
6257                        if (xpResolveInfo != null) {
6258                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6259                            // in the result.
6260                            result.remove(xpResolveInfo);
6261                        }
6262                        if (result.size() == 0 && !addEphemeral) {
6263                            // No result in current profile, but found candidate in parent user.
6264                            // And we are not going to add emphemeral app, so we can return the
6265                            // result straight away.
6266                            result.add(xpDomainInfo.resolveInfo);
6267                            return applyPostResolutionFilter(result, instantAppPkgName);
6268                        }
6269                    } else if (result.size() <= 1 && !addEphemeral) {
6270                        // No result in parent user and <= 1 result in current profile, and we
6271                        // are not going to add emphemeral app, so we can return the result without
6272                        // further processing.
6273                        return applyPostResolutionFilter(result, instantAppPkgName);
6274                    }
6275                    // We have more than one candidate (combining results from current and parent
6276                    // profile), so we need filtering and sorting.
6277                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6278                            intent, flags, result, xpDomainInfo, userId);
6279                    sortResult = true;
6280                }
6281            } else {
6282                final PackageParser.Package pkg = mPackages.get(pkgName);
6283                if (pkg != null) {
6284                    result = applyPostResolutionFilter(filterIfNotSystemUser(
6285                            mActivities.queryIntentForPackage(
6286                                    intent, resolvedType, flags, pkg.activities, userId),
6287                            userId), instantAppPkgName);
6288                } else {
6289                    // the caller wants to resolve for a particular package; however, there
6290                    // were no installed results, so, try to find an ephemeral result
6291                    addEphemeral =  !ephemeralDisabled
6292                            && isEphemeralAllowed(
6293                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6294                    result = new ArrayList<ResolveInfo>();
6295                }
6296            }
6297        }
6298        if (addEphemeral) {
6299            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6300            final EphemeralRequest requestObject = new EphemeralRequest(
6301                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6302                    null /*callingPackage*/, userId);
6303            final AuxiliaryResolveInfo auxiliaryResponse =
6304                    EphemeralResolver.doEphemeralResolutionPhaseOne(
6305                            mContext, mInstantAppResolverConnection, requestObject);
6306            if (auxiliaryResponse != null) {
6307                if (DEBUG_EPHEMERAL) {
6308                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6309                }
6310                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6311                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6312                // make sure this resolver is the default
6313                ephemeralInstaller.isDefault = true;
6314                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6315                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6316                // add a non-generic filter
6317                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6318                ephemeralInstaller.filter.addDataPath(
6319                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6320                ephemeralInstaller.instantAppAvailable = true;
6321                result.add(ephemeralInstaller);
6322            }
6323            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6324        }
6325        if (sortResult) {
6326            Collections.sort(result, mResolvePrioritySorter);
6327        }
6328        return applyPostResolutionFilter(result, instantAppPkgName);
6329    }
6330
6331    private static class CrossProfileDomainInfo {
6332        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6333        ResolveInfo resolveInfo;
6334        /* Best domain verification status of the activities found in the other profile */
6335        int bestDomainVerificationStatus;
6336    }
6337
6338    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6339            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6340        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6341                sourceUserId)) {
6342            return null;
6343        }
6344        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6345                resolvedType, flags, parentUserId);
6346
6347        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6348            return null;
6349        }
6350        CrossProfileDomainInfo result = null;
6351        int size = resultTargetUser.size();
6352        for (int i = 0; i < size; i++) {
6353            ResolveInfo riTargetUser = resultTargetUser.get(i);
6354            // Intent filter verification is only for filters that specify a host. So don't return
6355            // those that handle all web uris.
6356            if (riTargetUser.handleAllWebDataURI) {
6357                continue;
6358            }
6359            String packageName = riTargetUser.activityInfo.packageName;
6360            PackageSetting ps = mSettings.mPackages.get(packageName);
6361            if (ps == null) {
6362                continue;
6363            }
6364            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6365            int status = (int)(verificationState >> 32);
6366            if (result == null) {
6367                result = new CrossProfileDomainInfo();
6368                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6369                        sourceUserId, parentUserId);
6370                result.bestDomainVerificationStatus = status;
6371            } else {
6372                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6373                        result.bestDomainVerificationStatus);
6374            }
6375        }
6376        // Don't consider matches with status NEVER across profiles.
6377        if (result != null && result.bestDomainVerificationStatus
6378                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6379            return null;
6380        }
6381        return result;
6382    }
6383
6384    /**
6385     * Verification statuses are ordered from the worse to the best, except for
6386     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6387     */
6388    private int bestDomainVerificationStatus(int status1, int status2) {
6389        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6390            return status2;
6391        }
6392        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6393            return status1;
6394        }
6395        return (int) MathUtils.max(status1, status2);
6396    }
6397
6398    private boolean isUserEnabled(int userId) {
6399        long callingId = Binder.clearCallingIdentity();
6400        try {
6401            UserInfo userInfo = sUserManager.getUserInfo(userId);
6402            return userInfo != null && userInfo.isEnabled();
6403        } finally {
6404            Binder.restoreCallingIdentity(callingId);
6405        }
6406    }
6407
6408    /**
6409     * Filter out activities with systemUserOnly flag set, when current user is not System.
6410     *
6411     * @return filtered list
6412     */
6413    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6414        if (userId == UserHandle.USER_SYSTEM) {
6415            return resolveInfos;
6416        }
6417        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6418            ResolveInfo info = resolveInfos.get(i);
6419            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6420                resolveInfos.remove(i);
6421            }
6422        }
6423        return resolveInfos;
6424    }
6425
6426    /**
6427     * Filters out ephemeral activities.
6428     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6429     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6430     *
6431     * @param resolveInfos The pre-filtered list of resolved activities
6432     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6433     *          is performed.
6434     * @return A filtered list of resolved activities.
6435     */
6436    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6437            String ephemeralPkgName) {
6438        // TODO: When adding on-demand split support for non-instant apps, remove this check
6439        // and always apply post filtering
6440        if (ephemeralPkgName == null) {
6441            return resolveInfos;
6442        }
6443        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6444            final ResolveInfo info = resolveInfos.get(i);
6445            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6446            // allow activities that are defined in the provided package
6447            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6448                if (info.activityInfo.splitName != null
6449                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6450                                info.activityInfo.splitName)) {
6451                    // requested activity is defined in a split that hasn't been installed yet.
6452                    // add the installer to the resolve list
6453                    if (DEBUG_EPHEMERAL) {
6454                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6455                    }
6456                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6457                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6458                            info.activityInfo.packageName, info.activityInfo.splitName,
6459                            info.activityInfo.applicationInfo.versionCode);
6460                    // make sure this resolver is the default
6461                    installerInfo.isDefault = true;
6462                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6463                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6464                    // add a non-generic filter
6465                    installerInfo.filter = new IntentFilter();
6466                    // load resources from the correct package
6467                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6468                    resolveInfos.set(i, installerInfo);
6469                }
6470                continue;
6471            }
6472            // allow activities that have been explicitly exposed to ephemeral apps
6473            if (!isEphemeralApp
6474                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6475                continue;
6476            }
6477            resolveInfos.remove(i);
6478        }
6479        return resolveInfos;
6480    }
6481
6482    /**
6483     * @param resolveInfos list of resolve infos in descending priority order
6484     * @return if the list contains a resolve info with non-negative priority
6485     */
6486    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6487        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6488    }
6489
6490    private static boolean hasWebURI(Intent intent) {
6491        if (intent.getData() == null) {
6492            return false;
6493        }
6494        final String scheme = intent.getScheme();
6495        if (TextUtils.isEmpty(scheme)) {
6496            return false;
6497        }
6498        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6499    }
6500
6501    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6502            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6503            int userId) {
6504        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6505
6506        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6507            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6508                    candidates.size());
6509        }
6510
6511        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6512        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6513        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6514        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6515        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6516        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6517
6518        synchronized (mPackages) {
6519            final int count = candidates.size();
6520            // First, try to use linked apps. Partition the candidates into four lists:
6521            // one for the final results, one for the "do not use ever", one for "undefined status"
6522            // and finally one for "browser app type".
6523            for (int n=0; n<count; n++) {
6524                ResolveInfo info = candidates.get(n);
6525                String packageName = info.activityInfo.packageName;
6526                PackageSetting ps = mSettings.mPackages.get(packageName);
6527                if (ps != null) {
6528                    // Add to the special match all list (Browser use case)
6529                    if (info.handleAllWebDataURI) {
6530                        matchAllList.add(info);
6531                        continue;
6532                    }
6533                    // Try to get the status from User settings first
6534                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6535                    int status = (int)(packedStatus >> 32);
6536                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6537                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6538                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6539                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6540                                    + " : linkgen=" + linkGeneration);
6541                        }
6542                        // Use link-enabled generation as preferredOrder, i.e.
6543                        // prefer newly-enabled over earlier-enabled.
6544                        info.preferredOrder = linkGeneration;
6545                        alwaysList.add(info);
6546                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6547                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6548                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6549                        }
6550                        neverList.add(info);
6551                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6552                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6553                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6554                        }
6555                        alwaysAskList.add(info);
6556                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6557                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6558                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6559                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6560                        }
6561                        undefinedList.add(info);
6562                    }
6563                }
6564            }
6565
6566            // We'll want to include browser possibilities in a few cases
6567            boolean includeBrowser = false;
6568
6569            // First try to add the "always" resolution(s) for the current user, if any
6570            if (alwaysList.size() > 0) {
6571                result.addAll(alwaysList);
6572            } else {
6573                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6574                result.addAll(undefinedList);
6575                // Maybe add one for the other profile.
6576                if (xpDomainInfo != null && (
6577                        xpDomainInfo.bestDomainVerificationStatus
6578                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6579                    result.add(xpDomainInfo.resolveInfo);
6580                }
6581                includeBrowser = true;
6582            }
6583
6584            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6585            // If there were 'always' entries their preferred order has been set, so we also
6586            // back that off to make the alternatives equivalent
6587            if (alwaysAskList.size() > 0) {
6588                for (ResolveInfo i : result) {
6589                    i.preferredOrder = 0;
6590                }
6591                result.addAll(alwaysAskList);
6592                includeBrowser = true;
6593            }
6594
6595            if (includeBrowser) {
6596                // Also add browsers (all of them or only the default one)
6597                if (DEBUG_DOMAIN_VERIFICATION) {
6598                    Slog.v(TAG, "   ...including browsers in candidate set");
6599                }
6600                if ((matchFlags & MATCH_ALL) != 0) {
6601                    result.addAll(matchAllList);
6602                } else {
6603                    // Browser/generic handling case.  If there's a default browser, go straight
6604                    // to that (but only if there is no other higher-priority match).
6605                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6606                    int maxMatchPrio = 0;
6607                    ResolveInfo defaultBrowserMatch = null;
6608                    final int numCandidates = matchAllList.size();
6609                    for (int n = 0; n < numCandidates; n++) {
6610                        ResolveInfo info = matchAllList.get(n);
6611                        // track the highest overall match priority...
6612                        if (info.priority > maxMatchPrio) {
6613                            maxMatchPrio = info.priority;
6614                        }
6615                        // ...and the highest-priority default browser match
6616                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6617                            if (defaultBrowserMatch == null
6618                                    || (defaultBrowserMatch.priority < info.priority)) {
6619                                if (debug) {
6620                                    Slog.v(TAG, "Considering default browser match " + info);
6621                                }
6622                                defaultBrowserMatch = info;
6623                            }
6624                        }
6625                    }
6626                    if (defaultBrowserMatch != null
6627                            && defaultBrowserMatch.priority >= maxMatchPrio
6628                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6629                    {
6630                        if (debug) {
6631                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6632                        }
6633                        result.add(defaultBrowserMatch);
6634                    } else {
6635                        result.addAll(matchAllList);
6636                    }
6637                }
6638
6639                // If there is nothing selected, add all candidates and remove the ones that the user
6640                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6641                if (result.size() == 0) {
6642                    result.addAll(candidates);
6643                    result.removeAll(neverList);
6644                }
6645            }
6646        }
6647        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6648            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6649                    result.size());
6650            for (ResolveInfo info : result) {
6651                Slog.v(TAG, "  + " + info.activityInfo);
6652            }
6653        }
6654        return result;
6655    }
6656
6657    // Returns a packed value as a long:
6658    //
6659    // high 'int'-sized word: link status: undefined/ask/never/always.
6660    // low 'int'-sized word: relative priority among 'always' results.
6661    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6662        long result = ps.getDomainVerificationStatusForUser(userId);
6663        // if none available, get the master status
6664        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6665            if (ps.getIntentFilterVerificationInfo() != null) {
6666                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6667            }
6668        }
6669        return result;
6670    }
6671
6672    private ResolveInfo querySkipCurrentProfileIntents(
6673            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6674            int flags, int sourceUserId) {
6675        if (matchingFilters != null) {
6676            int size = matchingFilters.size();
6677            for (int i = 0; i < size; i ++) {
6678                CrossProfileIntentFilter filter = matchingFilters.get(i);
6679                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6680                    // Checking if there are activities in the target user that can handle the
6681                    // intent.
6682                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6683                            resolvedType, flags, sourceUserId);
6684                    if (resolveInfo != null) {
6685                        return resolveInfo;
6686                    }
6687                }
6688            }
6689        }
6690        return null;
6691    }
6692
6693    // Return matching ResolveInfo in target user if any.
6694    private ResolveInfo queryCrossProfileIntents(
6695            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6696            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6697        if (matchingFilters != null) {
6698            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6699            // match the same intent. For performance reasons, it is better not to
6700            // run queryIntent twice for the same userId
6701            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6702            int size = matchingFilters.size();
6703            for (int i = 0; i < size; i++) {
6704                CrossProfileIntentFilter filter = matchingFilters.get(i);
6705                int targetUserId = filter.getTargetUserId();
6706                boolean skipCurrentProfile =
6707                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6708                boolean skipCurrentProfileIfNoMatchFound =
6709                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6710                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6711                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6712                    // Checking if there are activities in the target user that can handle the
6713                    // intent.
6714                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6715                            resolvedType, flags, sourceUserId);
6716                    if (resolveInfo != null) return resolveInfo;
6717                    alreadyTriedUserIds.put(targetUserId, true);
6718                }
6719            }
6720        }
6721        return null;
6722    }
6723
6724    /**
6725     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6726     * will forward the intent to the filter's target user.
6727     * Otherwise, returns null.
6728     */
6729    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6730            String resolvedType, int flags, int sourceUserId) {
6731        int targetUserId = filter.getTargetUserId();
6732        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6733                resolvedType, flags, targetUserId);
6734        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6735            // If all the matches in the target profile are suspended, return null.
6736            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6737                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6738                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6739                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6740                            targetUserId);
6741                }
6742            }
6743        }
6744        return null;
6745    }
6746
6747    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6748            int sourceUserId, int targetUserId) {
6749        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6750        long ident = Binder.clearCallingIdentity();
6751        boolean targetIsProfile;
6752        try {
6753            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6754        } finally {
6755            Binder.restoreCallingIdentity(ident);
6756        }
6757        String className;
6758        if (targetIsProfile) {
6759            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6760        } else {
6761            className = FORWARD_INTENT_TO_PARENT;
6762        }
6763        ComponentName forwardingActivityComponentName = new ComponentName(
6764                mAndroidApplication.packageName, className);
6765        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6766                sourceUserId);
6767        if (!targetIsProfile) {
6768            forwardingActivityInfo.showUserIcon = targetUserId;
6769            forwardingResolveInfo.noResourceId = true;
6770        }
6771        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6772        forwardingResolveInfo.priority = 0;
6773        forwardingResolveInfo.preferredOrder = 0;
6774        forwardingResolveInfo.match = 0;
6775        forwardingResolveInfo.isDefault = true;
6776        forwardingResolveInfo.filter = filter;
6777        forwardingResolveInfo.targetUserId = targetUserId;
6778        return forwardingResolveInfo;
6779    }
6780
6781    @Override
6782    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6783            Intent[] specifics, String[] specificTypes, Intent intent,
6784            String resolvedType, int flags, int userId) {
6785        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6786                specificTypes, intent, resolvedType, flags, userId));
6787    }
6788
6789    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6790            Intent[] specifics, String[] specificTypes, Intent intent,
6791            String resolvedType, int flags, int userId) {
6792        if (!sUserManager.exists(userId)) return Collections.emptyList();
6793        flags = updateFlagsForResolve(flags, userId, intent, false);
6794        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6795                false /* requireFullPermission */, false /* checkShell */,
6796                "query intent activity options");
6797        final String resultsAction = intent.getAction();
6798
6799        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6800                | PackageManager.GET_RESOLVED_FILTER, userId);
6801
6802        if (DEBUG_INTENT_MATCHING) {
6803            Log.v(TAG, "Query " + intent + ": " + results);
6804        }
6805
6806        int specificsPos = 0;
6807        int N;
6808
6809        // todo: note that the algorithm used here is O(N^2).  This
6810        // isn't a problem in our current environment, but if we start running
6811        // into situations where we have more than 5 or 10 matches then this
6812        // should probably be changed to something smarter...
6813
6814        // First we go through and resolve each of the specific items
6815        // that were supplied, taking care of removing any corresponding
6816        // duplicate items in the generic resolve list.
6817        if (specifics != null) {
6818            for (int i=0; i<specifics.length; i++) {
6819                final Intent sintent = specifics[i];
6820                if (sintent == null) {
6821                    continue;
6822                }
6823
6824                if (DEBUG_INTENT_MATCHING) {
6825                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6826                }
6827
6828                String action = sintent.getAction();
6829                if (resultsAction != null && resultsAction.equals(action)) {
6830                    // If this action was explicitly requested, then don't
6831                    // remove things that have it.
6832                    action = null;
6833                }
6834
6835                ResolveInfo ri = null;
6836                ActivityInfo ai = null;
6837
6838                ComponentName comp = sintent.getComponent();
6839                if (comp == null) {
6840                    ri = resolveIntent(
6841                        sintent,
6842                        specificTypes != null ? specificTypes[i] : null,
6843                            flags, userId);
6844                    if (ri == null) {
6845                        continue;
6846                    }
6847                    if (ri == mResolveInfo) {
6848                        // ACK!  Must do something better with this.
6849                    }
6850                    ai = ri.activityInfo;
6851                    comp = new ComponentName(ai.applicationInfo.packageName,
6852                            ai.name);
6853                } else {
6854                    ai = getActivityInfo(comp, flags, userId);
6855                    if (ai == null) {
6856                        continue;
6857                    }
6858                }
6859
6860                // Look for any generic query activities that are duplicates
6861                // of this specific one, and remove them from the results.
6862                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6863                N = results.size();
6864                int j;
6865                for (j=specificsPos; j<N; j++) {
6866                    ResolveInfo sri = results.get(j);
6867                    if ((sri.activityInfo.name.equals(comp.getClassName())
6868                            && sri.activityInfo.applicationInfo.packageName.equals(
6869                                    comp.getPackageName()))
6870                        || (action != null && sri.filter.matchAction(action))) {
6871                        results.remove(j);
6872                        if (DEBUG_INTENT_MATCHING) Log.v(
6873                            TAG, "Removing duplicate item from " + j
6874                            + " due to specific " + specificsPos);
6875                        if (ri == null) {
6876                            ri = sri;
6877                        }
6878                        j--;
6879                        N--;
6880                    }
6881                }
6882
6883                // Add this specific item to its proper place.
6884                if (ri == null) {
6885                    ri = new ResolveInfo();
6886                    ri.activityInfo = ai;
6887                }
6888                results.add(specificsPos, ri);
6889                ri.specificIndex = i;
6890                specificsPos++;
6891            }
6892        }
6893
6894        // Now we go through the remaining generic results and remove any
6895        // duplicate actions that are found here.
6896        N = results.size();
6897        for (int i=specificsPos; i<N-1; i++) {
6898            final ResolveInfo rii = results.get(i);
6899            if (rii.filter == null) {
6900                continue;
6901            }
6902
6903            // Iterate over all of the actions of this result's intent
6904            // filter...  typically this should be just one.
6905            final Iterator<String> it = rii.filter.actionsIterator();
6906            if (it == null) {
6907                continue;
6908            }
6909            while (it.hasNext()) {
6910                final String action = it.next();
6911                if (resultsAction != null && resultsAction.equals(action)) {
6912                    // If this action was explicitly requested, then don't
6913                    // remove things that have it.
6914                    continue;
6915                }
6916                for (int j=i+1; j<N; j++) {
6917                    final ResolveInfo rij = results.get(j);
6918                    if (rij.filter != null && rij.filter.hasAction(action)) {
6919                        results.remove(j);
6920                        if (DEBUG_INTENT_MATCHING) Log.v(
6921                            TAG, "Removing duplicate item from " + j
6922                            + " due to action " + action + " at " + i);
6923                        j--;
6924                        N--;
6925                    }
6926                }
6927            }
6928
6929            // If the caller didn't request filter information, drop it now
6930            // so we don't have to marshall/unmarshall it.
6931            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6932                rii.filter = null;
6933            }
6934        }
6935
6936        // Filter out the caller activity if so requested.
6937        if (caller != null) {
6938            N = results.size();
6939            for (int i=0; i<N; i++) {
6940                ActivityInfo ainfo = results.get(i).activityInfo;
6941                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6942                        && caller.getClassName().equals(ainfo.name)) {
6943                    results.remove(i);
6944                    break;
6945                }
6946            }
6947        }
6948
6949        // If the caller didn't request filter information,
6950        // drop them now so we don't have to
6951        // marshall/unmarshall it.
6952        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6953            N = results.size();
6954            for (int i=0; i<N; i++) {
6955                results.get(i).filter = null;
6956            }
6957        }
6958
6959        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6960        return results;
6961    }
6962
6963    @Override
6964    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6965            String resolvedType, int flags, int userId) {
6966        return new ParceledListSlice<>(
6967                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6968    }
6969
6970    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6971            String resolvedType, int flags, int userId) {
6972        if (!sUserManager.exists(userId)) return Collections.emptyList();
6973        flags = updateFlagsForResolve(flags, userId, intent, false);
6974        ComponentName comp = intent.getComponent();
6975        if (comp == null) {
6976            if (intent.getSelector() != null) {
6977                intent = intent.getSelector();
6978                comp = intent.getComponent();
6979            }
6980        }
6981        if (comp != null) {
6982            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6983            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6984            if (ai != null) {
6985                ResolveInfo ri = new ResolveInfo();
6986                ri.activityInfo = ai;
6987                list.add(ri);
6988            }
6989            return list;
6990        }
6991
6992        // reader
6993        synchronized (mPackages) {
6994            String pkgName = intent.getPackage();
6995            if (pkgName == null) {
6996                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6997            }
6998            final PackageParser.Package pkg = mPackages.get(pkgName);
6999            if (pkg != null) {
7000                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7001                        userId);
7002            }
7003            return Collections.emptyList();
7004        }
7005    }
7006
7007    @Override
7008    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7009        if (!sUserManager.exists(userId)) return null;
7010        flags = updateFlagsForResolve(flags, userId, intent, false);
7011        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
7012        if (query != null) {
7013            if (query.size() >= 1) {
7014                // If there is more than one service with the same priority,
7015                // just arbitrarily pick the first one.
7016                return query.get(0);
7017            }
7018        }
7019        return null;
7020    }
7021
7022    @Override
7023    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7024            String resolvedType, int flags, int userId) {
7025        return new ParceledListSlice<>(
7026                queryIntentServicesInternal(intent, resolvedType, flags, userId));
7027    }
7028
7029    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7030            String resolvedType, int flags, int userId) {
7031        if (!sUserManager.exists(userId)) return Collections.emptyList();
7032        flags = updateFlagsForResolve(flags, userId, intent, false);
7033        ComponentName comp = intent.getComponent();
7034        if (comp == null) {
7035            if (intent.getSelector() != null) {
7036                intent = intent.getSelector();
7037                comp = intent.getComponent();
7038            }
7039        }
7040        if (comp != null) {
7041            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7042            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7043            if (si != null) {
7044                final ResolveInfo ri = new ResolveInfo();
7045                ri.serviceInfo = si;
7046                list.add(ri);
7047            }
7048            return list;
7049        }
7050
7051        // reader
7052        synchronized (mPackages) {
7053            String pkgName = intent.getPackage();
7054            if (pkgName == null) {
7055                return mServices.queryIntent(intent, resolvedType, flags, userId);
7056            }
7057            final PackageParser.Package pkg = mPackages.get(pkgName);
7058            if (pkg != null) {
7059                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7060                        userId);
7061            }
7062            return Collections.emptyList();
7063        }
7064    }
7065
7066    @Override
7067    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7068            String resolvedType, int flags, int userId) {
7069        return new ParceledListSlice<>(
7070                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7071    }
7072
7073    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7074            Intent intent, String resolvedType, int flags, int userId) {
7075        if (!sUserManager.exists(userId)) return Collections.emptyList();
7076        flags = updateFlagsForResolve(flags, userId, intent, false);
7077        ComponentName comp = intent.getComponent();
7078        if (comp == null) {
7079            if (intent.getSelector() != null) {
7080                intent = intent.getSelector();
7081                comp = intent.getComponent();
7082            }
7083        }
7084        if (comp != null) {
7085            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7086            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7087            if (pi != null) {
7088                final ResolveInfo ri = new ResolveInfo();
7089                ri.providerInfo = pi;
7090                list.add(ri);
7091            }
7092            return list;
7093        }
7094
7095        // reader
7096        synchronized (mPackages) {
7097            String pkgName = intent.getPackage();
7098            if (pkgName == null) {
7099                return mProviders.queryIntent(intent, resolvedType, flags, userId);
7100            }
7101            final PackageParser.Package pkg = mPackages.get(pkgName);
7102            if (pkg != null) {
7103                return mProviders.queryIntentForPackage(
7104                        intent, resolvedType, flags, pkg.providers, userId);
7105            }
7106            return Collections.emptyList();
7107        }
7108    }
7109
7110    @Override
7111    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7112        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7113        flags = updateFlagsForPackage(flags, userId, null);
7114        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7115        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7116                true /* requireFullPermission */, false /* checkShell */,
7117                "get installed packages");
7118
7119        // writer
7120        synchronized (mPackages) {
7121            ArrayList<PackageInfo> list;
7122            if (listUninstalled) {
7123                list = new ArrayList<>(mSettings.mPackages.size());
7124                for (PackageSetting ps : mSettings.mPackages.values()) {
7125                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7126                        continue;
7127                    }
7128                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7129                    if (pi != null) {
7130                        list.add(pi);
7131                    }
7132                }
7133            } else {
7134                list = new ArrayList<>(mPackages.size());
7135                for (PackageParser.Package p : mPackages.values()) {
7136                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7137                            Binder.getCallingUid(), userId)) {
7138                        continue;
7139                    }
7140                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7141                            p.mExtras, flags, userId);
7142                    if (pi != null) {
7143                        list.add(pi);
7144                    }
7145                }
7146            }
7147
7148            return new ParceledListSlice<>(list);
7149        }
7150    }
7151
7152    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7153            String[] permissions, boolean[] tmp, int flags, int userId) {
7154        int numMatch = 0;
7155        final PermissionsState permissionsState = ps.getPermissionsState();
7156        for (int i=0; i<permissions.length; i++) {
7157            final String permission = permissions[i];
7158            if (permissionsState.hasPermission(permission, userId)) {
7159                tmp[i] = true;
7160                numMatch++;
7161            } else {
7162                tmp[i] = false;
7163            }
7164        }
7165        if (numMatch == 0) {
7166            return;
7167        }
7168        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7169
7170        // The above might return null in cases of uninstalled apps or install-state
7171        // skew across users/profiles.
7172        if (pi != null) {
7173            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7174                if (numMatch == permissions.length) {
7175                    pi.requestedPermissions = permissions;
7176                } else {
7177                    pi.requestedPermissions = new String[numMatch];
7178                    numMatch = 0;
7179                    for (int i=0; i<permissions.length; i++) {
7180                        if (tmp[i]) {
7181                            pi.requestedPermissions[numMatch] = permissions[i];
7182                            numMatch++;
7183                        }
7184                    }
7185                }
7186            }
7187            list.add(pi);
7188        }
7189    }
7190
7191    @Override
7192    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7193            String[] permissions, int flags, int userId) {
7194        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7195        flags = updateFlagsForPackage(flags, userId, permissions);
7196        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7197                true /* requireFullPermission */, false /* checkShell */,
7198                "get packages holding permissions");
7199        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7200
7201        // writer
7202        synchronized (mPackages) {
7203            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7204            boolean[] tmpBools = new boolean[permissions.length];
7205            if (listUninstalled) {
7206                for (PackageSetting ps : mSettings.mPackages.values()) {
7207                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7208                            userId);
7209                }
7210            } else {
7211                for (PackageParser.Package pkg : mPackages.values()) {
7212                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7213                    if (ps != null) {
7214                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7215                                userId);
7216                    }
7217                }
7218            }
7219
7220            return new ParceledListSlice<PackageInfo>(list);
7221        }
7222    }
7223
7224    @Override
7225    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7226        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7227        flags = updateFlagsForApplication(flags, userId, null);
7228        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7229
7230        // writer
7231        synchronized (mPackages) {
7232            ArrayList<ApplicationInfo> list;
7233            if (listUninstalled) {
7234                list = new ArrayList<>(mSettings.mPackages.size());
7235                for (PackageSetting ps : mSettings.mPackages.values()) {
7236                    ApplicationInfo ai;
7237                    int effectiveFlags = flags;
7238                    if (ps.isSystem()) {
7239                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7240                    }
7241                    if (ps.pkg != null) {
7242                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7243                            continue;
7244                        }
7245                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7246                                ps.readUserState(userId), userId);
7247                        if (ai != null) {
7248                            rebaseEnabledOverlays(ai, userId);
7249                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7250                        }
7251                    } else {
7252                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7253                        // and already converts to externally visible package name
7254                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7255                                Binder.getCallingUid(), effectiveFlags, userId);
7256                    }
7257                    if (ai != null) {
7258                        list.add(ai);
7259                    }
7260                }
7261            } else {
7262                list = new ArrayList<>(mPackages.size());
7263                for (PackageParser.Package p : mPackages.values()) {
7264                    if (p.mExtras != null) {
7265                        PackageSetting ps = (PackageSetting) p.mExtras;
7266                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7267                            continue;
7268                        }
7269                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7270                                ps.readUserState(userId), userId);
7271                        if (ai != null) {
7272                            rebaseEnabledOverlays(ai, userId);
7273                            ai.packageName = resolveExternalPackageNameLPr(p);
7274                            list.add(ai);
7275                        }
7276                    }
7277                }
7278            }
7279
7280            return new ParceledListSlice<>(list);
7281        }
7282    }
7283
7284    @Override
7285    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7286        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7287            return null;
7288        }
7289
7290        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7291                "getEphemeralApplications");
7292        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7293                true /* requireFullPermission */, false /* checkShell */,
7294                "getEphemeralApplications");
7295        synchronized (mPackages) {
7296            List<InstantAppInfo> instantApps = mInstantAppRegistry
7297                    .getInstantAppsLPr(userId);
7298            if (instantApps != null) {
7299                return new ParceledListSlice<>(instantApps);
7300            }
7301        }
7302        return null;
7303    }
7304
7305    @Override
7306    public boolean isInstantApp(String packageName, int userId) {
7307        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7308                true /* requireFullPermission */, false /* checkShell */,
7309                "isInstantApp");
7310        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7311            return false;
7312        }
7313
7314        if (!isCallerSameApp(packageName)) {
7315            return false;
7316        }
7317        synchronized (mPackages) {
7318            final PackageSetting ps = mSettings.mPackages.get(packageName);
7319            if (ps != null) {
7320                return ps.getInstantApp(userId);
7321            }
7322        }
7323        return false;
7324    }
7325
7326    @Override
7327    public byte[] getInstantAppCookie(String packageName, int userId) {
7328        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7329            return null;
7330        }
7331
7332        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7333                true /* requireFullPermission */, false /* checkShell */,
7334                "getInstantAppCookie");
7335        if (!isCallerSameApp(packageName)) {
7336            return null;
7337        }
7338        synchronized (mPackages) {
7339            return mInstantAppRegistry.getInstantAppCookieLPw(
7340                    packageName, userId);
7341        }
7342    }
7343
7344    @Override
7345    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7346        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7347            return true;
7348        }
7349
7350        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7351                true /* requireFullPermission */, true /* checkShell */,
7352                "setInstantAppCookie");
7353        if (!isCallerSameApp(packageName)) {
7354            return false;
7355        }
7356        synchronized (mPackages) {
7357            return mInstantAppRegistry.setInstantAppCookieLPw(
7358                    packageName, cookie, userId);
7359        }
7360    }
7361
7362    @Override
7363    public Bitmap getInstantAppIcon(String packageName, int userId) {
7364        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7365            return null;
7366        }
7367
7368        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7369                "getInstantAppIcon");
7370
7371        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7372                true /* requireFullPermission */, false /* checkShell */,
7373                "getInstantAppIcon");
7374
7375        synchronized (mPackages) {
7376            return mInstantAppRegistry.getInstantAppIconLPw(
7377                    packageName, userId);
7378        }
7379    }
7380
7381    private boolean isCallerSameApp(String packageName) {
7382        PackageParser.Package pkg = mPackages.get(packageName);
7383        return pkg != null
7384                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7385    }
7386
7387    @Override
7388    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7389        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7390    }
7391
7392    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7393        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7394
7395        // reader
7396        synchronized (mPackages) {
7397            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7398            final int userId = UserHandle.getCallingUserId();
7399            while (i.hasNext()) {
7400                final PackageParser.Package p = i.next();
7401                if (p.applicationInfo == null) continue;
7402
7403                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7404                        && !p.applicationInfo.isDirectBootAware();
7405                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7406                        && p.applicationInfo.isDirectBootAware();
7407
7408                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7409                        && (!mSafeMode || isSystemApp(p))
7410                        && (matchesUnaware || matchesAware)) {
7411                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7412                    if (ps != null) {
7413                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7414                                ps.readUserState(userId), userId);
7415                        if (ai != null) {
7416                            rebaseEnabledOverlays(ai, userId);
7417                            finalList.add(ai);
7418                        }
7419                    }
7420                }
7421            }
7422        }
7423
7424        return finalList;
7425    }
7426
7427    @Override
7428    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7429        if (!sUserManager.exists(userId)) return null;
7430        flags = updateFlagsForComponent(flags, userId, name);
7431        // reader
7432        synchronized (mPackages) {
7433            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7434            PackageSetting ps = provider != null
7435                    ? mSettings.mPackages.get(provider.owner.packageName)
7436                    : null;
7437            return ps != null
7438                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7439                    ? PackageParser.generateProviderInfo(provider, flags,
7440                            ps.readUserState(userId), userId)
7441                    : null;
7442        }
7443    }
7444
7445    /**
7446     * @deprecated
7447     */
7448    @Deprecated
7449    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7450        // reader
7451        synchronized (mPackages) {
7452            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7453                    .entrySet().iterator();
7454            final int userId = UserHandle.getCallingUserId();
7455            while (i.hasNext()) {
7456                Map.Entry<String, PackageParser.Provider> entry = i.next();
7457                PackageParser.Provider p = entry.getValue();
7458                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7459
7460                if (ps != null && p.syncable
7461                        && (!mSafeMode || (p.info.applicationInfo.flags
7462                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7463                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7464                            ps.readUserState(userId), userId);
7465                    if (info != null) {
7466                        outNames.add(entry.getKey());
7467                        outInfo.add(info);
7468                    }
7469                }
7470            }
7471        }
7472    }
7473
7474    @Override
7475    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7476            int uid, int flags, String metaDataKey) {
7477        final int userId = processName != null ? UserHandle.getUserId(uid)
7478                : UserHandle.getCallingUserId();
7479        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7480        flags = updateFlagsForComponent(flags, userId, processName);
7481
7482        ArrayList<ProviderInfo> finalList = null;
7483        // reader
7484        synchronized (mPackages) {
7485            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7486            while (i.hasNext()) {
7487                final PackageParser.Provider p = i.next();
7488                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7489                if (ps != null && p.info.authority != null
7490                        && (processName == null
7491                                || (p.info.processName.equals(processName)
7492                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7493                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7494
7495                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7496                    // parameter.
7497                    if (metaDataKey != null
7498                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7499                        continue;
7500                    }
7501
7502                    if (finalList == null) {
7503                        finalList = new ArrayList<ProviderInfo>(3);
7504                    }
7505                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7506                            ps.readUserState(userId), userId);
7507                    if (info != null) {
7508                        finalList.add(info);
7509                    }
7510                }
7511            }
7512        }
7513
7514        if (finalList != null) {
7515            Collections.sort(finalList, mProviderInitOrderSorter);
7516            return new ParceledListSlice<ProviderInfo>(finalList);
7517        }
7518
7519        return ParceledListSlice.emptyList();
7520    }
7521
7522    @Override
7523    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7524        // reader
7525        synchronized (mPackages) {
7526            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7527            return PackageParser.generateInstrumentationInfo(i, flags);
7528        }
7529    }
7530
7531    @Override
7532    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7533            String targetPackage, int flags) {
7534        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7535    }
7536
7537    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7538            int flags) {
7539        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7540
7541        // reader
7542        synchronized (mPackages) {
7543            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7544            while (i.hasNext()) {
7545                final PackageParser.Instrumentation p = i.next();
7546                if (targetPackage == null
7547                        || targetPackage.equals(p.info.targetPackage)) {
7548                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7549                            flags);
7550                    if (ii != null) {
7551                        finalList.add(ii);
7552                    }
7553                }
7554            }
7555        }
7556
7557        return finalList;
7558    }
7559
7560    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7561        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7562        try {
7563            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7564        } finally {
7565            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7566        }
7567    }
7568
7569    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7570        final File[] files = dir.listFiles();
7571        if (ArrayUtils.isEmpty(files)) {
7572            Log.d(TAG, "No files in app dir " + dir);
7573            return;
7574        }
7575
7576        if (DEBUG_PACKAGE_SCANNING) {
7577            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7578                    + " flags=0x" + Integer.toHexString(parseFlags));
7579        }
7580        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7581                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7582
7583        // Submit files for parsing in parallel
7584        int fileCount = 0;
7585        for (File file : files) {
7586            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7587                    && !PackageInstallerService.isStageName(file.getName());
7588            if (!isPackage) {
7589                // Ignore entries which are not packages
7590                continue;
7591            }
7592            parallelPackageParser.submit(file, parseFlags);
7593            fileCount++;
7594        }
7595
7596        // Process results one by one
7597        for (; fileCount > 0; fileCount--) {
7598            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7599            Throwable throwable = parseResult.throwable;
7600            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7601
7602            if (throwable == null) {
7603                // Static shared libraries have synthetic package names
7604                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7605                    renameStaticSharedLibraryPackage(parseResult.pkg);
7606                }
7607                try {
7608                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7609                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7610                                currentTime, null);
7611                    }
7612                } catch (PackageManagerException e) {
7613                    errorCode = e.error;
7614                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7615                }
7616            } else if (throwable instanceof PackageParser.PackageParserException) {
7617                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7618                        throwable;
7619                errorCode = e.error;
7620                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7621            } else {
7622                throw new IllegalStateException("Unexpected exception occurred while parsing "
7623                        + parseResult.scanFile, throwable);
7624            }
7625
7626            // Delete invalid userdata apps
7627            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7628                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7629                logCriticalInfo(Log.WARN,
7630                        "Deleting invalid package at " + parseResult.scanFile);
7631                removeCodePathLI(parseResult.scanFile);
7632            }
7633        }
7634        parallelPackageParser.close();
7635    }
7636
7637    private static File getSettingsProblemFile() {
7638        File dataDir = Environment.getDataDirectory();
7639        File systemDir = new File(dataDir, "system");
7640        File fname = new File(systemDir, "uiderrors.txt");
7641        return fname;
7642    }
7643
7644    static void reportSettingsProblem(int priority, String msg) {
7645        logCriticalInfo(priority, msg);
7646    }
7647
7648    static void logCriticalInfo(int priority, String msg) {
7649        Slog.println(priority, TAG, msg);
7650        EventLogTags.writePmCriticalInfo(msg);
7651        try {
7652            File fname = getSettingsProblemFile();
7653            FileOutputStream out = new FileOutputStream(fname, true);
7654            PrintWriter pw = new FastPrintWriter(out);
7655            SimpleDateFormat formatter = new SimpleDateFormat();
7656            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7657            pw.println(dateString + ": " + msg);
7658            pw.close();
7659            FileUtils.setPermissions(
7660                    fname.toString(),
7661                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7662                    -1, -1);
7663        } catch (java.io.IOException e) {
7664        }
7665    }
7666
7667    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7668        if (srcFile.isDirectory()) {
7669            final File baseFile = new File(pkg.baseCodePath);
7670            long maxModifiedTime = baseFile.lastModified();
7671            if (pkg.splitCodePaths != null) {
7672                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7673                    final File splitFile = new File(pkg.splitCodePaths[i]);
7674                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7675                }
7676            }
7677            return maxModifiedTime;
7678        }
7679        return srcFile.lastModified();
7680    }
7681
7682    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7683            final int policyFlags) throws PackageManagerException {
7684        // When upgrading from pre-N MR1, verify the package time stamp using the package
7685        // directory and not the APK file.
7686        final long lastModifiedTime = mIsPreNMR1Upgrade
7687                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7688        if (ps != null
7689                && ps.codePath.equals(srcFile)
7690                && ps.timeStamp == lastModifiedTime
7691                && !isCompatSignatureUpdateNeeded(pkg)
7692                && !isRecoverSignatureUpdateNeeded(pkg)) {
7693            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7694            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7695            ArraySet<PublicKey> signingKs;
7696            synchronized (mPackages) {
7697                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7698            }
7699            if (ps.signatures.mSignatures != null
7700                    && ps.signatures.mSignatures.length != 0
7701                    && signingKs != null) {
7702                // Optimization: reuse the existing cached certificates
7703                // if the package appears to be unchanged.
7704                pkg.mSignatures = ps.signatures.mSignatures;
7705                pkg.mSigningKeys = signingKs;
7706                return;
7707            }
7708
7709            Slog.w(TAG, "PackageSetting for " + ps.name
7710                    + " is missing signatures.  Collecting certs again to recover them.");
7711        } else {
7712            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7713        }
7714
7715        try {
7716            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7717            PackageParser.collectCertificates(pkg, policyFlags);
7718        } catch (PackageParserException e) {
7719            throw PackageManagerException.from(e);
7720        } finally {
7721            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7722        }
7723    }
7724
7725    /**
7726     *  Traces a package scan.
7727     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7728     */
7729    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7730            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7731        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7732        try {
7733            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7734        } finally {
7735            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7736        }
7737    }
7738
7739    /**
7740     *  Scans a package and returns the newly parsed package.
7741     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7742     */
7743    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7744            long currentTime, UserHandle user) throws PackageManagerException {
7745        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7746        PackageParser pp = new PackageParser();
7747        pp.setSeparateProcesses(mSeparateProcesses);
7748        pp.setOnlyCoreApps(mOnlyCore);
7749        pp.setDisplayMetrics(mMetrics);
7750
7751        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7752            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7753        }
7754
7755        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7756        final PackageParser.Package pkg;
7757        try {
7758            pkg = pp.parsePackage(scanFile, parseFlags);
7759        } catch (PackageParserException e) {
7760            throw PackageManagerException.from(e);
7761        } finally {
7762            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7763        }
7764
7765        // Static shared libraries have synthetic package names
7766        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7767            renameStaticSharedLibraryPackage(pkg);
7768        }
7769
7770        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7771    }
7772
7773    /**
7774     *  Scans a package and returns the newly parsed package.
7775     *  @throws PackageManagerException on a parse error.
7776     */
7777    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7778            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7779            throws PackageManagerException {
7780        // If the package has children and this is the first dive in the function
7781        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7782        // packages (parent and children) would be successfully scanned before the
7783        // actual scan since scanning mutates internal state and we want to atomically
7784        // install the package and its children.
7785        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7786            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7787                scanFlags |= SCAN_CHECK_ONLY;
7788            }
7789        } else {
7790            scanFlags &= ~SCAN_CHECK_ONLY;
7791        }
7792
7793        // Scan the parent
7794        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7795                scanFlags, currentTime, user);
7796
7797        // Scan the children
7798        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7799        for (int i = 0; i < childCount; i++) {
7800            PackageParser.Package childPackage = pkg.childPackages.get(i);
7801            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7802                    currentTime, user);
7803        }
7804
7805
7806        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7807            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7808        }
7809
7810        return scannedPkg;
7811    }
7812
7813    /**
7814     *  Scans a package and returns the newly parsed package.
7815     *  @throws PackageManagerException on a parse error.
7816     */
7817    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7818            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7819            throws PackageManagerException {
7820        PackageSetting ps = null;
7821        PackageSetting updatedPkg;
7822        // reader
7823        synchronized (mPackages) {
7824            // Look to see if we already know about this package.
7825            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7826            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7827                // This package has been renamed to its original name.  Let's
7828                // use that.
7829                ps = mSettings.getPackageLPr(oldName);
7830            }
7831            // If there was no original package, see one for the real package name.
7832            if (ps == null) {
7833                ps = mSettings.getPackageLPr(pkg.packageName);
7834            }
7835            // Check to see if this package could be hiding/updating a system
7836            // package.  Must look for it either under the original or real
7837            // package name depending on our state.
7838            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7839            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7840
7841            // If this is a package we don't know about on the system partition, we
7842            // may need to remove disabled child packages on the system partition
7843            // or may need to not add child packages if the parent apk is updated
7844            // on the data partition and no longer defines this child package.
7845            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7846                // If this is a parent package for an updated system app and this system
7847                // app got an OTA update which no longer defines some of the child packages
7848                // we have to prune them from the disabled system packages.
7849                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7850                if (disabledPs != null) {
7851                    final int scannedChildCount = (pkg.childPackages != null)
7852                            ? pkg.childPackages.size() : 0;
7853                    final int disabledChildCount = disabledPs.childPackageNames != null
7854                            ? disabledPs.childPackageNames.size() : 0;
7855                    for (int i = 0; i < disabledChildCount; i++) {
7856                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7857                        boolean disabledPackageAvailable = false;
7858                        for (int j = 0; j < scannedChildCount; j++) {
7859                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7860                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7861                                disabledPackageAvailable = true;
7862                                break;
7863                            }
7864                         }
7865                         if (!disabledPackageAvailable) {
7866                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7867                         }
7868                    }
7869                }
7870            }
7871        }
7872
7873        boolean updatedPkgBetter = false;
7874        // First check if this is a system package that may involve an update
7875        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7876            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7877            // it needs to drop FLAG_PRIVILEGED.
7878            if (locationIsPrivileged(scanFile)) {
7879                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7880            } else {
7881                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7882            }
7883
7884            if (ps != null && !ps.codePath.equals(scanFile)) {
7885                // The path has changed from what was last scanned...  check the
7886                // version of the new path against what we have stored to determine
7887                // what to do.
7888                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7889                if (pkg.mVersionCode <= ps.versionCode) {
7890                    // The system package has been updated and the code path does not match
7891                    // Ignore entry. Skip it.
7892                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7893                            + " ignored: updated version " + ps.versionCode
7894                            + " better than this " + pkg.mVersionCode);
7895                    if (!updatedPkg.codePath.equals(scanFile)) {
7896                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7897                                + ps.name + " changing from " + updatedPkg.codePathString
7898                                + " to " + scanFile);
7899                        updatedPkg.codePath = scanFile;
7900                        updatedPkg.codePathString = scanFile.toString();
7901                        updatedPkg.resourcePath = scanFile;
7902                        updatedPkg.resourcePathString = scanFile.toString();
7903                    }
7904                    updatedPkg.pkg = pkg;
7905                    updatedPkg.versionCode = pkg.mVersionCode;
7906
7907                    // Update the disabled system child packages to point to the package too.
7908                    final int childCount = updatedPkg.childPackageNames != null
7909                            ? updatedPkg.childPackageNames.size() : 0;
7910                    for (int i = 0; i < childCount; i++) {
7911                        String childPackageName = updatedPkg.childPackageNames.get(i);
7912                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7913                                childPackageName);
7914                        if (updatedChildPkg != null) {
7915                            updatedChildPkg.pkg = pkg;
7916                            updatedChildPkg.versionCode = pkg.mVersionCode;
7917                        }
7918                    }
7919
7920                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7921                            + scanFile + " ignored: updated version " + ps.versionCode
7922                            + " better than this " + pkg.mVersionCode);
7923                } else {
7924                    // The current app on the system partition is better than
7925                    // what we have updated to on the data partition; switch
7926                    // back to the system partition version.
7927                    // At this point, its safely assumed that package installation for
7928                    // apps in system partition will go through. If not there won't be a working
7929                    // version of the app
7930                    // writer
7931                    synchronized (mPackages) {
7932                        // Just remove the loaded entries from package lists.
7933                        mPackages.remove(ps.name);
7934                    }
7935
7936                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7937                            + " reverting from " + ps.codePathString
7938                            + ": new version " + pkg.mVersionCode
7939                            + " better than installed " + ps.versionCode);
7940
7941                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7942                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7943                    synchronized (mInstallLock) {
7944                        args.cleanUpResourcesLI();
7945                    }
7946                    synchronized (mPackages) {
7947                        mSettings.enableSystemPackageLPw(ps.name);
7948                    }
7949                    updatedPkgBetter = true;
7950                }
7951            }
7952        }
7953
7954        if (updatedPkg != null) {
7955            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7956            // initially
7957            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7958
7959            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7960            // flag set initially
7961            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7962                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7963            }
7964        }
7965
7966        // Verify certificates against what was last scanned
7967        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7968
7969        /*
7970         * A new system app appeared, but we already had a non-system one of the
7971         * same name installed earlier.
7972         */
7973        boolean shouldHideSystemApp = false;
7974        if (updatedPkg == null && ps != null
7975                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7976            /*
7977             * Check to make sure the signatures match first. If they don't,
7978             * wipe the installed application and its data.
7979             */
7980            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7981                    != PackageManager.SIGNATURE_MATCH) {
7982                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7983                        + " signatures don't match existing userdata copy; removing");
7984                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7985                        "scanPackageInternalLI")) {
7986                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7987                }
7988                ps = null;
7989            } else {
7990                /*
7991                 * If the newly-added system app is an older version than the
7992                 * already installed version, hide it. It will be scanned later
7993                 * and re-added like an update.
7994                 */
7995                if (pkg.mVersionCode <= ps.versionCode) {
7996                    shouldHideSystemApp = true;
7997                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7998                            + " but new version " + pkg.mVersionCode + " better than installed "
7999                            + ps.versionCode + "; hiding system");
8000                } else {
8001                    /*
8002                     * The newly found system app is a newer version that the
8003                     * one previously installed. Simply remove the
8004                     * already-installed application and replace it with our own
8005                     * while keeping the application data.
8006                     */
8007                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8008                            + " reverting from " + ps.codePathString + ": new version "
8009                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8010                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8011                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8012                    synchronized (mInstallLock) {
8013                        args.cleanUpResourcesLI();
8014                    }
8015                }
8016            }
8017        }
8018
8019        // The apk is forward locked (not public) if its code and resources
8020        // are kept in different files. (except for app in either system or
8021        // vendor path).
8022        // TODO grab this value from PackageSettings
8023        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8024            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8025                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8026            }
8027        }
8028
8029        // TODO: extend to support forward-locked splits
8030        String resourcePath = null;
8031        String baseResourcePath = null;
8032        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8033            if (ps != null && ps.resourcePathString != null) {
8034                resourcePath = ps.resourcePathString;
8035                baseResourcePath = ps.resourcePathString;
8036            } else {
8037                // Should not happen at all. Just log an error.
8038                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8039            }
8040        } else {
8041            resourcePath = pkg.codePath;
8042            baseResourcePath = pkg.baseCodePath;
8043        }
8044
8045        // Set application objects path explicitly.
8046        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8047        pkg.setApplicationInfoCodePath(pkg.codePath);
8048        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8049        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8050        pkg.setApplicationInfoResourcePath(resourcePath);
8051        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8052        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8053
8054        final int userId = ((user == null) ? 0 : user.getIdentifier());
8055        if (ps != null && ps.getInstantApp(userId)) {
8056            scanFlags |= SCAN_AS_INSTANT_APP;
8057        }
8058
8059        // Note that we invoke the following method only if we are about to unpack an application
8060        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8061                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8062
8063        /*
8064         * If the system app should be overridden by a previously installed
8065         * data, hide the system app now and let the /data/app scan pick it up
8066         * again.
8067         */
8068        if (shouldHideSystemApp) {
8069            synchronized (mPackages) {
8070                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8071            }
8072        }
8073
8074        return scannedPkg;
8075    }
8076
8077    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8078        // Derive the new package synthetic package name
8079        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8080                + pkg.staticSharedLibVersion);
8081    }
8082
8083    private static String fixProcessName(String defProcessName,
8084            String processName) {
8085        if (processName == null) {
8086            return defProcessName;
8087        }
8088        return processName;
8089    }
8090
8091    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8092            throws PackageManagerException {
8093        if (pkgSetting.signatures.mSignatures != null) {
8094            // Already existing package. Make sure signatures match
8095            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8096                    == PackageManager.SIGNATURE_MATCH;
8097            if (!match) {
8098                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8099                        == PackageManager.SIGNATURE_MATCH;
8100            }
8101            if (!match) {
8102                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8103                        == PackageManager.SIGNATURE_MATCH;
8104            }
8105            if (!match) {
8106                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8107                        + pkg.packageName + " signatures do not match the "
8108                        + "previously installed version; ignoring!");
8109            }
8110        }
8111
8112        // Check for shared user signatures
8113        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8114            // Already existing package. Make sure signatures match
8115            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8116                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8117            if (!match) {
8118                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8119                        == PackageManager.SIGNATURE_MATCH;
8120            }
8121            if (!match) {
8122                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8123                        == PackageManager.SIGNATURE_MATCH;
8124            }
8125            if (!match) {
8126                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8127                        "Package " + pkg.packageName
8128                        + " has no signatures that match those in shared user "
8129                        + pkgSetting.sharedUser.name + "; ignoring!");
8130            }
8131        }
8132    }
8133
8134    /**
8135     * Enforces that only the system UID or root's UID can call a method exposed
8136     * via Binder.
8137     *
8138     * @param message used as message if SecurityException is thrown
8139     * @throws SecurityException if the caller is not system or root
8140     */
8141    private static final void enforceSystemOrRoot(String message) {
8142        final int uid = Binder.getCallingUid();
8143        if (uid != Process.SYSTEM_UID && uid != 0) {
8144            throw new SecurityException(message);
8145        }
8146    }
8147
8148    @Override
8149    public void performFstrimIfNeeded() {
8150        enforceSystemOrRoot("Only the system can request fstrim");
8151
8152        // Before everything else, see whether we need to fstrim.
8153        try {
8154            IStorageManager sm = PackageHelper.getStorageManager();
8155            if (sm != null) {
8156                boolean doTrim = false;
8157                final long interval = android.provider.Settings.Global.getLong(
8158                        mContext.getContentResolver(),
8159                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8160                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8161                if (interval > 0) {
8162                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8163                    if (timeSinceLast > interval) {
8164                        doTrim = true;
8165                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8166                                + "; running immediately");
8167                    }
8168                }
8169                if (doTrim) {
8170                    final boolean dexOptDialogShown;
8171                    synchronized (mPackages) {
8172                        dexOptDialogShown = mDexOptDialogShown;
8173                    }
8174                    if (!isFirstBoot() && dexOptDialogShown) {
8175                        try {
8176                            ActivityManager.getService().showBootMessage(
8177                                    mContext.getResources().getString(
8178                                            R.string.android_upgrading_fstrim), true);
8179                        } catch (RemoteException e) {
8180                        }
8181                    }
8182                    sm.runMaintenance();
8183                }
8184            } else {
8185                Slog.e(TAG, "storageManager service unavailable!");
8186            }
8187        } catch (RemoteException e) {
8188            // Can't happen; StorageManagerService is local
8189        }
8190    }
8191
8192    @Override
8193    public void updatePackagesIfNeeded() {
8194        enforceSystemOrRoot("Only the system can request package update");
8195
8196        // We need to re-extract after an OTA.
8197        boolean causeUpgrade = isUpgrade();
8198
8199        // First boot or factory reset.
8200        // Note: we also handle devices that are upgrading to N right now as if it is their
8201        //       first boot, as they do not have profile data.
8202        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8203
8204        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8205        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8206
8207        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8208            return;
8209        }
8210
8211        List<PackageParser.Package> pkgs;
8212        synchronized (mPackages) {
8213            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8214        }
8215
8216        final long startTime = System.nanoTime();
8217        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8218                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8219
8220        final int elapsedTimeSeconds =
8221                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8222
8223        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8224        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8225        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8226        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8227        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8228    }
8229
8230    /**
8231     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8232     * containing statistics about the invocation. The array consists of three elements,
8233     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8234     * and {@code numberOfPackagesFailed}.
8235     */
8236    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8237            String compilerFilter) {
8238
8239        int numberOfPackagesVisited = 0;
8240        int numberOfPackagesOptimized = 0;
8241        int numberOfPackagesSkipped = 0;
8242        int numberOfPackagesFailed = 0;
8243        final int numberOfPackagesToDexopt = pkgs.size();
8244
8245        for (PackageParser.Package pkg : pkgs) {
8246            numberOfPackagesVisited++;
8247
8248            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8249                if (DEBUG_DEXOPT) {
8250                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8251                }
8252                numberOfPackagesSkipped++;
8253                continue;
8254            }
8255
8256            if (DEBUG_DEXOPT) {
8257                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8258                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8259            }
8260
8261            if (showDialog) {
8262                try {
8263                    ActivityManager.getService().showBootMessage(
8264                            mContext.getResources().getString(R.string.android_upgrading_apk,
8265                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8266                } catch (RemoteException e) {
8267                }
8268                synchronized (mPackages) {
8269                    mDexOptDialogShown = true;
8270                }
8271            }
8272
8273            // If the OTA updates a system app which was previously preopted to a non-preopted state
8274            // the app might end up being verified at runtime. That's because by default the apps
8275            // are verify-profile but for preopted apps there's no profile.
8276            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8277            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8278            // filter (by default interpret-only).
8279            // Note that at this stage unused apps are already filtered.
8280            if (isSystemApp(pkg) &&
8281                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8282                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8283                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8284            }
8285
8286            // checkProfiles is false to avoid merging profiles during boot which
8287            // might interfere with background compilation (b/28612421).
8288            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8289            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8290            // trade-off worth doing to save boot time work.
8291            int dexOptStatus = performDexOptTraced(pkg.packageName,
8292                    false /* checkProfiles */,
8293                    compilerFilter,
8294                    false /* force */);
8295            switch (dexOptStatus) {
8296                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8297                    numberOfPackagesOptimized++;
8298                    break;
8299                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8300                    numberOfPackagesSkipped++;
8301                    break;
8302                case PackageDexOptimizer.DEX_OPT_FAILED:
8303                    numberOfPackagesFailed++;
8304                    break;
8305                default:
8306                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8307                    break;
8308            }
8309        }
8310
8311        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8312                numberOfPackagesFailed };
8313    }
8314
8315    @Override
8316    public void notifyPackageUse(String packageName, int reason) {
8317        synchronized (mPackages) {
8318            PackageParser.Package p = mPackages.get(packageName);
8319            if (p == null) {
8320                return;
8321            }
8322            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8323        }
8324    }
8325
8326    @Override
8327    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8328        int userId = UserHandle.getCallingUserId();
8329        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8330        if (ai == null) {
8331            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8332                + loadingPackageName + ", user=" + userId);
8333            return;
8334        }
8335        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8336    }
8337
8338    // TODO: this is not used nor needed. Delete it.
8339    @Override
8340    public boolean performDexOptIfNeeded(String packageName) {
8341        int dexOptStatus = performDexOptTraced(packageName,
8342                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8343        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8344    }
8345
8346    @Override
8347    public boolean performDexOpt(String packageName,
8348            boolean checkProfiles, int compileReason, boolean force) {
8349        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8350                getCompilerFilterForReason(compileReason), force);
8351        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8352    }
8353
8354    @Override
8355    public boolean performDexOptMode(String packageName,
8356            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8357        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8358                targetCompilerFilter, force);
8359        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8360    }
8361
8362    private int performDexOptTraced(String packageName,
8363                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8364        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8365        try {
8366            return performDexOptInternal(packageName, checkProfiles,
8367                    targetCompilerFilter, force);
8368        } finally {
8369            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8370        }
8371    }
8372
8373    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8374    // if the package can now be considered up to date for the given filter.
8375    private int performDexOptInternal(String packageName,
8376                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8377        PackageParser.Package p;
8378        synchronized (mPackages) {
8379            p = mPackages.get(packageName);
8380            if (p == null) {
8381                // Package could not be found. Report failure.
8382                return PackageDexOptimizer.DEX_OPT_FAILED;
8383            }
8384            mPackageUsage.maybeWriteAsync(mPackages);
8385            mCompilerStats.maybeWriteAsync();
8386        }
8387        long callingId = Binder.clearCallingIdentity();
8388        try {
8389            synchronized (mInstallLock) {
8390                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8391                        targetCompilerFilter, force);
8392            }
8393        } finally {
8394            Binder.restoreCallingIdentity(callingId);
8395        }
8396    }
8397
8398    public ArraySet<String> getOptimizablePackages() {
8399        ArraySet<String> pkgs = new ArraySet<String>();
8400        synchronized (mPackages) {
8401            for (PackageParser.Package p : mPackages.values()) {
8402                if (PackageDexOptimizer.canOptimizePackage(p)) {
8403                    pkgs.add(p.packageName);
8404                }
8405            }
8406        }
8407        return pkgs;
8408    }
8409
8410    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8411            boolean checkProfiles, String targetCompilerFilter,
8412            boolean force) {
8413        // Select the dex optimizer based on the force parameter.
8414        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8415        //       allocate an object here.
8416        PackageDexOptimizer pdo = force
8417                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8418                : mPackageDexOptimizer;
8419
8420        // Optimize all dependencies first. Note: we ignore the return value and march on
8421        // on errors.
8422        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8423        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8424        if (!deps.isEmpty()) {
8425            for (PackageParser.Package depPackage : deps) {
8426                // TODO: Analyze and investigate if we (should) profile libraries.
8427                // Currently this will do a full compilation of the library by default.
8428                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8429                        false /* checkProfiles */,
8430                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8431                        getOrCreateCompilerPackageStats(depPackage));
8432            }
8433        }
8434        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8435                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
8436    }
8437
8438    // Performs dexopt on the used secondary dex files belonging to the given package.
8439    // Returns true if all dex files were process successfully (which could mean either dexopt or
8440    // skip). Returns false if any of the files caused errors.
8441    @Override
8442    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8443            boolean force) {
8444        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8445    }
8446
8447    /**
8448     * Reconcile the information we have about the secondary dex files belonging to
8449     * {@code packagName} and the actual dex files. For all dex files that were
8450     * deleted, update the internal records and delete the generated oat files.
8451     */
8452    @Override
8453    public void reconcileSecondaryDexFiles(String packageName) {
8454        mDexManager.reconcileSecondaryDexFiles(packageName);
8455    }
8456
8457    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8458    // a reference there.
8459    /*package*/ DexManager getDexManager() {
8460        return mDexManager;
8461    }
8462
8463    /**
8464     * Execute the background dexopt job immediately.
8465     */
8466    @Override
8467    public boolean runBackgroundDexoptJob() {
8468        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8469    }
8470
8471    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8472        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8473                || p.usesStaticLibraries != null) {
8474            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8475            Set<String> collectedNames = new HashSet<>();
8476            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8477
8478            retValue.remove(p);
8479
8480            return retValue;
8481        } else {
8482            return Collections.emptyList();
8483        }
8484    }
8485
8486    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8487            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8488        if (!collectedNames.contains(p.packageName)) {
8489            collectedNames.add(p.packageName);
8490            collected.add(p);
8491
8492            if (p.usesLibraries != null) {
8493                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8494                        null, collected, collectedNames);
8495            }
8496            if (p.usesOptionalLibraries != null) {
8497                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8498                        null, collected, collectedNames);
8499            }
8500            if (p.usesStaticLibraries != null) {
8501                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8502                        p.usesStaticLibrariesVersions, collected, collectedNames);
8503            }
8504        }
8505    }
8506
8507    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8508            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8509        final int libNameCount = libs.size();
8510        for (int i = 0; i < libNameCount; i++) {
8511            String libName = libs.get(i);
8512            int version = (versions != null && versions.length == libNameCount)
8513                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8514            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8515            if (libPkg != null) {
8516                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8517            }
8518        }
8519    }
8520
8521    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8522        synchronized (mPackages) {
8523            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8524            if (libEntry != null) {
8525                return mPackages.get(libEntry.apk);
8526            }
8527            return null;
8528        }
8529    }
8530
8531    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8532        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8533        if (versionedLib == null) {
8534            return null;
8535        }
8536        return versionedLib.get(version);
8537    }
8538
8539    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8540        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8541                pkg.staticSharedLibName);
8542        if (versionedLib == null) {
8543            return null;
8544        }
8545        int previousLibVersion = -1;
8546        final int versionCount = versionedLib.size();
8547        for (int i = 0; i < versionCount; i++) {
8548            final int libVersion = versionedLib.keyAt(i);
8549            if (libVersion < pkg.staticSharedLibVersion) {
8550                previousLibVersion = Math.max(previousLibVersion, libVersion);
8551            }
8552        }
8553        if (previousLibVersion >= 0) {
8554            return versionedLib.get(previousLibVersion);
8555        }
8556        return null;
8557    }
8558
8559    public void shutdown() {
8560        mPackageUsage.writeNow(mPackages);
8561        mCompilerStats.writeNow();
8562    }
8563
8564    @Override
8565    public void dumpProfiles(String packageName) {
8566        PackageParser.Package pkg;
8567        synchronized (mPackages) {
8568            pkg = mPackages.get(packageName);
8569            if (pkg == null) {
8570                throw new IllegalArgumentException("Unknown package: " + packageName);
8571            }
8572        }
8573        /* Only the shell, root, or the app user should be able to dump profiles. */
8574        int callingUid = Binder.getCallingUid();
8575        if (callingUid != Process.SHELL_UID &&
8576            callingUid != Process.ROOT_UID &&
8577            callingUid != pkg.applicationInfo.uid) {
8578            throw new SecurityException("dumpProfiles");
8579        }
8580
8581        synchronized (mInstallLock) {
8582            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8583            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8584            try {
8585                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8586                String codePaths = TextUtils.join(";", allCodePaths);
8587                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8588            } catch (InstallerException e) {
8589                Slog.w(TAG, "Failed to dump profiles", e);
8590            }
8591            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8592        }
8593    }
8594
8595    @Override
8596    public void forceDexOpt(String packageName) {
8597        enforceSystemOrRoot("forceDexOpt");
8598
8599        PackageParser.Package pkg;
8600        synchronized (mPackages) {
8601            pkg = mPackages.get(packageName);
8602            if (pkg == null) {
8603                throw new IllegalArgumentException("Unknown package: " + packageName);
8604            }
8605        }
8606
8607        synchronized (mInstallLock) {
8608            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8609
8610            // Whoever is calling forceDexOpt wants a fully compiled package.
8611            // Don't use profiles since that may cause compilation to be skipped.
8612            final int res = performDexOptInternalWithDependenciesLI(pkg,
8613                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8614                    true /* force */);
8615
8616            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8617            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8618                throw new IllegalStateException("Failed to dexopt: " + res);
8619            }
8620        }
8621    }
8622
8623    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8624        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8625            Slog.w(TAG, "Unable to update from " + oldPkg.name
8626                    + " to " + newPkg.packageName
8627                    + ": old package not in system partition");
8628            return false;
8629        } else if (mPackages.get(oldPkg.name) != null) {
8630            Slog.w(TAG, "Unable to update from " + oldPkg.name
8631                    + " to " + newPkg.packageName
8632                    + ": old package still exists");
8633            return false;
8634        }
8635        return true;
8636    }
8637
8638    void removeCodePathLI(File codePath) {
8639        if (codePath.isDirectory()) {
8640            try {
8641                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8642            } catch (InstallerException e) {
8643                Slog.w(TAG, "Failed to remove code path", e);
8644            }
8645        } else {
8646            codePath.delete();
8647        }
8648    }
8649
8650    private int[] resolveUserIds(int userId) {
8651        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8652    }
8653
8654    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8655        if (pkg == null) {
8656            Slog.wtf(TAG, "Package was null!", new Throwable());
8657            return;
8658        }
8659        clearAppDataLeafLIF(pkg, userId, flags);
8660        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8661        for (int i = 0; i < childCount; i++) {
8662            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8663        }
8664    }
8665
8666    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8667        final PackageSetting ps;
8668        synchronized (mPackages) {
8669            ps = mSettings.mPackages.get(pkg.packageName);
8670        }
8671        for (int realUserId : resolveUserIds(userId)) {
8672            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8673            try {
8674                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8675                        ceDataInode);
8676            } catch (InstallerException e) {
8677                Slog.w(TAG, String.valueOf(e));
8678            }
8679        }
8680    }
8681
8682    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8683        if (pkg == null) {
8684            Slog.wtf(TAG, "Package was null!", new Throwable());
8685            return;
8686        }
8687        destroyAppDataLeafLIF(pkg, userId, flags);
8688        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8689        for (int i = 0; i < childCount; i++) {
8690            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8691        }
8692    }
8693
8694    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8695        final PackageSetting ps;
8696        synchronized (mPackages) {
8697            ps = mSettings.mPackages.get(pkg.packageName);
8698        }
8699        for (int realUserId : resolveUserIds(userId)) {
8700            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8701            try {
8702                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8703                        ceDataInode);
8704            } catch (InstallerException e) {
8705                Slog.w(TAG, String.valueOf(e));
8706            }
8707        }
8708    }
8709
8710    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8711        if (pkg == null) {
8712            Slog.wtf(TAG, "Package was null!", new Throwable());
8713            return;
8714        }
8715        destroyAppProfilesLeafLIF(pkg);
8716        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8717        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8718        for (int i = 0; i < childCount; i++) {
8719            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8720            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8721                    true /* removeBaseMarker */);
8722        }
8723    }
8724
8725    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8726            boolean removeBaseMarker) {
8727        if (pkg.isForwardLocked()) {
8728            return;
8729        }
8730
8731        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8732            try {
8733                path = PackageManagerServiceUtils.realpath(new File(path));
8734            } catch (IOException e) {
8735                // TODO: Should we return early here ?
8736                Slog.w(TAG, "Failed to get canonical path", e);
8737                continue;
8738            }
8739
8740            final String useMarker = path.replace('/', '@');
8741            for (int realUserId : resolveUserIds(userId)) {
8742                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8743                if (removeBaseMarker) {
8744                    File foreignUseMark = new File(profileDir, useMarker);
8745                    if (foreignUseMark.exists()) {
8746                        if (!foreignUseMark.delete()) {
8747                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8748                                    + pkg.packageName);
8749                        }
8750                    }
8751                }
8752
8753                File[] markers = profileDir.listFiles();
8754                if (markers != null) {
8755                    final String searchString = "@" + pkg.packageName + "@";
8756                    // We also delete all markers that contain the package name we're
8757                    // uninstalling. These are associated with secondary dex-files belonging
8758                    // to the package. Reconstructing the path of these dex files is messy
8759                    // in general.
8760                    for (File marker : markers) {
8761                        if (marker.getName().indexOf(searchString) > 0) {
8762                            if (!marker.delete()) {
8763                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8764                                    + pkg.packageName);
8765                            }
8766                        }
8767                    }
8768                }
8769            }
8770        }
8771    }
8772
8773    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8774        try {
8775            mInstaller.destroyAppProfiles(pkg.packageName);
8776        } catch (InstallerException e) {
8777            Slog.w(TAG, String.valueOf(e));
8778        }
8779    }
8780
8781    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8782        if (pkg == null) {
8783            Slog.wtf(TAG, "Package was null!", new Throwable());
8784            return;
8785        }
8786        clearAppProfilesLeafLIF(pkg);
8787        // We don't remove the base foreign use marker when clearing profiles because
8788        // we will rename it when the app is updated. Unlike the actual profile contents,
8789        // the foreign use marker is good across installs.
8790        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8791        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8792        for (int i = 0; i < childCount; i++) {
8793            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8794        }
8795    }
8796
8797    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8798        try {
8799            mInstaller.clearAppProfiles(pkg.packageName);
8800        } catch (InstallerException e) {
8801            Slog.w(TAG, String.valueOf(e));
8802        }
8803    }
8804
8805    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8806            long lastUpdateTime) {
8807        // Set parent install/update time
8808        PackageSetting ps = (PackageSetting) pkg.mExtras;
8809        if (ps != null) {
8810            ps.firstInstallTime = firstInstallTime;
8811            ps.lastUpdateTime = lastUpdateTime;
8812        }
8813        // Set children install/update time
8814        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8815        for (int i = 0; i < childCount; i++) {
8816            PackageParser.Package childPkg = pkg.childPackages.get(i);
8817            ps = (PackageSetting) childPkg.mExtras;
8818            if (ps != null) {
8819                ps.firstInstallTime = firstInstallTime;
8820                ps.lastUpdateTime = lastUpdateTime;
8821            }
8822        }
8823    }
8824
8825    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8826            PackageParser.Package changingLib) {
8827        if (file.path != null) {
8828            usesLibraryFiles.add(file.path);
8829            return;
8830        }
8831        PackageParser.Package p = mPackages.get(file.apk);
8832        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8833            // If we are doing this while in the middle of updating a library apk,
8834            // then we need to make sure to use that new apk for determining the
8835            // dependencies here.  (We haven't yet finished committing the new apk
8836            // to the package manager state.)
8837            if (p == null || p.packageName.equals(changingLib.packageName)) {
8838                p = changingLib;
8839            }
8840        }
8841        if (p != null) {
8842            usesLibraryFiles.addAll(p.getAllCodePaths());
8843        }
8844    }
8845
8846    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8847            PackageParser.Package changingLib) throws PackageManagerException {
8848        if (pkg == null) {
8849            return;
8850        }
8851        ArraySet<String> usesLibraryFiles = null;
8852        if (pkg.usesLibraries != null) {
8853            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8854                    null, null, pkg.packageName, changingLib, true, null);
8855        }
8856        if (pkg.usesStaticLibraries != null) {
8857            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8858                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8859                    pkg.packageName, changingLib, true, usesLibraryFiles);
8860        }
8861        if (pkg.usesOptionalLibraries != null) {
8862            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8863                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8864        }
8865        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8866            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8867        } else {
8868            pkg.usesLibraryFiles = null;
8869        }
8870    }
8871
8872    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8873            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8874            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8875            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8876            throws PackageManagerException {
8877        final int libCount = requestedLibraries.size();
8878        for (int i = 0; i < libCount; i++) {
8879            final String libName = requestedLibraries.get(i);
8880            final int libVersion = requiredVersions != null ? requiredVersions[i]
8881                    : SharedLibraryInfo.VERSION_UNDEFINED;
8882            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8883            if (libEntry == null) {
8884                if (required) {
8885                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8886                            "Package " + packageName + " requires unavailable shared library "
8887                                    + libName + "; failing!");
8888                } else {
8889                    Slog.w(TAG, "Package " + packageName
8890                            + " desires unavailable shared library "
8891                            + libName + "; ignoring!");
8892                }
8893            } else {
8894                if (requiredVersions != null && requiredCertDigests != null) {
8895                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8896                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8897                            "Package " + packageName + " requires unavailable static shared"
8898                                    + " library " + libName + " version "
8899                                    + libEntry.info.getVersion() + "; failing!");
8900                    }
8901
8902                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8903                    if (libPkg == null) {
8904                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8905                                "Package " + packageName + " requires unavailable static shared"
8906                                        + " library; failing!");
8907                    }
8908
8909                    String expectedCertDigest = requiredCertDigests[i];
8910                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8911                                libPkg.mSignatures[0]);
8912                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8913                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8914                                "Package " + packageName + " requires differently signed" +
8915                                        " static shared library; failing!");
8916                    }
8917                }
8918
8919                if (outUsedLibraries == null) {
8920                    outUsedLibraries = new ArraySet<>();
8921                }
8922                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8923            }
8924        }
8925        return outUsedLibraries;
8926    }
8927
8928    private static boolean hasString(List<String> list, List<String> which) {
8929        if (list == null) {
8930            return false;
8931        }
8932        for (int i=list.size()-1; i>=0; i--) {
8933            for (int j=which.size()-1; j>=0; j--) {
8934                if (which.get(j).equals(list.get(i))) {
8935                    return true;
8936                }
8937            }
8938        }
8939        return false;
8940    }
8941
8942    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8943            PackageParser.Package changingPkg) {
8944        ArrayList<PackageParser.Package> res = null;
8945        for (PackageParser.Package pkg : mPackages.values()) {
8946            if (changingPkg != null
8947                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8948                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8949                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8950                            changingPkg.staticSharedLibName)) {
8951                return null;
8952            }
8953            if (res == null) {
8954                res = new ArrayList<>();
8955            }
8956            res.add(pkg);
8957            try {
8958                updateSharedLibrariesLPr(pkg, changingPkg);
8959            } catch (PackageManagerException e) {
8960                // If a system app update or an app and a required lib missing we
8961                // delete the package and for updated system apps keep the data as
8962                // it is better for the user to reinstall than to be in an limbo
8963                // state. Also libs disappearing under an app should never happen
8964                // - just in case.
8965                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8966                    final int flags = pkg.isUpdatedSystemApp()
8967                            ? PackageManager.DELETE_KEEP_DATA : 0;
8968                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8969                            flags , null, true, null);
8970                }
8971                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8972            }
8973        }
8974        return res;
8975    }
8976
8977    /**
8978     * Derive the value of the {@code cpuAbiOverride} based on the provided
8979     * value and an optional stored value from the package settings.
8980     */
8981    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8982        String cpuAbiOverride = null;
8983
8984        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8985            cpuAbiOverride = null;
8986        } else if (abiOverride != null) {
8987            cpuAbiOverride = abiOverride;
8988        } else if (settings != null) {
8989            cpuAbiOverride = settings.cpuAbiOverrideString;
8990        }
8991
8992        return cpuAbiOverride;
8993    }
8994
8995    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8996            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8997                    throws PackageManagerException {
8998        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8999        // If the package has children and this is the first dive in the function
9000        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9001        // whether all packages (parent and children) would be successfully scanned
9002        // before the actual scan since scanning mutates internal state and we want
9003        // to atomically install the package and its children.
9004        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9005            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9006                scanFlags |= SCAN_CHECK_ONLY;
9007            }
9008        } else {
9009            scanFlags &= ~SCAN_CHECK_ONLY;
9010        }
9011
9012        final PackageParser.Package scannedPkg;
9013        try {
9014            // Scan the parent
9015            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9016            // Scan the children
9017            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9018            for (int i = 0; i < childCount; i++) {
9019                PackageParser.Package childPkg = pkg.childPackages.get(i);
9020                scanPackageLI(childPkg, policyFlags,
9021                        scanFlags, currentTime, user);
9022            }
9023        } finally {
9024            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9025        }
9026
9027        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9028            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9029        }
9030
9031        return scannedPkg;
9032    }
9033
9034    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9035            int scanFlags, long currentTime, @Nullable UserHandle user)
9036                    throws PackageManagerException {
9037        boolean success = false;
9038        try {
9039            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9040                    currentTime, user);
9041            success = true;
9042            return res;
9043        } finally {
9044            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9045                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9046                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9047                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9048                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9049            }
9050        }
9051    }
9052
9053    /**
9054     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9055     */
9056    private static boolean apkHasCode(String fileName) {
9057        StrictJarFile jarFile = null;
9058        try {
9059            jarFile = new StrictJarFile(fileName,
9060                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9061            return jarFile.findEntry("classes.dex") != null;
9062        } catch (IOException ignore) {
9063        } finally {
9064            try {
9065                if (jarFile != null) {
9066                    jarFile.close();
9067                }
9068            } catch (IOException ignore) {}
9069        }
9070        return false;
9071    }
9072
9073    /**
9074     * Enforces code policy for the package. This ensures that if an APK has
9075     * declared hasCode="true" in its manifest that the APK actually contains
9076     * code.
9077     *
9078     * @throws PackageManagerException If bytecode could not be found when it should exist
9079     */
9080    private static void assertCodePolicy(PackageParser.Package pkg)
9081            throws PackageManagerException {
9082        final boolean shouldHaveCode =
9083                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9084        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9085            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9086                    "Package " + pkg.baseCodePath + " code is missing");
9087        }
9088
9089        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9090            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9091                final boolean splitShouldHaveCode =
9092                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9093                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9094                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9095                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9096                }
9097            }
9098        }
9099    }
9100
9101    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9102            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9103                    throws PackageManagerException {
9104        if (DEBUG_PACKAGE_SCANNING) {
9105            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9106                Log.d(TAG, "Scanning package " + pkg.packageName);
9107        }
9108
9109        applyPolicy(pkg, policyFlags);
9110
9111        assertPackageIsValid(pkg, policyFlags, scanFlags);
9112
9113        // Initialize package source and resource directories
9114        final File scanFile = new File(pkg.codePath);
9115        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9116        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9117
9118        SharedUserSetting suid = null;
9119        PackageSetting pkgSetting = null;
9120
9121        // Getting the package setting may have a side-effect, so if we
9122        // are only checking if scan would succeed, stash a copy of the
9123        // old setting to restore at the end.
9124        PackageSetting nonMutatedPs = null;
9125
9126        // We keep references to the derived CPU Abis from settings in oder to reuse
9127        // them in the case where we're not upgrading or booting for the first time.
9128        String primaryCpuAbiFromSettings = null;
9129        String secondaryCpuAbiFromSettings = null;
9130
9131        // writer
9132        synchronized (mPackages) {
9133            if (pkg.mSharedUserId != null) {
9134                // SIDE EFFECTS; may potentially allocate a new shared user
9135                suid = mSettings.getSharedUserLPw(
9136                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9137                if (DEBUG_PACKAGE_SCANNING) {
9138                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9139                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9140                                + "): packages=" + suid.packages);
9141                }
9142            }
9143
9144            // Check if we are renaming from an original package name.
9145            PackageSetting origPackage = null;
9146            String realName = null;
9147            if (pkg.mOriginalPackages != null) {
9148                // This package may need to be renamed to a previously
9149                // installed name.  Let's check on that...
9150                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9151                if (pkg.mOriginalPackages.contains(renamed)) {
9152                    // This package had originally been installed as the
9153                    // original name, and we have already taken care of
9154                    // transitioning to the new one.  Just update the new
9155                    // one to continue using the old name.
9156                    realName = pkg.mRealPackage;
9157                    if (!pkg.packageName.equals(renamed)) {
9158                        // Callers into this function may have already taken
9159                        // care of renaming the package; only do it here if
9160                        // it is not already done.
9161                        pkg.setPackageName(renamed);
9162                    }
9163                } else {
9164                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9165                        if ((origPackage = mSettings.getPackageLPr(
9166                                pkg.mOriginalPackages.get(i))) != null) {
9167                            // We do have the package already installed under its
9168                            // original name...  should we use it?
9169                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9170                                // New package is not compatible with original.
9171                                origPackage = null;
9172                                continue;
9173                            } else if (origPackage.sharedUser != null) {
9174                                // Make sure uid is compatible between packages.
9175                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9176                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9177                                            + " to " + pkg.packageName + ": old uid "
9178                                            + origPackage.sharedUser.name
9179                                            + " differs from " + pkg.mSharedUserId);
9180                                    origPackage = null;
9181                                    continue;
9182                                }
9183                                // TODO: Add case when shared user id is added [b/28144775]
9184                            } else {
9185                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9186                                        + pkg.packageName + " to old name " + origPackage.name);
9187                            }
9188                            break;
9189                        }
9190                    }
9191                }
9192            }
9193
9194            if (mTransferedPackages.contains(pkg.packageName)) {
9195                Slog.w(TAG, "Package " + pkg.packageName
9196                        + " was transferred to another, but its .apk remains");
9197            }
9198
9199            // See comments in nonMutatedPs declaration
9200            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9201                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9202                if (foundPs != null) {
9203                    nonMutatedPs = new PackageSetting(foundPs);
9204                }
9205            }
9206
9207            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9208                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9209                if (foundPs != null) {
9210                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9211                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9212                }
9213            }
9214
9215            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9216            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9217                PackageManagerService.reportSettingsProblem(Log.WARN,
9218                        "Package " + pkg.packageName + " shared user changed from "
9219                                + (pkgSetting.sharedUser != null
9220                                        ? pkgSetting.sharedUser.name : "<nothing>")
9221                                + " to "
9222                                + (suid != null ? suid.name : "<nothing>")
9223                                + "; replacing with new");
9224                pkgSetting = null;
9225            }
9226            final PackageSetting oldPkgSetting =
9227                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9228            final PackageSetting disabledPkgSetting =
9229                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9230
9231            String[] usesStaticLibraries = null;
9232            if (pkg.usesStaticLibraries != null) {
9233                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9234                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9235            }
9236
9237            if (pkgSetting == null) {
9238                final String parentPackageName = (pkg.parentPackage != null)
9239                        ? pkg.parentPackage.packageName : null;
9240                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9241                // REMOVE SharedUserSetting from method; update in a separate call
9242                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9243                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9244                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9245                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9246                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9247                        true /*allowInstall*/, instantApp, parentPackageName,
9248                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9249                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9250                // SIDE EFFECTS; updates system state; move elsewhere
9251                if (origPackage != null) {
9252                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9253                }
9254                mSettings.addUserToSettingLPw(pkgSetting);
9255            } else {
9256                // REMOVE SharedUserSetting from method; update in a separate call.
9257                //
9258                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9259                // secondaryCpuAbi are not known at this point so we always update them
9260                // to null here, only to reset them at a later point.
9261                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9262                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9263                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9264                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9265                        UserManagerService.getInstance(), usesStaticLibraries,
9266                        pkg.usesStaticLibrariesVersions);
9267            }
9268            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9269            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9270
9271            // SIDE EFFECTS; modifies system state; move elsewhere
9272            if (pkgSetting.origPackage != null) {
9273                // If we are first transitioning from an original package,
9274                // fix up the new package's name now.  We need to do this after
9275                // looking up the package under its new name, so getPackageLP
9276                // can take care of fiddling things correctly.
9277                pkg.setPackageName(origPackage.name);
9278
9279                // File a report about this.
9280                String msg = "New package " + pkgSetting.realName
9281                        + " renamed to replace old package " + pkgSetting.name;
9282                reportSettingsProblem(Log.WARN, msg);
9283
9284                // Make a note of it.
9285                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9286                    mTransferedPackages.add(origPackage.name);
9287                }
9288
9289                // No longer need to retain this.
9290                pkgSetting.origPackage = null;
9291            }
9292
9293            // SIDE EFFECTS; modifies system state; move elsewhere
9294            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9295                // Make a note of it.
9296                mTransferedPackages.add(pkg.packageName);
9297            }
9298
9299            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9300                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9301            }
9302
9303            if ((scanFlags & SCAN_BOOTING) == 0
9304                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9305                // Check all shared libraries and map to their actual file path.
9306                // We only do this here for apps not on a system dir, because those
9307                // are the only ones that can fail an install due to this.  We
9308                // will take care of the system apps by updating all of their
9309                // library paths after the scan is done. Also during the initial
9310                // scan don't update any libs as we do this wholesale after all
9311                // apps are scanned to avoid dependency based scanning.
9312                updateSharedLibrariesLPr(pkg, null);
9313            }
9314
9315            if (mFoundPolicyFile) {
9316                SELinuxMMAC.assignSeInfoValue(pkg);
9317            }
9318            pkg.applicationInfo.uid = pkgSetting.appId;
9319            pkg.mExtras = pkgSetting;
9320
9321
9322            // Static shared libs have same package with different versions where
9323            // we internally use a synthetic package name to allow multiple versions
9324            // of the same package, therefore we need to compare signatures against
9325            // the package setting for the latest library version.
9326            PackageSetting signatureCheckPs = pkgSetting;
9327            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9328                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9329                if (libraryEntry != null) {
9330                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9331                }
9332            }
9333
9334            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9335                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9336                    // We just determined the app is signed correctly, so bring
9337                    // over the latest parsed certs.
9338                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9339                } else {
9340                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9341                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9342                                "Package " + pkg.packageName + " upgrade keys do not match the "
9343                                + "previously installed version");
9344                    } else {
9345                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9346                        String msg = "System package " + pkg.packageName
9347                                + " signature changed; retaining data.";
9348                        reportSettingsProblem(Log.WARN, msg);
9349                    }
9350                }
9351            } else {
9352                try {
9353                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9354                    verifySignaturesLP(signatureCheckPs, pkg);
9355                    // We just determined the app is signed correctly, so bring
9356                    // over the latest parsed certs.
9357                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9358                } catch (PackageManagerException e) {
9359                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9360                        throw e;
9361                    }
9362                    // The signature has changed, but this package is in the system
9363                    // image...  let's recover!
9364                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9365                    // However...  if this package is part of a shared user, but it
9366                    // doesn't match the signature of the shared user, let's fail.
9367                    // What this means is that you can't change the signatures
9368                    // associated with an overall shared user, which doesn't seem all
9369                    // that unreasonable.
9370                    if (signatureCheckPs.sharedUser != null) {
9371                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9372                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9373                            throw new PackageManagerException(
9374                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9375                                    "Signature mismatch for shared user: "
9376                                            + pkgSetting.sharedUser);
9377                        }
9378                    }
9379                    // File a report about this.
9380                    String msg = "System package " + pkg.packageName
9381                            + " signature changed; retaining data.";
9382                    reportSettingsProblem(Log.WARN, msg);
9383                }
9384            }
9385
9386            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9387                // This package wants to adopt ownership of permissions from
9388                // another package.
9389                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9390                    final String origName = pkg.mAdoptPermissions.get(i);
9391                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9392                    if (orig != null) {
9393                        if (verifyPackageUpdateLPr(orig, pkg)) {
9394                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9395                                    + pkg.packageName);
9396                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9397                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9398                        }
9399                    }
9400                }
9401            }
9402        }
9403
9404        pkg.applicationInfo.processName = fixProcessName(
9405                pkg.applicationInfo.packageName,
9406                pkg.applicationInfo.processName);
9407
9408        if (pkg != mPlatformPackage) {
9409            // Get all of our default paths setup
9410            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9411        }
9412
9413        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9414
9415        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9416            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9417                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9418                derivePackageAbi(
9419                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9420                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9421
9422                // Some system apps still use directory structure for native libraries
9423                // in which case we might end up not detecting abi solely based on apk
9424                // structure. Try to detect abi based on directory structure.
9425                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9426                        pkg.applicationInfo.primaryCpuAbi == null) {
9427                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9428                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9429                }
9430            } else {
9431                // This is not a first boot or an upgrade, don't bother deriving the
9432                // ABI during the scan. Instead, trust the value that was stored in the
9433                // package setting.
9434                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9435                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9436
9437                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9438
9439                if (DEBUG_ABI_SELECTION) {
9440                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9441                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9442                        pkg.applicationInfo.secondaryCpuAbi);
9443                }
9444            }
9445        } else {
9446            if ((scanFlags & SCAN_MOVE) != 0) {
9447                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9448                // but we already have this packages package info in the PackageSetting. We just
9449                // use that and derive the native library path based on the new codepath.
9450                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9451                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9452            }
9453
9454            // Set native library paths again. For moves, the path will be updated based on the
9455            // ABIs we've determined above. For non-moves, the path will be updated based on the
9456            // ABIs we determined during compilation, but the path will depend on the final
9457            // package path (after the rename away from the stage path).
9458            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9459        }
9460
9461        // This is a special case for the "system" package, where the ABI is
9462        // dictated by the zygote configuration (and init.rc). We should keep track
9463        // of this ABI so that we can deal with "normal" applications that run under
9464        // the same UID correctly.
9465        if (mPlatformPackage == pkg) {
9466            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9467                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9468        }
9469
9470        // If there's a mismatch between the abi-override in the package setting
9471        // and the abiOverride specified for the install. Warn about this because we
9472        // would've already compiled the app without taking the package setting into
9473        // account.
9474        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9475            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9476                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9477                        " for package " + pkg.packageName);
9478            }
9479        }
9480
9481        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9482        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9483        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9484
9485        // Copy the derived override back to the parsed package, so that we can
9486        // update the package settings accordingly.
9487        pkg.cpuAbiOverride = cpuAbiOverride;
9488
9489        if (DEBUG_ABI_SELECTION) {
9490            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9491                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9492                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9493        }
9494
9495        // Push the derived path down into PackageSettings so we know what to
9496        // clean up at uninstall time.
9497        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9498
9499        if (DEBUG_ABI_SELECTION) {
9500            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9501                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9502                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9503        }
9504
9505        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9506        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9507            // We don't do this here during boot because we can do it all
9508            // at once after scanning all existing packages.
9509            //
9510            // We also do this *before* we perform dexopt on this package, so that
9511            // we can avoid redundant dexopts, and also to make sure we've got the
9512            // code and package path correct.
9513            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9514        }
9515
9516        if (mFactoryTest && pkg.requestedPermissions.contains(
9517                android.Manifest.permission.FACTORY_TEST)) {
9518            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9519        }
9520
9521        if (isSystemApp(pkg)) {
9522            pkgSetting.isOrphaned = true;
9523        }
9524
9525        // Take care of first install / last update times.
9526        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9527        if (currentTime != 0) {
9528            if (pkgSetting.firstInstallTime == 0) {
9529                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9530            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9531                pkgSetting.lastUpdateTime = currentTime;
9532            }
9533        } else if (pkgSetting.firstInstallTime == 0) {
9534            // We need *something*.  Take time time stamp of the file.
9535            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9536        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9537            if (scanFileTime != pkgSetting.timeStamp) {
9538                // A package on the system image has changed; consider this
9539                // to be an update.
9540                pkgSetting.lastUpdateTime = scanFileTime;
9541            }
9542        }
9543        pkgSetting.setTimeStamp(scanFileTime);
9544
9545        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9546            if (nonMutatedPs != null) {
9547                synchronized (mPackages) {
9548                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9549                }
9550            }
9551        } else {
9552            final int userId = user == null ? 0 : user.getIdentifier();
9553            // Modify state for the given package setting
9554            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9555                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9556            if (pkgSetting.getInstantApp(userId)) {
9557                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9558            }
9559        }
9560        return pkg;
9561    }
9562
9563    /**
9564     * Applies policy to the parsed package based upon the given policy flags.
9565     * Ensures the package is in a good state.
9566     * <p>
9567     * Implementation detail: This method must NOT have any side effect. It would
9568     * ideally be static, but, it requires locks to read system state.
9569     */
9570    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9571        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9572            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9573            if (pkg.applicationInfo.isDirectBootAware()) {
9574                // we're direct boot aware; set for all components
9575                for (PackageParser.Service s : pkg.services) {
9576                    s.info.encryptionAware = s.info.directBootAware = true;
9577                }
9578                for (PackageParser.Provider p : pkg.providers) {
9579                    p.info.encryptionAware = p.info.directBootAware = true;
9580                }
9581                for (PackageParser.Activity a : pkg.activities) {
9582                    a.info.encryptionAware = a.info.directBootAware = true;
9583                }
9584                for (PackageParser.Activity r : pkg.receivers) {
9585                    r.info.encryptionAware = r.info.directBootAware = true;
9586                }
9587            }
9588        } else {
9589            // Only allow system apps to be flagged as core apps.
9590            pkg.coreApp = false;
9591            // clear flags not applicable to regular apps
9592            pkg.applicationInfo.privateFlags &=
9593                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9594            pkg.applicationInfo.privateFlags &=
9595                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9596        }
9597        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9598
9599        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9600            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9601        }
9602
9603        if (!isSystemApp(pkg)) {
9604            // Only system apps can use these features.
9605            pkg.mOriginalPackages = null;
9606            pkg.mRealPackage = null;
9607            pkg.mAdoptPermissions = null;
9608        }
9609    }
9610
9611    /**
9612     * Asserts the parsed package is valid according to the given policy. If the
9613     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
9614     * <p>
9615     * Implementation detail: This method must NOT have any side effects. It would
9616     * ideally be static, but, it requires locks to read system state.
9617     *
9618     * @throws PackageManagerException If the package fails any of the validation checks
9619     */
9620    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9621            throws PackageManagerException {
9622        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9623            assertCodePolicy(pkg);
9624        }
9625
9626        if (pkg.applicationInfo.getCodePath() == null ||
9627                pkg.applicationInfo.getResourcePath() == null) {
9628            // Bail out. The resource and code paths haven't been set.
9629            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9630                    "Code and resource paths haven't been set correctly");
9631        }
9632
9633        // Make sure we're not adding any bogus keyset info
9634        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9635        ksms.assertScannedPackageValid(pkg);
9636
9637        synchronized (mPackages) {
9638            // The special "android" package can only be defined once
9639            if (pkg.packageName.equals("android")) {
9640                if (mAndroidApplication != null) {
9641                    Slog.w(TAG, "*************************************************");
9642                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9643                    Slog.w(TAG, " codePath=" + pkg.codePath);
9644                    Slog.w(TAG, "*************************************************");
9645                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9646                            "Core android package being redefined.  Skipping.");
9647                }
9648            }
9649
9650            // A package name must be unique; don't allow duplicates
9651            if (mPackages.containsKey(pkg.packageName)) {
9652                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9653                        "Application package " + pkg.packageName
9654                        + " already installed.  Skipping duplicate.");
9655            }
9656
9657            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9658                // Static libs have a synthetic package name containing the version
9659                // but we still want the base name to be unique.
9660                if (mPackages.containsKey(pkg.manifestPackageName)) {
9661                    throw new PackageManagerException(
9662                            "Duplicate static shared lib provider package");
9663                }
9664
9665                // Static shared libraries should have at least O target SDK
9666                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9667                    throw new PackageManagerException(
9668                            "Packages declaring static-shared libs must target O SDK or higher");
9669                }
9670
9671                // Package declaring static a shared lib cannot be instant apps
9672                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9673                    throw new PackageManagerException(
9674                            "Packages declaring static-shared libs cannot be instant apps");
9675                }
9676
9677                // Package declaring static a shared lib cannot be renamed since the package
9678                // name is synthetic and apps can't code around package manager internals.
9679                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9680                    throw new PackageManagerException(
9681                            "Packages declaring static-shared libs cannot be renamed");
9682                }
9683
9684                // Package declaring static a shared lib cannot declare child packages
9685                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9686                    throw new PackageManagerException(
9687                            "Packages declaring static-shared libs cannot have child packages");
9688                }
9689
9690                // Package declaring static a shared lib cannot declare dynamic libs
9691                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9692                    throw new PackageManagerException(
9693                            "Packages declaring static-shared libs cannot declare dynamic libs");
9694                }
9695
9696                // Package declaring static a shared lib cannot declare shared users
9697                if (pkg.mSharedUserId != null) {
9698                    throw new PackageManagerException(
9699                            "Packages declaring static-shared libs cannot declare shared users");
9700                }
9701
9702                // Static shared libs cannot declare activities
9703                if (!pkg.activities.isEmpty()) {
9704                    throw new PackageManagerException(
9705                            "Static shared libs cannot declare activities");
9706                }
9707
9708                // Static shared libs cannot declare services
9709                if (!pkg.services.isEmpty()) {
9710                    throw new PackageManagerException(
9711                            "Static shared libs cannot declare services");
9712                }
9713
9714                // Static shared libs cannot declare providers
9715                if (!pkg.providers.isEmpty()) {
9716                    throw new PackageManagerException(
9717                            "Static shared libs cannot declare content providers");
9718                }
9719
9720                // Static shared libs cannot declare receivers
9721                if (!pkg.receivers.isEmpty()) {
9722                    throw new PackageManagerException(
9723                            "Static shared libs cannot declare broadcast receivers");
9724                }
9725
9726                // Static shared libs cannot declare permission groups
9727                if (!pkg.permissionGroups.isEmpty()) {
9728                    throw new PackageManagerException(
9729                            "Static shared libs cannot declare permission groups");
9730                }
9731
9732                // Static shared libs cannot declare permissions
9733                if (!pkg.permissions.isEmpty()) {
9734                    throw new PackageManagerException(
9735                            "Static shared libs cannot declare permissions");
9736                }
9737
9738                // Static shared libs cannot declare protected broadcasts
9739                if (pkg.protectedBroadcasts != null) {
9740                    throw new PackageManagerException(
9741                            "Static shared libs cannot declare protected broadcasts");
9742                }
9743
9744                // Static shared libs cannot be overlay targets
9745                if (pkg.mOverlayTarget != null) {
9746                    throw new PackageManagerException(
9747                            "Static shared libs cannot be overlay targets");
9748                }
9749
9750                // The version codes must be ordered as lib versions
9751                int minVersionCode = Integer.MIN_VALUE;
9752                int maxVersionCode = Integer.MAX_VALUE;
9753
9754                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9755                        pkg.staticSharedLibName);
9756                if (versionedLib != null) {
9757                    final int versionCount = versionedLib.size();
9758                    for (int i = 0; i < versionCount; i++) {
9759                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9760                        // TODO: We will change version code to long, so in the new API it is long
9761                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9762                                .getVersionCode();
9763                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9764                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9765                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9766                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9767                        } else {
9768                            minVersionCode = maxVersionCode = libVersionCode;
9769                            break;
9770                        }
9771                    }
9772                }
9773                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9774                    throw new PackageManagerException("Static shared"
9775                            + " lib version codes must be ordered as lib versions");
9776                }
9777            }
9778
9779            // Only privileged apps and updated privileged apps can add child packages.
9780            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9781                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9782                    throw new PackageManagerException("Only privileged apps can add child "
9783                            + "packages. Ignoring package " + pkg.packageName);
9784                }
9785                final int childCount = pkg.childPackages.size();
9786                for (int i = 0; i < childCount; i++) {
9787                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9788                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9789                            childPkg.packageName)) {
9790                        throw new PackageManagerException("Can't override child of "
9791                                + "another disabled app. Ignoring package " + pkg.packageName);
9792                    }
9793                }
9794            }
9795
9796            // If we're only installing presumed-existing packages, require that the
9797            // scanned APK is both already known and at the path previously established
9798            // for it.  Previously unknown packages we pick up normally, but if we have an
9799            // a priori expectation about this package's install presence, enforce it.
9800            // With a singular exception for new system packages. When an OTA contains
9801            // a new system package, we allow the codepath to change from a system location
9802            // to the user-installed location. If we don't allow this change, any newer,
9803            // user-installed version of the application will be ignored.
9804            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9805                if (mExpectingBetter.containsKey(pkg.packageName)) {
9806                    logCriticalInfo(Log.WARN,
9807                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9808                } else {
9809                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9810                    if (known != null) {
9811                        if (DEBUG_PACKAGE_SCANNING) {
9812                            Log.d(TAG, "Examining " + pkg.codePath
9813                                    + " and requiring known paths " + known.codePathString
9814                                    + " & " + known.resourcePathString);
9815                        }
9816                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9817                                || !pkg.applicationInfo.getResourcePath().equals(
9818                                        known.resourcePathString)) {
9819                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9820                                    "Application package " + pkg.packageName
9821                                    + " found at " + pkg.applicationInfo.getCodePath()
9822                                    + " but expected at " + known.codePathString
9823                                    + "; ignoring.");
9824                        }
9825                    }
9826                }
9827            }
9828
9829            // Verify that this new package doesn't have any content providers
9830            // that conflict with existing packages.  Only do this if the
9831            // package isn't already installed, since we don't want to break
9832            // things that are installed.
9833            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9834                final int N = pkg.providers.size();
9835                int i;
9836                for (i=0; i<N; i++) {
9837                    PackageParser.Provider p = pkg.providers.get(i);
9838                    if (p.info.authority != null) {
9839                        String names[] = p.info.authority.split(";");
9840                        for (int j = 0; j < names.length; j++) {
9841                            if (mProvidersByAuthority.containsKey(names[j])) {
9842                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9843                                final String otherPackageName =
9844                                        ((other != null && other.getComponentName() != null) ?
9845                                                other.getComponentName().getPackageName() : "?");
9846                                throw new PackageManagerException(
9847                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9848                                        "Can't install because provider name " + names[j]
9849                                                + " (in package " + pkg.applicationInfo.packageName
9850                                                + ") is already used by " + otherPackageName);
9851                            }
9852                        }
9853                    }
9854                }
9855            }
9856        }
9857    }
9858
9859    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9860            int type, String declaringPackageName, int declaringVersionCode) {
9861        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9862        if (versionedLib == null) {
9863            versionedLib = new SparseArray<>();
9864            mSharedLibraries.put(name, versionedLib);
9865            if (type == SharedLibraryInfo.TYPE_STATIC) {
9866                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9867            }
9868        } else if (versionedLib.indexOfKey(version) >= 0) {
9869            return false;
9870        }
9871        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9872                version, type, declaringPackageName, declaringVersionCode);
9873        versionedLib.put(version, libEntry);
9874        return true;
9875    }
9876
9877    private boolean removeSharedLibraryLPw(String name, int version) {
9878        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9879        if (versionedLib == null) {
9880            return false;
9881        }
9882        final int libIdx = versionedLib.indexOfKey(version);
9883        if (libIdx < 0) {
9884            return false;
9885        }
9886        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9887        versionedLib.remove(version);
9888        if (versionedLib.size() <= 0) {
9889            mSharedLibraries.remove(name);
9890            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9891                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9892                        .getPackageName());
9893            }
9894        }
9895        return true;
9896    }
9897
9898    /**
9899     * Adds a scanned package to the system. When this method is finished, the package will
9900     * be available for query, resolution, etc...
9901     */
9902    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9903            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9904        final String pkgName = pkg.packageName;
9905        if (mCustomResolverComponentName != null &&
9906                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9907            setUpCustomResolverActivity(pkg);
9908        }
9909
9910        if (pkg.packageName.equals("android")) {
9911            synchronized (mPackages) {
9912                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9913                    // Set up information for our fall-back user intent resolution activity.
9914                    mPlatformPackage = pkg;
9915                    pkg.mVersionCode = mSdkVersion;
9916                    mAndroidApplication = pkg.applicationInfo;
9917                    if (!mResolverReplaced) {
9918                        mResolveActivity.applicationInfo = mAndroidApplication;
9919                        mResolveActivity.name = ResolverActivity.class.getName();
9920                        mResolveActivity.packageName = mAndroidApplication.packageName;
9921                        mResolveActivity.processName = "system:ui";
9922                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9923                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9924                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9925                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9926                        mResolveActivity.exported = true;
9927                        mResolveActivity.enabled = true;
9928                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9929                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9930                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9931                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9932                                | ActivityInfo.CONFIG_ORIENTATION
9933                                | ActivityInfo.CONFIG_KEYBOARD
9934                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9935                        mResolveInfo.activityInfo = mResolveActivity;
9936                        mResolveInfo.priority = 0;
9937                        mResolveInfo.preferredOrder = 0;
9938                        mResolveInfo.match = 0;
9939                        mResolveComponentName = new ComponentName(
9940                                mAndroidApplication.packageName, mResolveActivity.name);
9941                    }
9942                }
9943            }
9944        }
9945
9946        ArrayList<PackageParser.Package> clientLibPkgs = null;
9947        // writer
9948        synchronized (mPackages) {
9949            boolean hasStaticSharedLibs = false;
9950
9951            // Any app can add new static shared libraries
9952            if (pkg.staticSharedLibName != null) {
9953                // Static shared libs don't allow renaming as they have synthetic package
9954                // names to allow install of multiple versions, so use name from manifest.
9955                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9956                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9957                        pkg.manifestPackageName, pkg.mVersionCode)) {
9958                    hasStaticSharedLibs = true;
9959                } else {
9960                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9961                                + pkg.staticSharedLibName + " already exists; skipping");
9962                }
9963                // Static shared libs cannot be updated once installed since they
9964                // use synthetic package name which includes the version code, so
9965                // not need to update other packages's shared lib dependencies.
9966            }
9967
9968            if (!hasStaticSharedLibs
9969                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9970                // Only system apps can add new dynamic shared libraries.
9971                if (pkg.libraryNames != null) {
9972                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9973                        String name = pkg.libraryNames.get(i);
9974                        boolean allowed = false;
9975                        if (pkg.isUpdatedSystemApp()) {
9976                            // New library entries can only be added through the
9977                            // system image.  This is important to get rid of a lot
9978                            // of nasty edge cases: for example if we allowed a non-
9979                            // system update of the app to add a library, then uninstalling
9980                            // the update would make the library go away, and assumptions
9981                            // we made such as through app install filtering would now
9982                            // have allowed apps on the device which aren't compatible
9983                            // with it.  Better to just have the restriction here, be
9984                            // conservative, and create many fewer cases that can negatively
9985                            // impact the user experience.
9986                            final PackageSetting sysPs = mSettings
9987                                    .getDisabledSystemPkgLPr(pkg.packageName);
9988                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9989                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9990                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9991                                        allowed = true;
9992                                        break;
9993                                    }
9994                                }
9995                            }
9996                        } else {
9997                            allowed = true;
9998                        }
9999                        if (allowed) {
10000                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10001                                    SharedLibraryInfo.VERSION_UNDEFINED,
10002                                    SharedLibraryInfo.TYPE_DYNAMIC,
10003                                    pkg.packageName, pkg.mVersionCode)) {
10004                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10005                                        + name + " already exists; skipping");
10006                            }
10007                        } else {
10008                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10009                                    + name + " that is not declared on system image; skipping");
10010                        }
10011                    }
10012
10013                    if ((scanFlags & SCAN_BOOTING) == 0) {
10014                        // If we are not booting, we need to update any applications
10015                        // that are clients of our shared library.  If we are booting,
10016                        // this will all be done once the scan is complete.
10017                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10018                    }
10019                }
10020            }
10021        }
10022
10023        if ((scanFlags & SCAN_BOOTING) != 0) {
10024            // No apps can run during boot scan, so they don't need to be frozen
10025        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10026            // Caller asked to not kill app, so it's probably not frozen
10027        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10028            // Caller asked us to ignore frozen check for some reason; they
10029            // probably didn't know the package name
10030        } else {
10031            // We're doing major surgery on this package, so it better be frozen
10032            // right now to keep it from launching
10033            checkPackageFrozen(pkgName);
10034        }
10035
10036        // Also need to kill any apps that are dependent on the library.
10037        if (clientLibPkgs != null) {
10038            for (int i=0; i<clientLibPkgs.size(); i++) {
10039                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10040                killApplication(clientPkg.applicationInfo.packageName,
10041                        clientPkg.applicationInfo.uid, "update lib");
10042            }
10043        }
10044
10045        // writer
10046        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10047
10048        synchronized (mPackages) {
10049            // We don't expect installation to fail beyond this point
10050
10051            if (pkgSetting.pkg != null) {
10052                // Note that |user| might be null during the initial boot scan. If a codePath
10053                // for an app has changed during a boot scan, it's due to an app update that's
10054                // part of the system partition and marker changes must be applied to all users.
10055                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
10056                final int[] userIds = resolveUserIds(userId);
10057                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
10058            }
10059
10060            // Add the new setting to mSettings
10061            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10062            // Add the new setting to mPackages
10063            mPackages.put(pkg.applicationInfo.packageName, pkg);
10064            // Make sure we don't accidentally delete its data.
10065            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10066            while (iter.hasNext()) {
10067                PackageCleanItem item = iter.next();
10068                if (pkgName.equals(item.packageName)) {
10069                    iter.remove();
10070                }
10071            }
10072
10073            // Add the package's KeySets to the global KeySetManagerService
10074            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10075            ksms.addScannedPackageLPw(pkg);
10076
10077            int N = pkg.providers.size();
10078            StringBuilder r = null;
10079            int i;
10080            for (i=0; i<N; i++) {
10081                PackageParser.Provider p = pkg.providers.get(i);
10082                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10083                        p.info.processName);
10084                mProviders.addProvider(p);
10085                p.syncable = p.info.isSyncable;
10086                if (p.info.authority != null) {
10087                    String names[] = p.info.authority.split(";");
10088                    p.info.authority = null;
10089                    for (int j = 0; j < names.length; j++) {
10090                        if (j == 1 && p.syncable) {
10091                            // We only want the first authority for a provider to possibly be
10092                            // syncable, so if we already added this provider using a different
10093                            // authority clear the syncable flag. We copy the provider before
10094                            // changing it because the mProviders object contains a reference
10095                            // to a provider that we don't want to change.
10096                            // Only do this for the second authority since the resulting provider
10097                            // object can be the same for all future authorities for this provider.
10098                            p = new PackageParser.Provider(p);
10099                            p.syncable = false;
10100                        }
10101                        if (!mProvidersByAuthority.containsKey(names[j])) {
10102                            mProvidersByAuthority.put(names[j], p);
10103                            if (p.info.authority == null) {
10104                                p.info.authority = names[j];
10105                            } else {
10106                                p.info.authority = p.info.authority + ";" + names[j];
10107                            }
10108                            if (DEBUG_PACKAGE_SCANNING) {
10109                                if (chatty)
10110                                    Log.d(TAG, "Registered content provider: " + names[j]
10111                                            + ", className = " + p.info.name + ", isSyncable = "
10112                                            + p.info.isSyncable);
10113                            }
10114                        } else {
10115                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10116                            Slog.w(TAG, "Skipping provider name " + names[j] +
10117                                    " (in package " + pkg.applicationInfo.packageName +
10118                                    "): name already used by "
10119                                    + ((other != null && other.getComponentName() != null)
10120                                            ? other.getComponentName().getPackageName() : "?"));
10121                        }
10122                    }
10123                }
10124                if (chatty) {
10125                    if (r == null) {
10126                        r = new StringBuilder(256);
10127                    } else {
10128                        r.append(' ');
10129                    }
10130                    r.append(p.info.name);
10131                }
10132            }
10133            if (r != null) {
10134                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10135            }
10136
10137            N = pkg.services.size();
10138            r = null;
10139            for (i=0; i<N; i++) {
10140                PackageParser.Service s = pkg.services.get(i);
10141                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10142                        s.info.processName);
10143                mServices.addService(s);
10144                if (chatty) {
10145                    if (r == null) {
10146                        r = new StringBuilder(256);
10147                    } else {
10148                        r.append(' ');
10149                    }
10150                    r.append(s.info.name);
10151                }
10152            }
10153            if (r != null) {
10154                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10155            }
10156
10157            N = pkg.receivers.size();
10158            r = null;
10159            for (i=0; i<N; i++) {
10160                PackageParser.Activity a = pkg.receivers.get(i);
10161                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10162                        a.info.processName);
10163                mReceivers.addActivity(a, "receiver");
10164                if (chatty) {
10165                    if (r == null) {
10166                        r = new StringBuilder(256);
10167                    } else {
10168                        r.append(' ');
10169                    }
10170                    r.append(a.info.name);
10171                }
10172            }
10173            if (r != null) {
10174                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10175            }
10176
10177            N = pkg.activities.size();
10178            r = null;
10179            for (i=0; i<N; i++) {
10180                PackageParser.Activity a = pkg.activities.get(i);
10181                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10182                        a.info.processName);
10183                mActivities.addActivity(a, "activity");
10184                if (chatty) {
10185                    if (r == null) {
10186                        r = new StringBuilder(256);
10187                    } else {
10188                        r.append(' ');
10189                    }
10190                    r.append(a.info.name);
10191                }
10192            }
10193            if (r != null) {
10194                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10195            }
10196
10197            N = pkg.permissionGroups.size();
10198            r = null;
10199            for (i=0; i<N; i++) {
10200                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10201                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10202                final String curPackageName = cur == null ? null : cur.info.packageName;
10203                // Dont allow ephemeral apps to define new permission groups.
10204                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10205                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10206                            + pg.info.packageName
10207                            + " ignored: instant apps cannot define new permission groups.");
10208                    continue;
10209                }
10210                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10211                if (cur == null || isPackageUpdate) {
10212                    mPermissionGroups.put(pg.info.name, pg);
10213                    if (chatty) {
10214                        if (r == null) {
10215                            r = new StringBuilder(256);
10216                        } else {
10217                            r.append(' ');
10218                        }
10219                        if (isPackageUpdate) {
10220                            r.append("UPD:");
10221                        }
10222                        r.append(pg.info.name);
10223                    }
10224                } else {
10225                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10226                            + pg.info.packageName + " ignored: original from "
10227                            + cur.info.packageName);
10228                    if (chatty) {
10229                        if (r == null) {
10230                            r = new StringBuilder(256);
10231                        } else {
10232                            r.append(' ');
10233                        }
10234                        r.append("DUP:");
10235                        r.append(pg.info.name);
10236                    }
10237                }
10238            }
10239            if (r != null) {
10240                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10241            }
10242
10243            N = pkg.permissions.size();
10244            r = null;
10245            for (i=0; i<N; i++) {
10246                PackageParser.Permission p = pkg.permissions.get(i);
10247
10248                // Dont allow ephemeral apps to define new permissions.
10249                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10250                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10251                            + p.info.packageName
10252                            + " ignored: instant apps cannot define new permissions.");
10253                    continue;
10254                }
10255
10256                // Assume by default that we did not install this permission into the system.
10257                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10258
10259                // Now that permission groups have a special meaning, we ignore permission
10260                // groups for legacy apps to prevent unexpected behavior. In particular,
10261                // permissions for one app being granted to someone just becase they happen
10262                // to be in a group defined by another app (before this had no implications).
10263                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10264                    p.group = mPermissionGroups.get(p.info.group);
10265                    // Warn for a permission in an unknown group.
10266                    if (p.info.group != null && p.group == null) {
10267                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10268                                + p.info.packageName + " in an unknown group " + p.info.group);
10269                    }
10270                }
10271
10272                ArrayMap<String, BasePermission> permissionMap =
10273                        p.tree ? mSettings.mPermissionTrees
10274                                : mSettings.mPermissions;
10275                BasePermission bp = permissionMap.get(p.info.name);
10276
10277                // Allow system apps to redefine non-system permissions
10278                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10279                    final boolean currentOwnerIsSystem = (bp.perm != null
10280                            && isSystemApp(bp.perm.owner));
10281                    if (isSystemApp(p.owner)) {
10282                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10283                            // It's a built-in permission and no owner, take ownership now
10284                            bp.packageSetting = pkgSetting;
10285                            bp.perm = p;
10286                            bp.uid = pkg.applicationInfo.uid;
10287                            bp.sourcePackage = p.info.packageName;
10288                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10289                        } else if (!currentOwnerIsSystem) {
10290                            String msg = "New decl " + p.owner + " of permission  "
10291                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10292                            reportSettingsProblem(Log.WARN, msg);
10293                            bp = null;
10294                        }
10295                    }
10296                }
10297
10298                if (bp == null) {
10299                    bp = new BasePermission(p.info.name, p.info.packageName,
10300                            BasePermission.TYPE_NORMAL);
10301                    permissionMap.put(p.info.name, bp);
10302                }
10303
10304                if (bp.perm == null) {
10305                    if (bp.sourcePackage == null
10306                            || bp.sourcePackage.equals(p.info.packageName)) {
10307                        BasePermission tree = findPermissionTreeLP(p.info.name);
10308                        if (tree == null
10309                                || tree.sourcePackage.equals(p.info.packageName)) {
10310                            bp.packageSetting = pkgSetting;
10311                            bp.perm = p;
10312                            bp.uid = pkg.applicationInfo.uid;
10313                            bp.sourcePackage = p.info.packageName;
10314                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10315                            if (chatty) {
10316                                if (r == null) {
10317                                    r = new StringBuilder(256);
10318                                } else {
10319                                    r.append(' ');
10320                                }
10321                                r.append(p.info.name);
10322                            }
10323                        } else {
10324                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10325                                    + p.info.packageName + " ignored: base tree "
10326                                    + tree.name + " is from package "
10327                                    + tree.sourcePackage);
10328                        }
10329                    } else {
10330                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10331                                + p.info.packageName + " ignored: original from "
10332                                + bp.sourcePackage);
10333                    }
10334                } else if (chatty) {
10335                    if (r == null) {
10336                        r = new StringBuilder(256);
10337                    } else {
10338                        r.append(' ');
10339                    }
10340                    r.append("DUP:");
10341                    r.append(p.info.name);
10342                }
10343                if (bp.perm == p) {
10344                    bp.protectionLevel = p.info.protectionLevel;
10345                }
10346            }
10347
10348            if (r != null) {
10349                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10350            }
10351
10352            N = pkg.instrumentation.size();
10353            r = null;
10354            for (i=0; i<N; i++) {
10355                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10356                a.info.packageName = pkg.applicationInfo.packageName;
10357                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10358                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10359                a.info.splitNames = pkg.splitNames;
10360                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10361                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10362                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10363                a.info.dataDir = pkg.applicationInfo.dataDir;
10364                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10365                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10366                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10367                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10368                mInstrumentation.put(a.getComponentName(), a);
10369                if (chatty) {
10370                    if (r == null) {
10371                        r = new StringBuilder(256);
10372                    } else {
10373                        r.append(' ');
10374                    }
10375                    r.append(a.info.name);
10376                }
10377            }
10378            if (r != null) {
10379                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10380            }
10381
10382            if (pkg.protectedBroadcasts != null) {
10383                N = pkg.protectedBroadcasts.size();
10384                for (i=0; i<N; i++) {
10385                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10386                }
10387            }
10388        }
10389
10390        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10391    }
10392
10393    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
10394            PackageParser.Package update, int[] userIds) {
10395        if (existing.applicationInfo == null || update.applicationInfo == null) {
10396            // This isn't due to an app installation.
10397            return;
10398        }
10399
10400        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
10401        final File newCodePath = new File(update.applicationInfo.getCodePath());
10402
10403        // The codePath hasn't changed, so there's nothing for us to do.
10404        if (Objects.equals(oldCodePath, newCodePath)) {
10405            return;
10406        }
10407
10408        File canonicalNewCodePath;
10409        try {
10410            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
10411        } catch (IOException e) {
10412            Slog.w(TAG, "Failed to get canonical path.", e);
10413            return;
10414        }
10415
10416        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
10417        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
10418        // that the last component of the path (i.e, the name) doesn't need canonicalization
10419        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
10420        // but may change in the future. Hopefully this function won't exist at that point.
10421        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
10422                oldCodePath.getName());
10423
10424        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
10425        // with "@".
10426        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
10427        if (!oldMarkerPrefix.endsWith("@")) {
10428            oldMarkerPrefix += "@";
10429        }
10430        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
10431        if (!newMarkerPrefix.endsWith("@")) {
10432            newMarkerPrefix += "@";
10433        }
10434
10435        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
10436        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
10437        for (String updatedPath : updatedPaths) {
10438            String updatedPathName = new File(updatedPath).getName();
10439            markerSuffixes.add(updatedPathName.replace('/', '@'));
10440        }
10441
10442        for (int userId : userIds) {
10443            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
10444
10445            for (String markerSuffix : markerSuffixes) {
10446                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
10447                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
10448                if (oldForeignUseMark.exists()) {
10449                    try {
10450                        Os.rename(oldForeignUseMark.getAbsolutePath(),
10451                                newForeignUseMark.getAbsolutePath());
10452                    } catch (ErrnoException e) {
10453                        Slog.w(TAG, "Failed to rename foreign use marker", e);
10454                        oldForeignUseMark.delete();
10455                    }
10456                }
10457            }
10458        }
10459    }
10460
10461    /**
10462     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10463     * is derived purely on the basis of the contents of {@code scanFile} and
10464     * {@code cpuAbiOverride}.
10465     *
10466     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10467     */
10468    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10469                                 String cpuAbiOverride, boolean extractLibs,
10470                                 File appLib32InstallDir)
10471            throws PackageManagerException {
10472        // Give ourselves some initial paths; we'll come back for another
10473        // pass once we've determined ABI below.
10474        setNativeLibraryPaths(pkg, appLib32InstallDir);
10475
10476        // We would never need to extract libs for forward-locked and external packages,
10477        // since the container service will do it for us. We shouldn't attempt to
10478        // extract libs from system app when it was not updated.
10479        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10480                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10481            extractLibs = false;
10482        }
10483
10484        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10485        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10486
10487        NativeLibraryHelper.Handle handle = null;
10488        try {
10489            handle = NativeLibraryHelper.Handle.create(pkg);
10490            // TODO(multiArch): This can be null for apps that didn't go through the
10491            // usual installation process. We can calculate it again, like we
10492            // do during install time.
10493            //
10494            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10495            // unnecessary.
10496            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10497
10498            // Null out the abis so that they can be recalculated.
10499            pkg.applicationInfo.primaryCpuAbi = null;
10500            pkg.applicationInfo.secondaryCpuAbi = null;
10501            if (isMultiArch(pkg.applicationInfo)) {
10502                // Warn if we've set an abiOverride for multi-lib packages..
10503                // By definition, we need to copy both 32 and 64 bit libraries for
10504                // such packages.
10505                if (pkg.cpuAbiOverride != null
10506                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10507                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10508                }
10509
10510                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10511                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10512                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10513                    if (extractLibs) {
10514                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10515                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10516                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10517                                useIsaSpecificSubdirs);
10518                    } else {
10519                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10520                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10521                    }
10522                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10523                }
10524
10525                maybeThrowExceptionForMultiArchCopy(
10526                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10527
10528                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10529                    if (extractLibs) {
10530                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10531                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10532                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10533                                useIsaSpecificSubdirs);
10534                    } else {
10535                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10536                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10537                    }
10538                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10539                }
10540
10541                maybeThrowExceptionForMultiArchCopy(
10542                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10543
10544                if (abi64 >= 0) {
10545                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10546                }
10547
10548                if (abi32 >= 0) {
10549                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10550                    if (abi64 >= 0) {
10551                        if (pkg.use32bitAbi) {
10552                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10553                            pkg.applicationInfo.primaryCpuAbi = abi;
10554                        } else {
10555                            pkg.applicationInfo.secondaryCpuAbi = abi;
10556                        }
10557                    } else {
10558                        pkg.applicationInfo.primaryCpuAbi = abi;
10559                    }
10560                }
10561
10562            } else {
10563                String[] abiList = (cpuAbiOverride != null) ?
10564                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10565
10566                // Enable gross and lame hacks for apps that are built with old
10567                // SDK tools. We must scan their APKs for renderscript bitcode and
10568                // not launch them if it's present. Don't bother checking on devices
10569                // that don't have 64 bit support.
10570                boolean needsRenderScriptOverride = false;
10571                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10572                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10573                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10574                    needsRenderScriptOverride = true;
10575                }
10576
10577                final int copyRet;
10578                if (extractLibs) {
10579                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10580                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10581                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10582                } else {
10583                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10584                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10585                }
10586                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10587
10588                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10589                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10590                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10591                }
10592
10593                if (copyRet >= 0) {
10594                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10595                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10596                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10597                } else if (needsRenderScriptOverride) {
10598                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10599                }
10600            }
10601        } catch (IOException ioe) {
10602            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10603        } finally {
10604            IoUtils.closeQuietly(handle);
10605        }
10606
10607        // Now that we've calculated the ABIs and determined if it's an internal app,
10608        // we will go ahead and populate the nativeLibraryPath.
10609        setNativeLibraryPaths(pkg, appLib32InstallDir);
10610    }
10611
10612    /**
10613     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10614     * i.e, so that all packages can be run inside a single process if required.
10615     *
10616     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10617     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10618     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10619     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10620     * updating a package that belongs to a shared user.
10621     *
10622     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10623     * adds unnecessary complexity.
10624     */
10625    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10626            PackageParser.Package scannedPackage) {
10627        String requiredInstructionSet = null;
10628        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10629            requiredInstructionSet = VMRuntime.getInstructionSet(
10630                     scannedPackage.applicationInfo.primaryCpuAbi);
10631        }
10632
10633        PackageSetting requirer = null;
10634        for (PackageSetting ps : packagesForUser) {
10635            // If packagesForUser contains scannedPackage, we skip it. This will happen
10636            // when scannedPackage is an update of an existing package. Without this check,
10637            // we will never be able to change the ABI of any package belonging to a shared
10638            // user, even if it's compatible with other packages.
10639            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10640                if (ps.primaryCpuAbiString == null) {
10641                    continue;
10642                }
10643
10644                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10645                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10646                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10647                    // this but there's not much we can do.
10648                    String errorMessage = "Instruction set mismatch, "
10649                            + ((requirer == null) ? "[caller]" : requirer)
10650                            + " requires " + requiredInstructionSet + " whereas " + ps
10651                            + " requires " + instructionSet;
10652                    Slog.w(TAG, errorMessage);
10653                }
10654
10655                if (requiredInstructionSet == null) {
10656                    requiredInstructionSet = instructionSet;
10657                    requirer = ps;
10658                }
10659            }
10660        }
10661
10662        if (requiredInstructionSet != null) {
10663            String adjustedAbi;
10664            if (requirer != null) {
10665                // requirer != null implies that either scannedPackage was null or that scannedPackage
10666                // did not require an ABI, in which case we have to adjust scannedPackage to match
10667                // the ABI of the set (which is the same as requirer's ABI)
10668                adjustedAbi = requirer.primaryCpuAbiString;
10669                if (scannedPackage != null) {
10670                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10671                }
10672            } else {
10673                // requirer == null implies that we're updating all ABIs in the set to
10674                // match scannedPackage.
10675                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10676            }
10677
10678            for (PackageSetting ps : packagesForUser) {
10679                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10680                    if (ps.primaryCpuAbiString != null) {
10681                        continue;
10682                    }
10683
10684                    ps.primaryCpuAbiString = adjustedAbi;
10685                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10686                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10687                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10688                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10689                                + " (requirer="
10690                                + (requirer == null ? "null" : requirer.pkg.packageName)
10691                                + ", scannedPackage="
10692                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10693                                + ")");
10694                        try {
10695                            mInstaller.rmdex(ps.codePathString,
10696                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10697                        } catch (InstallerException ignored) {
10698                        }
10699                    }
10700                }
10701            }
10702        }
10703    }
10704
10705    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10706        synchronized (mPackages) {
10707            mResolverReplaced = true;
10708            // Set up information for custom user intent resolution activity.
10709            mResolveActivity.applicationInfo = pkg.applicationInfo;
10710            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10711            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10712            mResolveActivity.processName = pkg.applicationInfo.packageName;
10713            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10714            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10715                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10716            mResolveActivity.theme = 0;
10717            mResolveActivity.exported = true;
10718            mResolveActivity.enabled = true;
10719            mResolveInfo.activityInfo = mResolveActivity;
10720            mResolveInfo.priority = 0;
10721            mResolveInfo.preferredOrder = 0;
10722            mResolveInfo.match = 0;
10723            mResolveComponentName = mCustomResolverComponentName;
10724            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10725                    mResolveComponentName);
10726        }
10727    }
10728
10729    private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) {
10730        if (installerComponent == null) {
10731            if (DEBUG_EPHEMERAL) {
10732                Slog.d(TAG, "Clear ephemeral installer activity");
10733            }
10734            mInstantAppInstallerActivity.applicationInfo = null;
10735            return;
10736        }
10737
10738        if (DEBUG_EPHEMERAL) {
10739            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10740        }
10741        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10742        // Set up information for ephemeral installer activity
10743        mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo;
10744        mInstantAppInstallerActivity.name = installerComponent.getClassName();
10745        mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName;
10746        mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName;
10747        mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10748        mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10749                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10750        mInstantAppInstallerActivity.theme = 0;
10751        mInstantAppInstallerActivity.exported = true;
10752        mInstantAppInstallerActivity.enabled = true;
10753        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10754        mInstantAppInstallerInfo.priority = 0;
10755        mInstantAppInstallerInfo.preferredOrder = 1;
10756        mInstantAppInstallerInfo.isDefault = true;
10757        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10758                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10759    }
10760
10761    private static String calculateBundledApkRoot(final String codePathString) {
10762        final File codePath = new File(codePathString);
10763        final File codeRoot;
10764        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10765            codeRoot = Environment.getRootDirectory();
10766        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10767            codeRoot = Environment.getOemDirectory();
10768        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10769            codeRoot = Environment.getVendorDirectory();
10770        } else {
10771            // Unrecognized code path; take its top real segment as the apk root:
10772            // e.g. /something/app/blah.apk => /something
10773            try {
10774                File f = codePath.getCanonicalFile();
10775                File parent = f.getParentFile();    // non-null because codePath is a file
10776                File tmp;
10777                while ((tmp = parent.getParentFile()) != null) {
10778                    f = parent;
10779                    parent = tmp;
10780                }
10781                codeRoot = f;
10782                Slog.w(TAG, "Unrecognized code path "
10783                        + codePath + " - using " + codeRoot);
10784            } catch (IOException e) {
10785                // Can't canonicalize the code path -- shenanigans?
10786                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10787                return Environment.getRootDirectory().getPath();
10788            }
10789        }
10790        return codeRoot.getPath();
10791    }
10792
10793    /**
10794     * Derive and set the location of native libraries for the given package,
10795     * which varies depending on where and how the package was installed.
10796     */
10797    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10798        final ApplicationInfo info = pkg.applicationInfo;
10799        final String codePath = pkg.codePath;
10800        final File codeFile = new File(codePath);
10801        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10802        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10803
10804        info.nativeLibraryRootDir = null;
10805        info.nativeLibraryRootRequiresIsa = false;
10806        info.nativeLibraryDir = null;
10807        info.secondaryNativeLibraryDir = null;
10808
10809        if (isApkFile(codeFile)) {
10810            // Monolithic install
10811            if (bundledApp) {
10812                // If "/system/lib64/apkname" exists, assume that is the per-package
10813                // native library directory to use; otherwise use "/system/lib/apkname".
10814                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10815                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10816                        getPrimaryInstructionSet(info));
10817
10818                // This is a bundled system app so choose the path based on the ABI.
10819                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10820                // is just the default path.
10821                final String apkName = deriveCodePathName(codePath);
10822                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10823                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10824                        apkName).getAbsolutePath();
10825
10826                if (info.secondaryCpuAbi != null) {
10827                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10828                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10829                            secondaryLibDir, apkName).getAbsolutePath();
10830                }
10831            } else if (asecApp) {
10832                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10833                        .getAbsolutePath();
10834            } else {
10835                final String apkName = deriveCodePathName(codePath);
10836                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10837                        .getAbsolutePath();
10838            }
10839
10840            info.nativeLibraryRootRequiresIsa = false;
10841            info.nativeLibraryDir = info.nativeLibraryRootDir;
10842        } else {
10843            // Cluster install
10844            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10845            info.nativeLibraryRootRequiresIsa = true;
10846
10847            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10848                    getPrimaryInstructionSet(info)).getAbsolutePath();
10849
10850            if (info.secondaryCpuAbi != null) {
10851                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10852                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10853            }
10854        }
10855    }
10856
10857    /**
10858     * Calculate the abis and roots for a bundled app. These can uniquely
10859     * be determined from the contents of the system partition, i.e whether
10860     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10861     * of this information, and instead assume that the system was built
10862     * sensibly.
10863     */
10864    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10865                                           PackageSetting pkgSetting) {
10866        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10867
10868        // If "/system/lib64/apkname" exists, assume that is the per-package
10869        // native library directory to use; otherwise use "/system/lib/apkname".
10870        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10871        setBundledAppAbi(pkg, apkRoot, apkName);
10872        // pkgSetting might be null during rescan following uninstall of updates
10873        // to a bundled app, so accommodate that possibility.  The settings in
10874        // that case will be established later from the parsed package.
10875        //
10876        // If the settings aren't null, sync them up with what we've just derived.
10877        // note that apkRoot isn't stored in the package settings.
10878        if (pkgSetting != null) {
10879            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10880            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10881        }
10882    }
10883
10884    /**
10885     * Deduces the ABI of a bundled app and sets the relevant fields on the
10886     * parsed pkg object.
10887     *
10888     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10889     *        under which system libraries are installed.
10890     * @param apkName the name of the installed package.
10891     */
10892    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10893        final File codeFile = new File(pkg.codePath);
10894
10895        final boolean has64BitLibs;
10896        final boolean has32BitLibs;
10897        if (isApkFile(codeFile)) {
10898            // Monolithic install
10899            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10900            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10901        } else {
10902            // Cluster install
10903            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10904            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10905                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10906                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10907                has64BitLibs = (new File(rootDir, isa)).exists();
10908            } else {
10909                has64BitLibs = false;
10910            }
10911            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10912                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10913                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10914                has32BitLibs = (new File(rootDir, isa)).exists();
10915            } else {
10916                has32BitLibs = false;
10917            }
10918        }
10919
10920        if (has64BitLibs && !has32BitLibs) {
10921            // The package has 64 bit libs, but not 32 bit libs. Its primary
10922            // ABI should be 64 bit. We can safely assume here that the bundled
10923            // native libraries correspond to the most preferred ABI in the list.
10924
10925            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10926            pkg.applicationInfo.secondaryCpuAbi = null;
10927        } else if (has32BitLibs && !has64BitLibs) {
10928            // The package has 32 bit libs but not 64 bit libs. Its primary
10929            // ABI should be 32 bit.
10930
10931            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10932            pkg.applicationInfo.secondaryCpuAbi = null;
10933        } else if (has32BitLibs && has64BitLibs) {
10934            // The application has both 64 and 32 bit bundled libraries. We check
10935            // here that the app declares multiArch support, and warn if it doesn't.
10936            //
10937            // We will be lenient here and record both ABIs. The primary will be the
10938            // ABI that's higher on the list, i.e, a device that's configured to prefer
10939            // 64 bit apps will see a 64 bit primary ABI,
10940
10941            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10942                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10943            }
10944
10945            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10946                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10947                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10948            } else {
10949                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10950                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10951            }
10952        } else {
10953            pkg.applicationInfo.primaryCpuAbi = null;
10954            pkg.applicationInfo.secondaryCpuAbi = null;
10955        }
10956    }
10957
10958    private void killApplication(String pkgName, int appId, String reason) {
10959        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10960    }
10961
10962    private void killApplication(String pkgName, int appId, int userId, String reason) {
10963        // Request the ActivityManager to kill the process(only for existing packages)
10964        // so that we do not end up in a confused state while the user is still using the older
10965        // version of the application while the new one gets installed.
10966        final long token = Binder.clearCallingIdentity();
10967        try {
10968            IActivityManager am = ActivityManager.getService();
10969            if (am != null) {
10970                try {
10971                    am.killApplication(pkgName, appId, userId, reason);
10972                } catch (RemoteException e) {
10973                }
10974            }
10975        } finally {
10976            Binder.restoreCallingIdentity(token);
10977        }
10978    }
10979
10980    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10981        // Remove the parent package setting
10982        PackageSetting ps = (PackageSetting) pkg.mExtras;
10983        if (ps != null) {
10984            removePackageLI(ps, chatty);
10985        }
10986        // Remove the child package setting
10987        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10988        for (int i = 0; i < childCount; i++) {
10989            PackageParser.Package childPkg = pkg.childPackages.get(i);
10990            ps = (PackageSetting) childPkg.mExtras;
10991            if (ps != null) {
10992                removePackageLI(ps, chatty);
10993            }
10994        }
10995    }
10996
10997    void removePackageLI(PackageSetting ps, boolean chatty) {
10998        if (DEBUG_INSTALL) {
10999            if (chatty)
11000                Log.d(TAG, "Removing package " + ps.name);
11001        }
11002
11003        // writer
11004        synchronized (mPackages) {
11005            mPackages.remove(ps.name);
11006            final PackageParser.Package pkg = ps.pkg;
11007            if (pkg != null) {
11008                cleanPackageDataStructuresLILPw(pkg, chatty);
11009            }
11010        }
11011    }
11012
11013    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11014        if (DEBUG_INSTALL) {
11015            if (chatty)
11016                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11017        }
11018
11019        // writer
11020        synchronized (mPackages) {
11021            // Remove the parent package
11022            mPackages.remove(pkg.applicationInfo.packageName);
11023            cleanPackageDataStructuresLILPw(pkg, chatty);
11024
11025            // Remove the child packages
11026            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11027            for (int i = 0; i < childCount; i++) {
11028                PackageParser.Package childPkg = pkg.childPackages.get(i);
11029                mPackages.remove(childPkg.applicationInfo.packageName);
11030                cleanPackageDataStructuresLILPw(childPkg, chatty);
11031            }
11032        }
11033    }
11034
11035    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11036        int N = pkg.providers.size();
11037        StringBuilder r = null;
11038        int i;
11039        for (i=0; i<N; i++) {
11040            PackageParser.Provider p = pkg.providers.get(i);
11041            mProviders.removeProvider(p);
11042            if (p.info.authority == null) {
11043
11044                /* There was another ContentProvider with this authority when
11045                 * this app was installed so this authority is null,
11046                 * Ignore it as we don't have to unregister the provider.
11047                 */
11048                continue;
11049            }
11050            String names[] = p.info.authority.split(";");
11051            for (int j = 0; j < names.length; j++) {
11052                if (mProvidersByAuthority.get(names[j]) == p) {
11053                    mProvidersByAuthority.remove(names[j]);
11054                    if (DEBUG_REMOVE) {
11055                        if (chatty)
11056                            Log.d(TAG, "Unregistered content provider: " + names[j]
11057                                    + ", className = " + p.info.name + ", isSyncable = "
11058                                    + p.info.isSyncable);
11059                    }
11060                }
11061            }
11062            if (DEBUG_REMOVE && chatty) {
11063                if (r == null) {
11064                    r = new StringBuilder(256);
11065                } else {
11066                    r.append(' ');
11067                }
11068                r.append(p.info.name);
11069            }
11070        }
11071        if (r != null) {
11072            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11073        }
11074
11075        N = pkg.services.size();
11076        r = null;
11077        for (i=0; i<N; i++) {
11078            PackageParser.Service s = pkg.services.get(i);
11079            mServices.removeService(s);
11080            if (chatty) {
11081                if (r == null) {
11082                    r = new StringBuilder(256);
11083                } else {
11084                    r.append(' ');
11085                }
11086                r.append(s.info.name);
11087            }
11088        }
11089        if (r != null) {
11090            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11091        }
11092
11093        N = pkg.receivers.size();
11094        r = null;
11095        for (i=0; i<N; i++) {
11096            PackageParser.Activity a = pkg.receivers.get(i);
11097            mReceivers.removeActivity(a, "receiver");
11098            if (DEBUG_REMOVE && chatty) {
11099                if (r == null) {
11100                    r = new StringBuilder(256);
11101                } else {
11102                    r.append(' ');
11103                }
11104                r.append(a.info.name);
11105            }
11106        }
11107        if (r != null) {
11108            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11109        }
11110
11111        N = pkg.activities.size();
11112        r = null;
11113        for (i=0; i<N; i++) {
11114            PackageParser.Activity a = pkg.activities.get(i);
11115            mActivities.removeActivity(a, "activity");
11116            if (DEBUG_REMOVE && chatty) {
11117                if (r == null) {
11118                    r = new StringBuilder(256);
11119                } else {
11120                    r.append(' ');
11121                }
11122                r.append(a.info.name);
11123            }
11124        }
11125        if (r != null) {
11126            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11127        }
11128
11129        N = pkg.permissions.size();
11130        r = null;
11131        for (i=0; i<N; i++) {
11132            PackageParser.Permission p = pkg.permissions.get(i);
11133            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11134            if (bp == null) {
11135                bp = mSettings.mPermissionTrees.get(p.info.name);
11136            }
11137            if (bp != null && bp.perm == p) {
11138                bp.perm = null;
11139                if (DEBUG_REMOVE && chatty) {
11140                    if (r == null) {
11141                        r = new StringBuilder(256);
11142                    } else {
11143                        r.append(' ');
11144                    }
11145                    r.append(p.info.name);
11146                }
11147            }
11148            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11149                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11150                if (appOpPkgs != null) {
11151                    appOpPkgs.remove(pkg.packageName);
11152                }
11153            }
11154        }
11155        if (r != null) {
11156            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11157        }
11158
11159        N = pkg.requestedPermissions.size();
11160        r = null;
11161        for (i=0; i<N; i++) {
11162            String perm = pkg.requestedPermissions.get(i);
11163            BasePermission bp = mSettings.mPermissions.get(perm);
11164            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11165                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11166                if (appOpPkgs != null) {
11167                    appOpPkgs.remove(pkg.packageName);
11168                    if (appOpPkgs.isEmpty()) {
11169                        mAppOpPermissionPackages.remove(perm);
11170                    }
11171                }
11172            }
11173        }
11174        if (r != null) {
11175            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11176        }
11177
11178        N = pkg.instrumentation.size();
11179        r = null;
11180        for (i=0; i<N; i++) {
11181            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11182            mInstrumentation.remove(a.getComponentName());
11183            if (DEBUG_REMOVE && chatty) {
11184                if (r == null) {
11185                    r = new StringBuilder(256);
11186                } else {
11187                    r.append(' ');
11188                }
11189                r.append(a.info.name);
11190            }
11191        }
11192        if (r != null) {
11193            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11194        }
11195
11196        r = null;
11197        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11198            // Only system apps can hold shared libraries.
11199            if (pkg.libraryNames != null) {
11200                for (i = 0; i < pkg.libraryNames.size(); i++) {
11201                    String name = pkg.libraryNames.get(i);
11202                    if (removeSharedLibraryLPw(name, 0)) {
11203                        if (DEBUG_REMOVE && chatty) {
11204                            if (r == null) {
11205                                r = new StringBuilder(256);
11206                            } else {
11207                                r.append(' ');
11208                            }
11209                            r.append(name);
11210                        }
11211                    }
11212                }
11213            }
11214        }
11215
11216        r = null;
11217
11218        // Any package can hold static shared libraries.
11219        if (pkg.staticSharedLibName != null) {
11220            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11221                if (DEBUG_REMOVE && chatty) {
11222                    if (r == null) {
11223                        r = new StringBuilder(256);
11224                    } else {
11225                        r.append(' ');
11226                    }
11227                    r.append(pkg.staticSharedLibName);
11228                }
11229            }
11230        }
11231
11232        if (r != null) {
11233            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11234        }
11235    }
11236
11237    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11238        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11239            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11240                return true;
11241            }
11242        }
11243        return false;
11244    }
11245
11246    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11247    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11248    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11249
11250    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11251        // Update the parent permissions
11252        updatePermissionsLPw(pkg.packageName, pkg, flags);
11253        // Update the child permissions
11254        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11255        for (int i = 0; i < childCount; i++) {
11256            PackageParser.Package childPkg = pkg.childPackages.get(i);
11257            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11258        }
11259    }
11260
11261    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11262            int flags) {
11263        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11264        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11265    }
11266
11267    private void updatePermissionsLPw(String changingPkg,
11268            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11269        // Make sure there are no dangling permission trees.
11270        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11271        while (it.hasNext()) {
11272            final BasePermission bp = it.next();
11273            if (bp.packageSetting == null) {
11274                // We may not yet have parsed the package, so just see if
11275                // we still know about its settings.
11276                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11277            }
11278            if (bp.packageSetting == null) {
11279                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11280                        + " from package " + bp.sourcePackage);
11281                it.remove();
11282            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11283                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11284                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11285                            + " from package " + bp.sourcePackage);
11286                    flags |= UPDATE_PERMISSIONS_ALL;
11287                    it.remove();
11288                }
11289            }
11290        }
11291
11292        // Make sure all dynamic permissions have been assigned to a package,
11293        // and make sure there are no dangling permissions.
11294        it = mSettings.mPermissions.values().iterator();
11295        while (it.hasNext()) {
11296            final BasePermission bp = it.next();
11297            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11298                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11299                        + bp.name + " pkg=" + bp.sourcePackage
11300                        + " info=" + bp.pendingInfo);
11301                if (bp.packageSetting == null && bp.pendingInfo != null) {
11302                    final BasePermission tree = findPermissionTreeLP(bp.name);
11303                    if (tree != null && tree.perm != null) {
11304                        bp.packageSetting = tree.packageSetting;
11305                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11306                                new PermissionInfo(bp.pendingInfo));
11307                        bp.perm.info.packageName = tree.perm.info.packageName;
11308                        bp.perm.info.name = bp.name;
11309                        bp.uid = tree.uid;
11310                    }
11311                }
11312            }
11313            if (bp.packageSetting == null) {
11314                // We may not yet have parsed the package, so just see if
11315                // we still know about its settings.
11316                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11317            }
11318            if (bp.packageSetting == null) {
11319                Slog.w(TAG, "Removing dangling permission: " + bp.name
11320                        + " from package " + bp.sourcePackage);
11321                it.remove();
11322            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11323                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11324                    Slog.i(TAG, "Removing old permission: " + bp.name
11325                            + " from package " + bp.sourcePackage);
11326                    flags |= UPDATE_PERMISSIONS_ALL;
11327                    it.remove();
11328                }
11329            }
11330        }
11331
11332        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11333        // Now update the permissions for all packages, in particular
11334        // replace the granted permissions of the system packages.
11335        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11336            for (PackageParser.Package pkg : mPackages.values()) {
11337                if (pkg != pkgInfo) {
11338                    // Only replace for packages on requested volume
11339                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11340                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11341                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11342                    grantPermissionsLPw(pkg, replace, changingPkg);
11343                }
11344            }
11345        }
11346
11347        if (pkgInfo != null) {
11348            // Only replace for packages on requested volume
11349            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11350            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11351                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11352            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11353        }
11354        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11355    }
11356
11357    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11358            String packageOfInterest) {
11359        // IMPORTANT: There are two types of permissions: install and runtime.
11360        // Install time permissions are granted when the app is installed to
11361        // all device users and users added in the future. Runtime permissions
11362        // are granted at runtime explicitly to specific users. Normal and signature
11363        // protected permissions are install time permissions. Dangerous permissions
11364        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11365        // otherwise they are runtime permissions. This function does not manage
11366        // runtime permissions except for the case an app targeting Lollipop MR1
11367        // being upgraded to target a newer SDK, in which case dangerous permissions
11368        // are transformed from install time to runtime ones.
11369
11370        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11371        if (ps == null) {
11372            return;
11373        }
11374
11375        PermissionsState permissionsState = ps.getPermissionsState();
11376        PermissionsState origPermissions = permissionsState;
11377
11378        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11379
11380        boolean runtimePermissionsRevoked = false;
11381        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11382
11383        boolean changedInstallPermission = false;
11384
11385        if (replace) {
11386            ps.installPermissionsFixed = false;
11387            if (!ps.isSharedUser()) {
11388                origPermissions = new PermissionsState(permissionsState);
11389                permissionsState.reset();
11390            } else {
11391                // We need to know only about runtime permission changes since the
11392                // calling code always writes the install permissions state but
11393                // the runtime ones are written only if changed. The only cases of
11394                // changed runtime permissions here are promotion of an install to
11395                // runtime and revocation of a runtime from a shared user.
11396                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11397                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11398                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11399                    runtimePermissionsRevoked = true;
11400                }
11401            }
11402        }
11403
11404        permissionsState.setGlobalGids(mGlobalGids);
11405
11406        final int N = pkg.requestedPermissions.size();
11407        for (int i=0; i<N; i++) {
11408            final String name = pkg.requestedPermissions.get(i);
11409            final BasePermission bp = mSettings.mPermissions.get(name);
11410
11411            if (DEBUG_INSTALL) {
11412                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11413            }
11414
11415            if (bp == null || bp.packageSetting == null) {
11416                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11417                    Slog.w(TAG, "Unknown permission " + name
11418                            + " in package " + pkg.packageName);
11419                }
11420                continue;
11421            }
11422
11423
11424            // Limit ephemeral apps to ephemeral allowed permissions.
11425            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11426                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11427                        + pkg.packageName);
11428                continue;
11429            }
11430
11431            final String perm = bp.name;
11432            boolean allowedSig = false;
11433            int grant = GRANT_DENIED;
11434
11435            // Keep track of app op permissions.
11436            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11437                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11438                if (pkgs == null) {
11439                    pkgs = new ArraySet<>();
11440                    mAppOpPermissionPackages.put(bp.name, pkgs);
11441                }
11442                pkgs.add(pkg.packageName);
11443            }
11444
11445            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11446            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11447                    >= Build.VERSION_CODES.M;
11448            switch (level) {
11449                case PermissionInfo.PROTECTION_NORMAL: {
11450                    // For all apps normal permissions are install time ones.
11451                    grant = GRANT_INSTALL;
11452                } break;
11453
11454                case PermissionInfo.PROTECTION_DANGEROUS: {
11455                    // If a permission review is required for legacy apps we represent
11456                    // their permissions as always granted runtime ones since we need
11457                    // to keep the review required permission flag per user while an
11458                    // install permission's state is shared across all users.
11459                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11460                        // For legacy apps dangerous permissions are install time ones.
11461                        grant = GRANT_INSTALL;
11462                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11463                        // For legacy apps that became modern, install becomes runtime.
11464                        grant = GRANT_UPGRADE;
11465                    } else if (mPromoteSystemApps
11466                            && isSystemApp(ps)
11467                            && mExistingSystemPackages.contains(ps.name)) {
11468                        // For legacy system apps, install becomes runtime.
11469                        // We cannot check hasInstallPermission() for system apps since those
11470                        // permissions were granted implicitly and not persisted pre-M.
11471                        grant = GRANT_UPGRADE;
11472                    } else {
11473                        // For modern apps keep runtime permissions unchanged.
11474                        grant = GRANT_RUNTIME;
11475                    }
11476                } break;
11477
11478                case PermissionInfo.PROTECTION_SIGNATURE: {
11479                    // For all apps signature permissions are install time ones.
11480                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11481                    if (allowedSig) {
11482                        grant = GRANT_INSTALL;
11483                    }
11484                } break;
11485            }
11486
11487            if (DEBUG_INSTALL) {
11488                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11489            }
11490
11491            if (grant != GRANT_DENIED) {
11492                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11493                    // If this is an existing, non-system package, then
11494                    // we can't add any new permissions to it.
11495                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11496                        // Except...  if this is a permission that was added
11497                        // to the platform (note: need to only do this when
11498                        // updating the platform).
11499                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11500                            grant = GRANT_DENIED;
11501                        }
11502                    }
11503                }
11504
11505                switch (grant) {
11506                    case GRANT_INSTALL: {
11507                        // Revoke this as runtime permission to handle the case of
11508                        // a runtime permission being downgraded to an install one.
11509                        // Also in permission review mode we keep dangerous permissions
11510                        // for legacy apps
11511                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11512                            if (origPermissions.getRuntimePermissionState(
11513                                    bp.name, userId) != null) {
11514                                // Revoke the runtime permission and clear the flags.
11515                                origPermissions.revokeRuntimePermission(bp, userId);
11516                                origPermissions.updatePermissionFlags(bp, userId,
11517                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11518                                // If we revoked a permission permission, we have to write.
11519                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11520                                        changedRuntimePermissionUserIds, userId);
11521                            }
11522                        }
11523                        // Grant an install permission.
11524                        if (permissionsState.grantInstallPermission(bp) !=
11525                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11526                            changedInstallPermission = true;
11527                        }
11528                    } break;
11529
11530                    case GRANT_RUNTIME: {
11531                        // Grant previously granted runtime permissions.
11532                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11533                            PermissionState permissionState = origPermissions
11534                                    .getRuntimePermissionState(bp.name, userId);
11535                            int flags = permissionState != null
11536                                    ? permissionState.getFlags() : 0;
11537                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11538                                // Don't propagate the permission in a permission review mode if
11539                                // the former was revoked, i.e. marked to not propagate on upgrade.
11540                                // Note that in a permission review mode install permissions are
11541                                // represented as constantly granted runtime ones since we need to
11542                                // keep a per user state associated with the permission. Also the
11543                                // revoke on upgrade flag is no longer applicable and is reset.
11544                                final boolean revokeOnUpgrade = (flags & PackageManager
11545                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11546                                if (revokeOnUpgrade) {
11547                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11548                                    // Since we changed the flags, we have to write.
11549                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11550                                            changedRuntimePermissionUserIds, userId);
11551                                }
11552                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11553                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11554                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11555                                        // If we cannot put the permission as it was,
11556                                        // we have to write.
11557                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11558                                                changedRuntimePermissionUserIds, userId);
11559                                    }
11560                                }
11561
11562                                // If the app supports runtime permissions no need for a review.
11563                                if (mPermissionReviewRequired
11564                                        && appSupportsRuntimePermissions
11565                                        && (flags & PackageManager
11566                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11567                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11568                                    // Since we changed the flags, we have to write.
11569                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11570                                            changedRuntimePermissionUserIds, userId);
11571                                }
11572                            } else if (mPermissionReviewRequired
11573                                    && !appSupportsRuntimePermissions) {
11574                                // For legacy apps that need a permission review, every new
11575                                // runtime permission is granted but it is pending a review.
11576                                // We also need to review only platform defined runtime
11577                                // permissions as these are the only ones the platform knows
11578                                // how to disable the API to simulate revocation as legacy
11579                                // apps don't expect to run with revoked permissions.
11580                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11581                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11582                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11583                                        // We changed the flags, hence have to write.
11584                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11585                                                changedRuntimePermissionUserIds, userId);
11586                                    }
11587                                }
11588                                if (permissionsState.grantRuntimePermission(bp, userId)
11589                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11590                                    // We changed the permission, hence have to write.
11591                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11592                                            changedRuntimePermissionUserIds, userId);
11593                                }
11594                            }
11595                            // Propagate the permission flags.
11596                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11597                        }
11598                    } break;
11599
11600                    case GRANT_UPGRADE: {
11601                        // Grant runtime permissions for a previously held install permission.
11602                        PermissionState permissionState = origPermissions
11603                                .getInstallPermissionState(bp.name);
11604                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11605
11606                        if (origPermissions.revokeInstallPermission(bp)
11607                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11608                            // We will be transferring the permission flags, so clear them.
11609                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11610                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11611                            changedInstallPermission = true;
11612                        }
11613
11614                        // If the permission is not to be promoted to runtime we ignore it and
11615                        // also its other flags as they are not applicable to install permissions.
11616                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11617                            for (int userId : currentUserIds) {
11618                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11619                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11620                                    // Transfer the permission flags.
11621                                    permissionsState.updatePermissionFlags(bp, userId,
11622                                            flags, flags);
11623                                    // If we granted the permission, we have to write.
11624                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11625                                            changedRuntimePermissionUserIds, userId);
11626                                }
11627                            }
11628                        }
11629                    } break;
11630
11631                    default: {
11632                        if (packageOfInterest == null
11633                                || packageOfInterest.equals(pkg.packageName)) {
11634                            Slog.w(TAG, "Not granting permission " + perm
11635                                    + " to package " + pkg.packageName
11636                                    + " because it was previously installed without");
11637                        }
11638                    } break;
11639                }
11640            } else {
11641                if (permissionsState.revokeInstallPermission(bp) !=
11642                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11643                    // Also drop the permission flags.
11644                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11645                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11646                    changedInstallPermission = true;
11647                    Slog.i(TAG, "Un-granting permission " + perm
11648                            + " from package " + pkg.packageName
11649                            + " (protectionLevel=" + bp.protectionLevel
11650                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11651                            + ")");
11652                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11653                    // Don't print warning for app op permissions, since it is fine for them
11654                    // not to be granted, there is a UI for the user to decide.
11655                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11656                        Slog.w(TAG, "Not granting permission " + perm
11657                                + " to package " + pkg.packageName
11658                                + " (protectionLevel=" + bp.protectionLevel
11659                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11660                                + ")");
11661                    }
11662                }
11663            }
11664        }
11665
11666        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11667                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11668            // This is the first that we have heard about this package, so the
11669            // permissions we have now selected are fixed until explicitly
11670            // changed.
11671            ps.installPermissionsFixed = true;
11672        }
11673
11674        // Persist the runtime permissions state for users with changes. If permissions
11675        // were revoked because no app in the shared user declares them we have to
11676        // write synchronously to avoid losing runtime permissions state.
11677        for (int userId : changedRuntimePermissionUserIds) {
11678            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11679        }
11680    }
11681
11682    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11683        boolean allowed = false;
11684        final int NP = PackageParser.NEW_PERMISSIONS.length;
11685        for (int ip=0; ip<NP; ip++) {
11686            final PackageParser.NewPermissionInfo npi
11687                    = PackageParser.NEW_PERMISSIONS[ip];
11688            if (npi.name.equals(perm)
11689                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11690                allowed = true;
11691                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11692                        + pkg.packageName);
11693                break;
11694            }
11695        }
11696        return allowed;
11697    }
11698
11699    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11700            BasePermission bp, PermissionsState origPermissions) {
11701        boolean privilegedPermission = (bp.protectionLevel
11702                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11703        boolean privappPermissionsDisable =
11704                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11705        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11706        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11707        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11708                && !platformPackage && platformPermission) {
11709            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11710                    .getPrivAppPermissions(pkg.packageName);
11711            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11712            if (!whitelisted) {
11713                Slog.w(TAG, "Privileged permission " + perm + " for package "
11714                        + pkg.packageName + " - not in privapp-permissions whitelist");
11715                // Only report violations for apps on system image
11716                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11717                    if (mPrivappPermissionsViolations == null) {
11718                        mPrivappPermissionsViolations = new ArraySet<>();
11719                    }
11720                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11721                }
11722                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11723                    return false;
11724                }
11725            }
11726        }
11727        boolean allowed = (compareSignatures(
11728                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11729                        == PackageManager.SIGNATURE_MATCH)
11730                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11731                        == PackageManager.SIGNATURE_MATCH);
11732        if (!allowed && privilegedPermission) {
11733            if (isSystemApp(pkg)) {
11734                // For updated system applications, a system permission
11735                // is granted only if it had been defined by the original application.
11736                if (pkg.isUpdatedSystemApp()) {
11737                    final PackageSetting sysPs = mSettings
11738                            .getDisabledSystemPkgLPr(pkg.packageName);
11739                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11740                        // If the original was granted this permission, we take
11741                        // that grant decision as read and propagate it to the
11742                        // update.
11743                        if (sysPs.isPrivileged()) {
11744                            allowed = true;
11745                        }
11746                    } else {
11747                        // The system apk may have been updated with an older
11748                        // version of the one on the data partition, but which
11749                        // granted a new system permission that it didn't have
11750                        // before.  In this case we do want to allow the app to
11751                        // now get the new permission if the ancestral apk is
11752                        // privileged to get it.
11753                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11754                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11755                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11756                                    allowed = true;
11757                                    break;
11758                                }
11759                            }
11760                        }
11761                        // Also if a privileged parent package on the system image or any of
11762                        // its children requested a privileged permission, the updated child
11763                        // packages can also get the permission.
11764                        if (pkg.parentPackage != null) {
11765                            final PackageSetting disabledSysParentPs = mSettings
11766                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11767                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11768                                    && disabledSysParentPs.isPrivileged()) {
11769                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11770                                    allowed = true;
11771                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11772                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11773                                    for (int i = 0; i < count; i++) {
11774                                        PackageParser.Package disabledSysChildPkg =
11775                                                disabledSysParentPs.pkg.childPackages.get(i);
11776                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11777                                                perm)) {
11778                                            allowed = true;
11779                                            break;
11780                                        }
11781                                    }
11782                                }
11783                            }
11784                        }
11785                    }
11786                } else {
11787                    allowed = isPrivilegedApp(pkg);
11788                }
11789            }
11790        }
11791        if (!allowed) {
11792            if (!allowed && (bp.protectionLevel
11793                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11794                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11795                // If this was a previously normal/dangerous permission that got moved
11796                // to a system permission as part of the runtime permission redesign, then
11797                // we still want to blindly grant it to old apps.
11798                allowed = true;
11799            }
11800            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11801                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11802                // If this permission is to be granted to the system installer and
11803                // this app is an installer, then it gets the permission.
11804                allowed = true;
11805            }
11806            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11807                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11808                // If this permission is to be granted to the system verifier and
11809                // this app is a verifier, then it gets the permission.
11810                allowed = true;
11811            }
11812            if (!allowed && (bp.protectionLevel
11813                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11814                    && isSystemApp(pkg)) {
11815                // Any pre-installed system app is allowed to get this permission.
11816                allowed = true;
11817            }
11818            if (!allowed && (bp.protectionLevel
11819                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11820                // For development permissions, a development permission
11821                // is granted only if it was already granted.
11822                allowed = origPermissions.hasInstallPermission(perm);
11823            }
11824            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11825                    && pkg.packageName.equals(mSetupWizardPackage)) {
11826                // If this permission is to be granted to the system setup wizard and
11827                // this app is a setup wizard, then it gets the permission.
11828                allowed = true;
11829            }
11830        }
11831        return allowed;
11832    }
11833
11834    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11835        final int permCount = pkg.requestedPermissions.size();
11836        for (int j = 0; j < permCount; j++) {
11837            String requestedPermission = pkg.requestedPermissions.get(j);
11838            if (permission.equals(requestedPermission)) {
11839                return true;
11840            }
11841        }
11842        return false;
11843    }
11844
11845    final class ActivityIntentResolver
11846            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11847        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11848                boolean defaultOnly, int userId) {
11849            if (!sUserManager.exists(userId)) return null;
11850            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11851            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11852        }
11853
11854        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11855                int userId) {
11856            if (!sUserManager.exists(userId)) return null;
11857            mFlags = flags;
11858            return super.queryIntent(intent, resolvedType,
11859                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11860                    userId);
11861        }
11862
11863        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11864                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11865            if (!sUserManager.exists(userId)) return null;
11866            if (packageActivities == null) {
11867                return null;
11868            }
11869            mFlags = flags;
11870            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11871            final int N = packageActivities.size();
11872            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11873                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11874
11875            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11876            for (int i = 0; i < N; ++i) {
11877                intentFilters = packageActivities.get(i).intents;
11878                if (intentFilters != null && intentFilters.size() > 0) {
11879                    PackageParser.ActivityIntentInfo[] array =
11880                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11881                    intentFilters.toArray(array);
11882                    listCut.add(array);
11883                }
11884            }
11885            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11886        }
11887
11888        /**
11889         * Finds a privileged activity that matches the specified activity names.
11890         */
11891        private PackageParser.Activity findMatchingActivity(
11892                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11893            for (PackageParser.Activity sysActivity : activityList) {
11894                if (sysActivity.info.name.equals(activityInfo.name)) {
11895                    return sysActivity;
11896                }
11897                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11898                    return sysActivity;
11899                }
11900                if (sysActivity.info.targetActivity != null) {
11901                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11902                        return sysActivity;
11903                    }
11904                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11905                        return sysActivity;
11906                    }
11907                }
11908            }
11909            return null;
11910        }
11911
11912        public class IterGenerator<E> {
11913            public Iterator<E> generate(ActivityIntentInfo info) {
11914                return null;
11915            }
11916        }
11917
11918        public class ActionIterGenerator extends IterGenerator<String> {
11919            @Override
11920            public Iterator<String> generate(ActivityIntentInfo info) {
11921                return info.actionsIterator();
11922            }
11923        }
11924
11925        public class CategoriesIterGenerator extends IterGenerator<String> {
11926            @Override
11927            public Iterator<String> generate(ActivityIntentInfo info) {
11928                return info.categoriesIterator();
11929            }
11930        }
11931
11932        public class SchemesIterGenerator extends IterGenerator<String> {
11933            @Override
11934            public Iterator<String> generate(ActivityIntentInfo info) {
11935                return info.schemesIterator();
11936            }
11937        }
11938
11939        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11940            @Override
11941            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11942                return info.authoritiesIterator();
11943            }
11944        }
11945
11946        /**
11947         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11948         * MODIFIED. Do not pass in a list that should not be changed.
11949         */
11950        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11951                IterGenerator<T> generator, Iterator<T> searchIterator) {
11952            // loop through the set of actions; every one must be found in the intent filter
11953            while (searchIterator.hasNext()) {
11954                // we must have at least one filter in the list to consider a match
11955                if (intentList.size() == 0) {
11956                    break;
11957                }
11958
11959                final T searchAction = searchIterator.next();
11960
11961                // loop through the set of intent filters
11962                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11963                while (intentIter.hasNext()) {
11964                    final ActivityIntentInfo intentInfo = intentIter.next();
11965                    boolean selectionFound = false;
11966
11967                    // loop through the intent filter's selection criteria; at least one
11968                    // of them must match the searched criteria
11969                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11970                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11971                        final T intentSelection = intentSelectionIter.next();
11972                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11973                            selectionFound = true;
11974                            break;
11975                        }
11976                    }
11977
11978                    // the selection criteria wasn't found in this filter's set; this filter
11979                    // is not a potential match
11980                    if (!selectionFound) {
11981                        intentIter.remove();
11982                    }
11983                }
11984            }
11985        }
11986
11987        private boolean isProtectedAction(ActivityIntentInfo filter) {
11988            final Iterator<String> actionsIter = filter.actionsIterator();
11989            while (actionsIter != null && actionsIter.hasNext()) {
11990                final String filterAction = actionsIter.next();
11991                if (PROTECTED_ACTIONS.contains(filterAction)) {
11992                    return true;
11993                }
11994            }
11995            return false;
11996        }
11997
11998        /**
11999         * Adjusts the priority of the given intent filter according to policy.
12000         * <p>
12001         * <ul>
12002         * <li>The priority for non privileged applications is capped to '0'</li>
12003         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12004         * <li>The priority for unbundled updates to privileged applications is capped to the
12005         *      priority defined on the system partition</li>
12006         * </ul>
12007         * <p>
12008         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12009         * allowed to obtain any priority on any action.
12010         */
12011        private void adjustPriority(
12012                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12013            // nothing to do; priority is fine as-is
12014            if (intent.getPriority() <= 0) {
12015                return;
12016            }
12017
12018            final ActivityInfo activityInfo = intent.activity.info;
12019            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12020
12021            final boolean privilegedApp =
12022                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12023            if (!privilegedApp) {
12024                // non-privileged applications can never define a priority >0
12025                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
12026                        + " package: " + applicationInfo.packageName
12027                        + " activity: " + intent.activity.className
12028                        + " origPrio: " + intent.getPriority());
12029                intent.setPriority(0);
12030                return;
12031            }
12032
12033            if (systemActivities == null) {
12034                // the system package is not disabled; we're parsing the system partition
12035                if (isProtectedAction(intent)) {
12036                    if (mDeferProtectedFilters) {
12037                        // We can't deal with these just yet. No component should ever obtain a
12038                        // >0 priority for a protected actions, with ONE exception -- the setup
12039                        // wizard. The setup wizard, however, cannot be known until we're able to
12040                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12041                        // until all intent filters have been processed. Chicken, meet egg.
12042                        // Let the filter temporarily have a high priority and rectify the
12043                        // priorities after all system packages have been scanned.
12044                        mProtectedFilters.add(intent);
12045                        if (DEBUG_FILTERS) {
12046                            Slog.i(TAG, "Protected action; save for later;"
12047                                    + " package: " + applicationInfo.packageName
12048                                    + " activity: " + intent.activity.className
12049                                    + " origPrio: " + intent.getPriority());
12050                        }
12051                        return;
12052                    } else {
12053                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12054                            Slog.i(TAG, "No setup wizard;"
12055                                + " All protected intents capped to priority 0");
12056                        }
12057                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12058                            if (DEBUG_FILTERS) {
12059                                Slog.i(TAG, "Found setup wizard;"
12060                                    + " allow priority " + intent.getPriority() + ";"
12061                                    + " package: " + intent.activity.info.packageName
12062                                    + " activity: " + intent.activity.className
12063                                    + " priority: " + intent.getPriority());
12064                            }
12065                            // setup wizard gets whatever it wants
12066                            return;
12067                        }
12068                        Slog.w(TAG, "Protected action; cap priority to 0;"
12069                                + " package: " + intent.activity.info.packageName
12070                                + " activity: " + intent.activity.className
12071                                + " origPrio: " + intent.getPriority());
12072                        intent.setPriority(0);
12073                        return;
12074                    }
12075                }
12076                // privileged apps on the system image get whatever priority they request
12077                return;
12078            }
12079
12080            // privileged app unbundled update ... try to find the same activity
12081            final PackageParser.Activity foundActivity =
12082                    findMatchingActivity(systemActivities, activityInfo);
12083            if (foundActivity == null) {
12084                // this is a new activity; it cannot obtain >0 priority
12085                if (DEBUG_FILTERS) {
12086                    Slog.i(TAG, "New activity; cap priority to 0;"
12087                            + " package: " + applicationInfo.packageName
12088                            + " activity: " + intent.activity.className
12089                            + " origPrio: " + intent.getPriority());
12090                }
12091                intent.setPriority(0);
12092                return;
12093            }
12094
12095            // found activity, now check for filter equivalence
12096
12097            // a shallow copy is enough; we modify the list, not its contents
12098            final List<ActivityIntentInfo> intentListCopy =
12099                    new ArrayList<>(foundActivity.intents);
12100            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12101
12102            // find matching action subsets
12103            final Iterator<String> actionsIterator = intent.actionsIterator();
12104            if (actionsIterator != null) {
12105                getIntentListSubset(
12106                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12107                if (intentListCopy.size() == 0) {
12108                    // no more intents to match; we're not equivalent
12109                    if (DEBUG_FILTERS) {
12110                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12111                                + " package: " + applicationInfo.packageName
12112                                + " activity: " + intent.activity.className
12113                                + " origPrio: " + intent.getPriority());
12114                    }
12115                    intent.setPriority(0);
12116                    return;
12117                }
12118            }
12119
12120            // find matching category subsets
12121            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12122            if (categoriesIterator != null) {
12123                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12124                        categoriesIterator);
12125                if (intentListCopy.size() == 0) {
12126                    // no more intents to match; we're not equivalent
12127                    if (DEBUG_FILTERS) {
12128                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12129                                + " package: " + applicationInfo.packageName
12130                                + " activity: " + intent.activity.className
12131                                + " origPrio: " + intent.getPriority());
12132                    }
12133                    intent.setPriority(0);
12134                    return;
12135                }
12136            }
12137
12138            // find matching schemes subsets
12139            final Iterator<String> schemesIterator = intent.schemesIterator();
12140            if (schemesIterator != null) {
12141                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12142                        schemesIterator);
12143                if (intentListCopy.size() == 0) {
12144                    // no more intents to match; we're not equivalent
12145                    if (DEBUG_FILTERS) {
12146                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12147                                + " package: " + applicationInfo.packageName
12148                                + " activity: " + intent.activity.className
12149                                + " origPrio: " + intent.getPriority());
12150                    }
12151                    intent.setPriority(0);
12152                    return;
12153                }
12154            }
12155
12156            // find matching authorities subsets
12157            final Iterator<IntentFilter.AuthorityEntry>
12158                    authoritiesIterator = intent.authoritiesIterator();
12159            if (authoritiesIterator != null) {
12160                getIntentListSubset(intentListCopy,
12161                        new AuthoritiesIterGenerator(),
12162                        authoritiesIterator);
12163                if (intentListCopy.size() == 0) {
12164                    // no more intents to match; we're not equivalent
12165                    if (DEBUG_FILTERS) {
12166                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12167                                + " package: " + applicationInfo.packageName
12168                                + " activity: " + intent.activity.className
12169                                + " origPrio: " + intent.getPriority());
12170                    }
12171                    intent.setPriority(0);
12172                    return;
12173                }
12174            }
12175
12176            // we found matching filter(s); app gets the max priority of all intents
12177            int cappedPriority = 0;
12178            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12179                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12180            }
12181            if (intent.getPriority() > cappedPriority) {
12182                if (DEBUG_FILTERS) {
12183                    Slog.i(TAG, "Found matching filter(s);"
12184                            + " cap priority to " + cappedPriority + ";"
12185                            + " package: " + applicationInfo.packageName
12186                            + " activity: " + intent.activity.className
12187                            + " origPrio: " + intent.getPriority());
12188                }
12189                intent.setPriority(cappedPriority);
12190                return;
12191            }
12192            // all this for nothing; the requested priority was <= what was on the system
12193        }
12194
12195        public final void addActivity(PackageParser.Activity a, String type) {
12196            mActivities.put(a.getComponentName(), a);
12197            if (DEBUG_SHOW_INFO)
12198                Log.v(
12199                TAG, "  " + type + " " +
12200                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12201            if (DEBUG_SHOW_INFO)
12202                Log.v(TAG, "    Class=" + a.info.name);
12203            final int NI = a.intents.size();
12204            for (int j=0; j<NI; j++) {
12205                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12206                if ("activity".equals(type)) {
12207                    final PackageSetting ps =
12208                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12209                    final List<PackageParser.Activity> systemActivities =
12210                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12211                    adjustPriority(systemActivities, intent);
12212                }
12213                if (DEBUG_SHOW_INFO) {
12214                    Log.v(TAG, "    IntentFilter:");
12215                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12216                }
12217                if (!intent.debugCheck()) {
12218                    Log.w(TAG, "==> For Activity " + a.info.name);
12219                }
12220                addFilter(intent);
12221            }
12222        }
12223
12224        public final void removeActivity(PackageParser.Activity a, String type) {
12225            mActivities.remove(a.getComponentName());
12226            if (DEBUG_SHOW_INFO) {
12227                Log.v(TAG, "  " + type + " "
12228                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12229                                : a.info.name) + ":");
12230                Log.v(TAG, "    Class=" + a.info.name);
12231            }
12232            final int NI = a.intents.size();
12233            for (int j=0; j<NI; j++) {
12234                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12235                if (DEBUG_SHOW_INFO) {
12236                    Log.v(TAG, "    IntentFilter:");
12237                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12238                }
12239                removeFilter(intent);
12240            }
12241        }
12242
12243        @Override
12244        protected boolean allowFilterResult(
12245                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12246            ActivityInfo filterAi = filter.activity.info;
12247            for (int i=dest.size()-1; i>=0; i--) {
12248                ActivityInfo destAi = dest.get(i).activityInfo;
12249                if (destAi.name == filterAi.name
12250                        && destAi.packageName == filterAi.packageName) {
12251                    return false;
12252                }
12253            }
12254            return true;
12255        }
12256
12257        @Override
12258        protected ActivityIntentInfo[] newArray(int size) {
12259            return new ActivityIntentInfo[size];
12260        }
12261
12262        @Override
12263        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12264            if (!sUserManager.exists(userId)) return true;
12265            PackageParser.Package p = filter.activity.owner;
12266            if (p != null) {
12267                PackageSetting ps = (PackageSetting)p.mExtras;
12268                if (ps != null) {
12269                    // System apps are never considered stopped for purposes of
12270                    // filtering, because there may be no way for the user to
12271                    // actually re-launch them.
12272                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12273                            && ps.getStopped(userId);
12274                }
12275            }
12276            return false;
12277        }
12278
12279        @Override
12280        protected boolean isPackageForFilter(String packageName,
12281                PackageParser.ActivityIntentInfo info) {
12282            return packageName.equals(info.activity.owner.packageName);
12283        }
12284
12285        @Override
12286        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12287                int match, int userId) {
12288            if (!sUserManager.exists(userId)) return null;
12289            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12290                return null;
12291            }
12292            final PackageParser.Activity activity = info.activity;
12293            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12294            if (ps == null) {
12295                return null;
12296            }
12297            final PackageUserState userState = ps.readUserState(userId);
12298            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12299                    userState, userId);
12300            if (ai == null) {
12301                return null;
12302            }
12303            final boolean matchVisibleToInstantApp =
12304                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12305            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12306            // throw out filters that aren't visible to ephemeral apps
12307            if (matchVisibleToInstantApp
12308                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12309                return null;
12310            }
12311            // throw out ephemeral filters if we're not explicitly requesting them
12312            if (!isInstantApp && userState.instantApp) {
12313                return null;
12314            }
12315            final ResolveInfo res = new ResolveInfo();
12316            res.activityInfo = ai;
12317            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12318                res.filter = info;
12319            }
12320            if (info != null) {
12321                res.handleAllWebDataURI = info.handleAllWebDataURI();
12322            }
12323            res.priority = info.getPriority();
12324            res.preferredOrder = activity.owner.mPreferredOrder;
12325            //System.out.println("Result: " + res.activityInfo.className +
12326            //                   " = " + res.priority);
12327            res.match = match;
12328            res.isDefault = info.hasDefault;
12329            res.labelRes = info.labelRes;
12330            res.nonLocalizedLabel = info.nonLocalizedLabel;
12331            if (userNeedsBadging(userId)) {
12332                res.noResourceId = true;
12333            } else {
12334                res.icon = info.icon;
12335            }
12336            res.iconResourceId = info.icon;
12337            res.system = res.activityInfo.applicationInfo.isSystemApp();
12338            res.instantAppAvailable = userState.instantApp;
12339            return res;
12340        }
12341
12342        @Override
12343        protected void sortResults(List<ResolveInfo> results) {
12344            Collections.sort(results, mResolvePrioritySorter);
12345        }
12346
12347        @Override
12348        protected void dumpFilter(PrintWriter out, String prefix,
12349                PackageParser.ActivityIntentInfo filter) {
12350            out.print(prefix); out.print(
12351                    Integer.toHexString(System.identityHashCode(filter.activity)));
12352                    out.print(' ');
12353                    filter.activity.printComponentShortName(out);
12354                    out.print(" filter ");
12355                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12356        }
12357
12358        @Override
12359        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12360            return filter.activity;
12361        }
12362
12363        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12364            PackageParser.Activity activity = (PackageParser.Activity)label;
12365            out.print(prefix); out.print(
12366                    Integer.toHexString(System.identityHashCode(activity)));
12367                    out.print(' ');
12368                    activity.printComponentShortName(out);
12369            if (count > 1) {
12370                out.print(" ("); out.print(count); out.print(" filters)");
12371            }
12372            out.println();
12373        }
12374
12375        // Keys are String (activity class name), values are Activity.
12376        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12377                = new ArrayMap<ComponentName, PackageParser.Activity>();
12378        private int mFlags;
12379    }
12380
12381    private final class ServiceIntentResolver
12382            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12383        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12384                boolean defaultOnly, int userId) {
12385            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12386            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12387        }
12388
12389        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12390                int userId) {
12391            if (!sUserManager.exists(userId)) return null;
12392            mFlags = flags;
12393            return super.queryIntent(intent, resolvedType,
12394                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12395                    userId);
12396        }
12397
12398        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12399                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12400            if (!sUserManager.exists(userId)) return null;
12401            if (packageServices == null) {
12402                return null;
12403            }
12404            mFlags = flags;
12405            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12406            final int N = packageServices.size();
12407            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12408                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12409
12410            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12411            for (int i = 0; i < N; ++i) {
12412                intentFilters = packageServices.get(i).intents;
12413                if (intentFilters != null && intentFilters.size() > 0) {
12414                    PackageParser.ServiceIntentInfo[] array =
12415                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12416                    intentFilters.toArray(array);
12417                    listCut.add(array);
12418                }
12419            }
12420            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12421        }
12422
12423        public final void addService(PackageParser.Service s) {
12424            mServices.put(s.getComponentName(), s);
12425            if (DEBUG_SHOW_INFO) {
12426                Log.v(TAG, "  "
12427                        + (s.info.nonLocalizedLabel != null
12428                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12429                Log.v(TAG, "    Class=" + s.info.name);
12430            }
12431            final int NI = s.intents.size();
12432            int j;
12433            for (j=0; j<NI; j++) {
12434                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12435                if (DEBUG_SHOW_INFO) {
12436                    Log.v(TAG, "    IntentFilter:");
12437                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12438                }
12439                if (!intent.debugCheck()) {
12440                    Log.w(TAG, "==> For Service " + s.info.name);
12441                }
12442                addFilter(intent);
12443            }
12444        }
12445
12446        public final void removeService(PackageParser.Service s) {
12447            mServices.remove(s.getComponentName());
12448            if (DEBUG_SHOW_INFO) {
12449                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12450                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12451                Log.v(TAG, "    Class=" + s.info.name);
12452            }
12453            final int NI = s.intents.size();
12454            int j;
12455            for (j=0; j<NI; j++) {
12456                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12457                if (DEBUG_SHOW_INFO) {
12458                    Log.v(TAG, "    IntentFilter:");
12459                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12460                }
12461                removeFilter(intent);
12462            }
12463        }
12464
12465        @Override
12466        protected boolean allowFilterResult(
12467                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12468            ServiceInfo filterSi = filter.service.info;
12469            for (int i=dest.size()-1; i>=0; i--) {
12470                ServiceInfo destAi = dest.get(i).serviceInfo;
12471                if (destAi.name == filterSi.name
12472                        && destAi.packageName == filterSi.packageName) {
12473                    return false;
12474                }
12475            }
12476            return true;
12477        }
12478
12479        @Override
12480        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12481            return new PackageParser.ServiceIntentInfo[size];
12482        }
12483
12484        @Override
12485        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12486            if (!sUserManager.exists(userId)) return true;
12487            PackageParser.Package p = filter.service.owner;
12488            if (p != null) {
12489                PackageSetting ps = (PackageSetting)p.mExtras;
12490                if (ps != null) {
12491                    // System apps are never considered stopped for purposes of
12492                    // filtering, because there may be no way for the user to
12493                    // actually re-launch them.
12494                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12495                            && ps.getStopped(userId);
12496                }
12497            }
12498            return false;
12499        }
12500
12501        @Override
12502        protected boolean isPackageForFilter(String packageName,
12503                PackageParser.ServiceIntentInfo info) {
12504            return packageName.equals(info.service.owner.packageName);
12505        }
12506
12507        @Override
12508        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12509                int match, int userId) {
12510            if (!sUserManager.exists(userId)) return null;
12511            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12512            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12513                return null;
12514            }
12515            final PackageParser.Service service = info.service;
12516            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12517            if (ps == null) {
12518                return null;
12519            }
12520            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12521                    ps.readUserState(userId), userId);
12522            if (si == null) {
12523                return null;
12524            }
12525            final ResolveInfo res = new ResolveInfo();
12526            res.serviceInfo = si;
12527            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12528                res.filter = filter;
12529            }
12530            res.priority = info.getPriority();
12531            res.preferredOrder = service.owner.mPreferredOrder;
12532            res.match = match;
12533            res.isDefault = info.hasDefault;
12534            res.labelRes = info.labelRes;
12535            res.nonLocalizedLabel = info.nonLocalizedLabel;
12536            res.icon = info.icon;
12537            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12538            return res;
12539        }
12540
12541        @Override
12542        protected void sortResults(List<ResolveInfo> results) {
12543            Collections.sort(results, mResolvePrioritySorter);
12544        }
12545
12546        @Override
12547        protected void dumpFilter(PrintWriter out, String prefix,
12548                PackageParser.ServiceIntentInfo filter) {
12549            out.print(prefix); out.print(
12550                    Integer.toHexString(System.identityHashCode(filter.service)));
12551                    out.print(' ');
12552                    filter.service.printComponentShortName(out);
12553                    out.print(" filter ");
12554                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12555        }
12556
12557        @Override
12558        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12559            return filter.service;
12560        }
12561
12562        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12563            PackageParser.Service service = (PackageParser.Service)label;
12564            out.print(prefix); out.print(
12565                    Integer.toHexString(System.identityHashCode(service)));
12566                    out.print(' ');
12567                    service.printComponentShortName(out);
12568            if (count > 1) {
12569                out.print(" ("); out.print(count); out.print(" filters)");
12570            }
12571            out.println();
12572        }
12573
12574//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12575//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12576//            final List<ResolveInfo> retList = Lists.newArrayList();
12577//            while (i.hasNext()) {
12578//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12579//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12580//                    retList.add(resolveInfo);
12581//                }
12582//            }
12583//            return retList;
12584//        }
12585
12586        // Keys are String (activity class name), values are Activity.
12587        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12588                = new ArrayMap<ComponentName, PackageParser.Service>();
12589        private int mFlags;
12590    }
12591
12592    private final class ProviderIntentResolver
12593            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12594        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12595                boolean defaultOnly, int userId) {
12596            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12597            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12598        }
12599
12600        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12601                int userId) {
12602            if (!sUserManager.exists(userId))
12603                return null;
12604            mFlags = flags;
12605            return super.queryIntent(intent, resolvedType,
12606                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12607                    userId);
12608        }
12609
12610        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12611                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12612            if (!sUserManager.exists(userId))
12613                return null;
12614            if (packageProviders == null) {
12615                return null;
12616            }
12617            mFlags = flags;
12618            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12619            final int N = packageProviders.size();
12620            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12621                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12622
12623            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12624            for (int i = 0; i < N; ++i) {
12625                intentFilters = packageProviders.get(i).intents;
12626                if (intentFilters != null && intentFilters.size() > 0) {
12627                    PackageParser.ProviderIntentInfo[] array =
12628                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12629                    intentFilters.toArray(array);
12630                    listCut.add(array);
12631                }
12632            }
12633            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12634        }
12635
12636        public final void addProvider(PackageParser.Provider p) {
12637            if (mProviders.containsKey(p.getComponentName())) {
12638                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12639                return;
12640            }
12641
12642            mProviders.put(p.getComponentName(), p);
12643            if (DEBUG_SHOW_INFO) {
12644                Log.v(TAG, "  "
12645                        + (p.info.nonLocalizedLabel != null
12646                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12647                Log.v(TAG, "    Class=" + p.info.name);
12648            }
12649            final int NI = p.intents.size();
12650            int j;
12651            for (j = 0; j < NI; j++) {
12652                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12653                if (DEBUG_SHOW_INFO) {
12654                    Log.v(TAG, "    IntentFilter:");
12655                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12656                }
12657                if (!intent.debugCheck()) {
12658                    Log.w(TAG, "==> For Provider " + p.info.name);
12659                }
12660                addFilter(intent);
12661            }
12662        }
12663
12664        public final void removeProvider(PackageParser.Provider p) {
12665            mProviders.remove(p.getComponentName());
12666            if (DEBUG_SHOW_INFO) {
12667                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12668                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12669                Log.v(TAG, "    Class=" + p.info.name);
12670            }
12671            final int NI = p.intents.size();
12672            int j;
12673            for (j = 0; j < NI; j++) {
12674                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12675                if (DEBUG_SHOW_INFO) {
12676                    Log.v(TAG, "    IntentFilter:");
12677                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12678                }
12679                removeFilter(intent);
12680            }
12681        }
12682
12683        @Override
12684        protected boolean allowFilterResult(
12685                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12686            ProviderInfo filterPi = filter.provider.info;
12687            for (int i = dest.size() - 1; i >= 0; i--) {
12688                ProviderInfo destPi = dest.get(i).providerInfo;
12689                if (destPi.name == filterPi.name
12690                        && destPi.packageName == filterPi.packageName) {
12691                    return false;
12692                }
12693            }
12694            return true;
12695        }
12696
12697        @Override
12698        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12699            return new PackageParser.ProviderIntentInfo[size];
12700        }
12701
12702        @Override
12703        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12704            if (!sUserManager.exists(userId))
12705                return true;
12706            PackageParser.Package p = filter.provider.owner;
12707            if (p != null) {
12708                PackageSetting ps = (PackageSetting) p.mExtras;
12709                if (ps != null) {
12710                    // System apps are never considered stopped for purposes of
12711                    // filtering, because there may be no way for the user to
12712                    // actually re-launch them.
12713                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12714                            && ps.getStopped(userId);
12715                }
12716            }
12717            return false;
12718        }
12719
12720        @Override
12721        protected boolean isPackageForFilter(String packageName,
12722                PackageParser.ProviderIntentInfo info) {
12723            return packageName.equals(info.provider.owner.packageName);
12724        }
12725
12726        @Override
12727        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12728                int match, int userId) {
12729            if (!sUserManager.exists(userId))
12730                return null;
12731            final PackageParser.ProviderIntentInfo info = filter;
12732            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12733                return null;
12734            }
12735            final PackageParser.Provider provider = info.provider;
12736            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12737            if (ps == null) {
12738                return null;
12739            }
12740            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12741                    ps.readUserState(userId), userId);
12742            if (pi == null) {
12743                return null;
12744            }
12745            final ResolveInfo res = new ResolveInfo();
12746            res.providerInfo = pi;
12747            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12748                res.filter = filter;
12749            }
12750            res.priority = info.getPriority();
12751            res.preferredOrder = provider.owner.mPreferredOrder;
12752            res.match = match;
12753            res.isDefault = info.hasDefault;
12754            res.labelRes = info.labelRes;
12755            res.nonLocalizedLabel = info.nonLocalizedLabel;
12756            res.icon = info.icon;
12757            res.system = res.providerInfo.applicationInfo.isSystemApp();
12758            return res;
12759        }
12760
12761        @Override
12762        protected void sortResults(List<ResolveInfo> results) {
12763            Collections.sort(results, mResolvePrioritySorter);
12764        }
12765
12766        @Override
12767        protected void dumpFilter(PrintWriter out, String prefix,
12768                PackageParser.ProviderIntentInfo filter) {
12769            out.print(prefix);
12770            out.print(
12771                    Integer.toHexString(System.identityHashCode(filter.provider)));
12772            out.print(' ');
12773            filter.provider.printComponentShortName(out);
12774            out.print(" filter ");
12775            out.println(Integer.toHexString(System.identityHashCode(filter)));
12776        }
12777
12778        @Override
12779        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12780            return filter.provider;
12781        }
12782
12783        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12784            PackageParser.Provider provider = (PackageParser.Provider)label;
12785            out.print(prefix); out.print(
12786                    Integer.toHexString(System.identityHashCode(provider)));
12787                    out.print(' ');
12788                    provider.printComponentShortName(out);
12789            if (count > 1) {
12790                out.print(" ("); out.print(count); out.print(" filters)");
12791            }
12792            out.println();
12793        }
12794
12795        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12796                = new ArrayMap<ComponentName, PackageParser.Provider>();
12797        private int mFlags;
12798    }
12799
12800    static final class EphemeralIntentResolver
12801            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12802        /**
12803         * The result that has the highest defined order. Ordering applies on a
12804         * per-package basis. Mapping is from package name to Pair of order and
12805         * EphemeralResolveInfo.
12806         * <p>
12807         * NOTE: This is implemented as a field variable for convenience and efficiency.
12808         * By having a field variable, we're able to track filter ordering as soon as
12809         * a non-zero order is defined. Otherwise, multiple loops across the result set
12810         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12811         * this needs to be contained entirely within {@link #filterResults()}.
12812         */
12813        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
12814
12815        @Override
12816        protected AuxiliaryResolveInfo[] newArray(int size) {
12817            return new AuxiliaryResolveInfo[size];
12818        }
12819
12820        @Override
12821        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12822            return true;
12823        }
12824
12825        @Override
12826        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12827                int userId) {
12828            if (!sUserManager.exists(userId)) {
12829                return null;
12830            }
12831            final String packageName = responseObj.resolveInfo.getPackageName();
12832            final Integer order = responseObj.getOrder();
12833            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
12834                    mOrderResult.get(packageName);
12835            // ordering is enabled and this item's order isn't high enough
12836            if (lastOrderResult != null && lastOrderResult.first >= order) {
12837                return null;
12838            }
12839            final EphemeralResolveInfo res = responseObj.resolveInfo;
12840            if (order > 0) {
12841                // non-zero order, enable ordering
12842                mOrderResult.put(packageName, new Pair<>(order, res));
12843            }
12844            return responseObj;
12845        }
12846
12847        @Override
12848        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12849            // only do work if ordering is enabled [most of the time it won't be]
12850            if (mOrderResult.size() == 0) {
12851                return;
12852            }
12853            int resultSize = results.size();
12854            for (int i = 0; i < resultSize; i++) {
12855                final EphemeralResolveInfo info = results.get(i).resolveInfo;
12856                final String packageName = info.getPackageName();
12857                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
12858                if (savedInfo == null) {
12859                    // package doesn't having ordering
12860                    continue;
12861                }
12862                if (savedInfo.second == info) {
12863                    // circled back to the highest ordered item; remove from order list
12864                    mOrderResult.remove(savedInfo);
12865                    if (mOrderResult.size() == 0) {
12866                        // no more ordered items
12867                        break;
12868                    }
12869                    continue;
12870                }
12871                // item has a worse order, remove it from the result list
12872                results.remove(i);
12873                resultSize--;
12874                i--;
12875            }
12876        }
12877    }
12878
12879    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12880            new Comparator<ResolveInfo>() {
12881        public int compare(ResolveInfo r1, ResolveInfo r2) {
12882            int v1 = r1.priority;
12883            int v2 = r2.priority;
12884            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12885            if (v1 != v2) {
12886                return (v1 > v2) ? -1 : 1;
12887            }
12888            v1 = r1.preferredOrder;
12889            v2 = r2.preferredOrder;
12890            if (v1 != v2) {
12891                return (v1 > v2) ? -1 : 1;
12892            }
12893            if (r1.isDefault != r2.isDefault) {
12894                return r1.isDefault ? -1 : 1;
12895            }
12896            v1 = r1.match;
12897            v2 = r2.match;
12898            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12899            if (v1 != v2) {
12900                return (v1 > v2) ? -1 : 1;
12901            }
12902            if (r1.system != r2.system) {
12903                return r1.system ? -1 : 1;
12904            }
12905            if (r1.activityInfo != null) {
12906                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12907            }
12908            if (r1.serviceInfo != null) {
12909                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12910            }
12911            if (r1.providerInfo != null) {
12912                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12913            }
12914            return 0;
12915        }
12916    };
12917
12918    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12919            new Comparator<ProviderInfo>() {
12920        public int compare(ProviderInfo p1, ProviderInfo p2) {
12921            final int v1 = p1.initOrder;
12922            final int v2 = p2.initOrder;
12923            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12924        }
12925    };
12926
12927    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12928            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12929            final int[] userIds) {
12930        mHandler.post(new Runnable() {
12931            @Override
12932            public void run() {
12933                try {
12934                    final IActivityManager am = ActivityManager.getService();
12935                    if (am == null) return;
12936                    final int[] resolvedUserIds;
12937                    if (userIds == null) {
12938                        resolvedUserIds = am.getRunningUserIds();
12939                    } else {
12940                        resolvedUserIds = userIds;
12941                    }
12942                    for (int id : resolvedUserIds) {
12943                        final Intent intent = new Intent(action,
12944                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12945                        if (extras != null) {
12946                            intent.putExtras(extras);
12947                        }
12948                        if (targetPkg != null) {
12949                            intent.setPackage(targetPkg);
12950                        }
12951                        // Modify the UID when posting to other users
12952                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12953                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12954                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12955                            intent.putExtra(Intent.EXTRA_UID, uid);
12956                        }
12957                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12958                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12959                        if (DEBUG_BROADCASTS) {
12960                            RuntimeException here = new RuntimeException("here");
12961                            here.fillInStackTrace();
12962                            Slog.d(TAG, "Sending to user " + id + ": "
12963                                    + intent.toShortString(false, true, false, false)
12964                                    + " " + intent.getExtras(), here);
12965                        }
12966                        am.broadcastIntent(null, intent, null, finishedReceiver,
12967                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12968                                null, finishedReceiver != null, false, id);
12969                    }
12970                } catch (RemoteException ex) {
12971                }
12972            }
12973        });
12974    }
12975
12976    /**
12977     * Check if the external storage media is available. This is true if there
12978     * is a mounted external storage medium or if the external storage is
12979     * emulated.
12980     */
12981    private boolean isExternalMediaAvailable() {
12982        return mMediaMounted || Environment.isExternalStorageEmulated();
12983    }
12984
12985    @Override
12986    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12987        // writer
12988        synchronized (mPackages) {
12989            if (!isExternalMediaAvailable()) {
12990                // If the external storage is no longer mounted at this point,
12991                // the caller may not have been able to delete all of this
12992                // packages files and can not delete any more.  Bail.
12993                return null;
12994            }
12995            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12996            if (lastPackage != null) {
12997                pkgs.remove(lastPackage);
12998            }
12999            if (pkgs.size() > 0) {
13000                return pkgs.get(0);
13001            }
13002        }
13003        return null;
13004    }
13005
13006    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13007        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13008                userId, andCode ? 1 : 0, packageName);
13009        if (mSystemReady) {
13010            msg.sendToTarget();
13011        } else {
13012            if (mPostSystemReadyMessages == null) {
13013                mPostSystemReadyMessages = new ArrayList<>();
13014            }
13015            mPostSystemReadyMessages.add(msg);
13016        }
13017    }
13018
13019    void startCleaningPackages() {
13020        // reader
13021        if (!isExternalMediaAvailable()) {
13022            return;
13023        }
13024        synchronized (mPackages) {
13025            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13026                return;
13027            }
13028        }
13029        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13030        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13031        IActivityManager am = ActivityManager.getService();
13032        if (am != null) {
13033            try {
13034                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
13035                        UserHandle.USER_SYSTEM);
13036            } catch (RemoteException e) {
13037            }
13038        }
13039    }
13040
13041    @Override
13042    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13043            int installFlags, String installerPackageName, int userId) {
13044        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13045
13046        final int callingUid = Binder.getCallingUid();
13047        enforceCrossUserPermission(callingUid, userId,
13048                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13049
13050        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13051            try {
13052                if (observer != null) {
13053                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13054                }
13055            } catch (RemoteException re) {
13056            }
13057            return;
13058        }
13059
13060        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13061            installFlags |= PackageManager.INSTALL_FROM_ADB;
13062
13063        } else {
13064            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13065            // about installerPackageName.
13066
13067            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13068            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13069        }
13070
13071        UserHandle user;
13072        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13073            user = UserHandle.ALL;
13074        } else {
13075            user = new UserHandle(userId);
13076        }
13077
13078        // Only system components can circumvent runtime permissions when installing.
13079        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13080                && mContext.checkCallingOrSelfPermission(Manifest.permission
13081                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13082            throw new SecurityException("You need the "
13083                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13084                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13085        }
13086
13087        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13088                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13089            throw new IllegalArgumentException(
13090                    "New installs into ASEC containers no longer supported");
13091        }
13092
13093        final File originFile = new File(originPath);
13094        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13095
13096        final Message msg = mHandler.obtainMessage(INIT_COPY);
13097        final VerificationInfo verificationInfo = new VerificationInfo(
13098                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13099        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13100                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13101                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13102                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13103        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13104        msg.obj = params;
13105
13106        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13107                System.identityHashCode(msg.obj));
13108        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13109                System.identityHashCode(msg.obj));
13110
13111        mHandler.sendMessage(msg);
13112    }
13113
13114
13115    /**
13116     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13117     * it is acting on behalf on an enterprise or the user).
13118     *
13119     * Note that the ordering of the conditionals in this method is important. The checks we perform
13120     * are as follows, in this order:
13121     *
13122     * 1) If the install is being performed by a system app, we can trust the app to have set the
13123     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13124     *    what it is.
13125     * 2) If the install is being performed by a device or profile owner app, the install reason
13126     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13127     *    set the install reason correctly. If the app targets an older SDK version where install
13128     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13129     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13130     * 3) In all other cases, the install is being performed by a regular app that is neither part
13131     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13132     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13133     *    set to enterprise policy and if so, change it to unknown instead.
13134     */
13135    private int fixUpInstallReason(String installerPackageName, int installerUid,
13136            int installReason) {
13137        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13138                == PERMISSION_GRANTED) {
13139            // If the install is being performed by a system app, we trust that app to have set the
13140            // install reason correctly.
13141            return installReason;
13142        }
13143
13144        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13145            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13146        if (dpm != null) {
13147            ComponentName owner = null;
13148            try {
13149                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13150                if (owner == null) {
13151                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13152                }
13153            } catch (RemoteException e) {
13154            }
13155            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13156                // If the install is being performed by a device or profile owner, the install
13157                // reason should be enterprise policy.
13158                return PackageManager.INSTALL_REASON_POLICY;
13159            }
13160        }
13161
13162        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13163            // If the install is being performed by a regular app (i.e. neither system app nor
13164            // device or profile owner), we have no reason to believe that the app is acting on
13165            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13166            // change it to unknown instead.
13167            return PackageManager.INSTALL_REASON_UNKNOWN;
13168        }
13169
13170        // If the install is being performed by a regular app and the install reason was set to any
13171        // value but enterprise policy, leave the install reason unchanged.
13172        return installReason;
13173    }
13174
13175    void installStage(String packageName, File stagedDir, String stagedCid,
13176            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13177            String installerPackageName, int installerUid, UserHandle user,
13178            Certificate[][] certificates) {
13179        if (DEBUG_EPHEMERAL) {
13180            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13181                Slog.d(TAG, "Ephemeral install of " + packageName);
13182            }
13183        }
13184        final VerificationInfo verificationInfo = new VerificationInfo(
13185                sessionParams.originatingUri, sessionParams.referrerUri,
13186                sessionParams.originatingUid, installerUid);
13187
13188        final OriginInfo origin;
13189        if (stagedDir != null) {
13190            origin = OriginInfo.fromStagedFile(stagedDir);
13191        } else {
13192            origin = OriginInfo.fromStagedContainer(stagedCid);
13193        }
13194
13195        final Message msg = mHandler.obtainMessage(INIT_COPY);
13196        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13197                sessionParams.installReason);
13198        final InstallParams params = new InstallParams(origin, null, observer,
13199                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13200                verificationInfo, user, sessionParams.abiOverride,
13201                sessionParams.grantedRuntimePermissions, certificates, installReason);
13202        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13203        msg.obj = params;
13204
13205        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13206                System.identityHashCode(msg.obj));
13207        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13208                System.identityHashCode(msg.obj));
13209
13210        mHandler.sendMessage(msg);
13211    }
13212
13213    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13214            int userId) {
13215        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13216        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13217    }
13218
13219    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13220            int appId, int... userIds) {
13221        if (ArrayUtils.isEmpty(userIds)) {
13222            return;
13223        }
13224        Bundle extras = new Bundle(1);
13225        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13226        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13227
13228        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13229                packageName, extras, 0, null, null, userIds);
13230        if (isSystem) {
13231            mHandler.post(() -> {
13232                        for (int userId : userIds) {
13233                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13234                        }
13235                    }
13236            );
13237        }
13238    }
13239
13240    /**
13241     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13242     * automatically without needing an explicit launch.
13243     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13244     */
13245    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13246        // If user is not running, the app didn't miss any broadcast
13247        if (!mUserManagerInternal.isUserRunning(userId)) {
13248            return;
13249        }
13250        final IActivityManager am = ActivityManager.getService();
13251        try {
13252            // Deliver LOCKED_BOOT_COMPLETED first
13253            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13254                    .setPackage(packageName);
13255            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13256            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13257                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13258
13259            // Deliver BOOT_COMPLETED only if user is unlocked
13260            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13261                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13262                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13263                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13264            }
13265        } catch (RemoteException e) {
13266            throw e.rethrowFromSystemServer();
13267        }
13268    }
13269
13270    @Override
13271    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13272            int userId) {
13273        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13274        PackageSetting pkgSetting;
13275        final int uid = Binder.getCallingUid();
13276        enforceCrossUserPermission(uid, userId,
13277                true /* requireFullPermission */, true /* checkShell */,
13278                "setApplicationHiddenSetting for user " + userId);
13279
13280        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13281            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13282            return false;
13283        }
13284
13285        long callingId = Binder.clearCallingIdentity();
13286        try {
13287            boolean sendAdded = false;
13288            boolean sendRemoved = false;
13289            // writer
13290            synchronized (mPackages) {
13291                pkgSetting = mSettings.mPackages.get(packageName);
13292                if (pkgSetting == null) {
13293                    return false;
13294                }
13295                // Do not allow "android" is being disabled
13296                if ("android".equals(packageName)) {
13297                    Slog.w(TAG, "Cannot hide package: android");
13298                    return false;
13299                }
13300                // Cannot hide static shared libs as they are considered
13301                // a part of the using app (emulating static linking). Also
13302                // static libs are installed always on internal storage.
13303                PackageParser.Package pkg = mPackages.get(packageName);
13304                if (pkg != null && pkg.staticSharedLibName != null) {
13305                    Slog.w(TAG, "Cannot hide package: " + packageName
13306                            + " providing static shared library: "
13307                            + pkg.staticSharedLibName);
13308                    return false;
13309                }
13310                // Only allow protected packages to hide themselves.
13311                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13312                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13313                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13314                    return false;
13315                }
13316
13317                if (pkgSetting.getHidden(userId) != hidden) {
13318                    pkgSetting.setHidden(hidden, userId);
13319                    mSettings.writePackageRestrictionsLPr(userId);
13320                    if (hidden) {
13321                        sendRemoved = true;
13322                    } else {
13323                        sendAdded = true;
13324                    }
13325                }
13326            }
13327            if (sendAdded) {
13328                sendPackageAddedForUser(packageName, pkgSetting, userId);
13329                return true;
13330            }
13331            if (sendRemoved) {
13332                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13333                        "hiding pkg");
13334                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13335                return true;
13336            }
13337        } finally {
13338            Binder.restoreCallingIdentity(callingId);
13339        }
13340        return false;
13341    }
13342
13343    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13344            int userId) {
13345        final PackageRemovedInfo info = new PackageRemovedInfo();
13346        info.removedPackage = packageName;
13347        info.removedUsers = new int[] {userId};
13348        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13349        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13350    }
13351
13352    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13353        if (pkgList.length > 0) {
13354            Bundle extras = new Bundle(1);
13355            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13356
13357            sendPackageBroadcast(
13358                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13359                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13360                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13361                    new int[] {userId});
13362        }
13363    }
13364
13365    /**
13366     * Returns true if application is not found or there was an error. Otherwise it returns
13367     * the hidden state of the package for the given user.
13368     */
13369    @Override
13370    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13371        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13372        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13373                true /* requireFullPermission */, false /* checkShell */,
13374                "getApplicationHidden for user " + userId);
13375        PackageSetting pkgSetting;
13376        long callingId = Binder.clearCallingIdentity();
13377        try {
13378            // writer
13379            synchronized (mPackages) {
13380                pkgSetting = mSettings.mPackages.get(packageName);
13381                if (pkgSetting == null) {
13382                    return true;
13383                }
13384                return pkgSetting.getHidden(userId);
13385            }
13386        } finally {
13387            Binder.restoreCallingIdentity(callingId);
13388        }
13389    }
13390
13391    /**
13392     * @hide
13393     */
13394    @Override
13395    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13396            int installReason) {
13397        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13398                null);
13399        PackageSetting pkgSetting;
13400        final int uid = Binder.getCallingUid();
13401        enforceCrossUserPermission(uid, userId,
13402                true /* requireFullPermission */, true /* checkShell */,
13403                "installExistingPackage for user " + userId);
13404        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13405            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13406        }
13407
13408        long callingId = Binder.clearCallingIdentity();
13409        try {
13410            boolean installed = false;
13411            final boolean instantApp =
13412                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13413            final boolean fullApp =
13414                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13415
13416            // writer
13417            synchronized (mPackages) {
13418                pkgSetting = mSettings.mPackages.get(packageName);
13419                if (pkgSetting == null) {
13420                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13421                }
13422                if (!pkgSetting.getInstalled(userId)) {
13423                    pkgSetting.setInstalled(true, userId);
13424                    pkgSetting.setHidden(false, userId);
13425                    pkgSetting.setInstallReason(installReason, userId);
13426                    mSettings.writePackageRestrictionsLPr(userId);
13427                    mSettings.writeKernelMappingLPr(pkgSetting);
13428                    installed = true;
13429                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13430                    // upgrade app from instant to full; we don't allow app downgrade
13431                    installed = true;
13432                }
13433                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13434            }
13435
13436            if (installed) {
13437                if (pkgSetting.pkg != null) {
13438                    synchronized (mInstallLock) {
13439                        // We don't need to freeze for a brand new install
13440                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13441                    }
13442                }
13443                sendPackageAddedForUser(packageName, pkgSetting, userId);
13444                synchronized (mPackages) {
13445                    updateSequenceNumberLP(packageName, new int[]{ userId });
13446                }
13447            }
13448        } finally {
13449            Binder.restoreCallingIdentity(callingId);
13450        }
13451
13452        return PackageManager.INSTALL_SUCCEEDED;
13453    }
13454
13455    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13456            boolean instantApp, boolean fullApp) {
13457        // no state specified; do nothing
13458        if (!instantApp && !fullApp) {
13459            return;
13460        }
13461        if (userId != UserHandle.USER_ALL) {
13462            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13463                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13464            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13465                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13466            }
13467        } else {
13468            for (int currentUserId : sUserManager.getUserIds()) {
13469                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13470                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13471                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13472                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13473                }
13474            }
13475        }
13476    }
13477
13478    boolean isUserRestricted(int userId, String restrictionKey) {
13479        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13480        if (restrictions.getBoolean(restrictionKey, false)) {
13481            Log.w(TAG, "User is restricted: " + restrictionKey);
13482            return true;
13483        }
13484        return false;
13485    }
13486
13487    @Override
13488    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13489            int userId) {
13490        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13491        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13492                true /* requireFullPermission */, true /* checkShell */,
13493                "setPackagesSuspended for user " + userId);
13494
13495        if (ArrayUtils.isEmpty(packageNames)) {
13496            return packageNames;
13497        }
13498
13499        // List of package names for whom the suspended state has changed.
13500        List<String> changedPackages = new ArrayList<>(packageNames.length);
13501        // List of package names for whom the suspended state is not set as requested in this
13502        // method.
13503        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13504        long callingId = Binder.clearCallingIdentity();
13505        try {
13506            for (int i = 0; i < packageNames.length; i++) {
13507                String packageName = packageNames[i];
13508                boolean changed = false;
13509                final int appId;
13510                synchronized (mPackages) {
13511                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13512                    if (pkgSetting == null) {
13513                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13514                                + "\". Skipping suspending/un-suspending.");
13515                        unactionedPackages.add(packageName);
13516                        continue;
13517                    }
13518                    appId = pkgSetting.appId;
13519                    if (pkgSetting.getSuspended(userId) != suspended) {
13520                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13521                            unactionedPackages.add(packageName);
13522                            continue;
13523                        }
13524                        pkgSetting.setSuspended(suspended, userId);
13525                        mSettings.writePackageRestrictionsLPr(userId);
13526                        changed = true;
13527                        changedPackages.add(packageName);
13528                    }
13529                }
13530
13531                if (changed && suspended) {
13532                    killApplication(packageName, UserHandle.getUid(userId, appId),
13533                            "suspending package");
13534                }
13535            }
13536        } finally {
13537            Binder.restoreCallingIdentity(callingId);
13538        }
13539
13540        if (!changedPackages.isEmpty()) {
13541            sendPackagesSuspendedForUser(changedPackages.toArray(
13542                    new String[changedPackages.size()]), userId, suspended);
13543        }
13544
13545        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13546    }
13547
13548    @Override
13549    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13550        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13551                true /* requireFullPermission */, false /* checkShell */,
13552                "isPackageSuspendedForUser for user " + userId);
13553        synchronized (mPackages) {
13554            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13555            if (pkgSetting == null) {
13556                throw new IllegalArgumentException("Unknown target package: " + packageName);
13557            }
13558            return pkgSetting.getSuspended(userId);
13559        }
13560    }
13561
13562    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13563        if (isPackageDeviceAdmin(packageName, userId)) {
13564            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13565                    + "\": has an active device admin");
13566            return false;
13567        }
13568
13569        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13570        if (packageName.equals(activeLauncherPackageName)) {
13571            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13572                    + "\": contains the active launcher");
13573            return false;
13574        }
13575
13576        if (packageName.equals(mRequiredInstallerPackage)) {
13577            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13578                    + "\": required for package installation");
13579            return false;
13580        }
13581
13582        if (packageName.equals(mRequiredUninstallerPackage)) {
13583            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13584                    + "\": required for package uninstallation");
13585            return false;
13586        }
13587
13588        if (packageName.equals(mRequiredVerifierPackage)) {
13589            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13590                    + "\": required for package verification");
13591            return false;
13592        }
13593
13594        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13595            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13596                    + "\": is the default dialer");
13597            return false;
13598        }
13599
13600        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13601            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13602                    + "\": protected package");
13603            return false;
13604        }
13605
13606        // Cannot suspend static shared libs as they are considered
13607        // a part of the using app (emulating static linking). Also
13608        // static libs are installed always on internal storage.
13609        PackageParser.Package pkg = mPackages.get(packageName);
13610        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13611            Slog.w(TAG, "Cannot suspend package: " + packageName
13612                    + " providing static shared library: "
13613                    + pkg.staticSharedLibName);
13614            return false;
13615        }
13616
13617        return true;
13618    }
13619
13620    private String getActiveLauncherPackageName(int userId) {
13621        Intent intent = new Intent(Intent.ACTION_MAIN);
13622        intent.addCategory(Intent.CATEGORY_HOME);
13623        ResolveInfo resolveInfo = resolveIntent(
13624                intent,
13625                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13626                PackageManager.MATCH_DEFAULT_ONLY,
13627                userId);
13628
13629        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13630    }
13631
13632    private String getDefaultDialerPackageName(int userId) {
13633        synchronized (mPackages) {
13634            return mSettings.getDefaultDialerPackageNameLPw(userId);
13635        }
13636    }
13637
13638    @Override
13639    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13640        mContext.enforceCallingOrSelfPermission(
13641                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13642                "Only package verification agents can verify applications");
13643
13644        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13645        final PackageVerificationResponse response = new PackageVerificationResponse(
13646                verificationCode, Binder.getCallingUid());
13647        msg.arg1 = id;
13648        msg.obj = response;
13649        mHandler.sendMessage(msg);
13650    }
13651
13652    @Override
13653    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13654            long millisecondsToDelay) {
13655        mContext.enforceCallingOrSelfPermission(
13656                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13657                "Only package verification agents can extend verification timeouts");
13658
13659        final PackageVerificationState state = mPendingVerification.get(id);
13660        final PackageVerificationResponse response = new PackageVerificationResponse(
13661                verificationCodeAtTimeout, Binder.getCallingUid());
13662
13663        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13664            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13665        }
13666        if (millisecondsToDelay < 0) {
13667            millisecondsToDelay = 0;
13668        }
13669        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13670                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13671            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13672        }
13673
13674        if ((state != null) && !state.timeoutExtended()) {
13675            state.extendTimeout();
13676
13677            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13678            msg.arg1 = id;
13679            msg.obj = response;
13680            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13681        }
13682    }
13683
13684    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13685            int verificationCode, UserHandle user) {
13686        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13687        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13688        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13689        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13690        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13691
13692        mContext.sendBroadcastAsUser(intent, user,
13693                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13694    }
13695
13696    private ComponentName matchComponentForVerifier(String packageName,
13697            List<ResolveInfo> receivers) {
13698        ActivityInfo targetReceiver = null;
13699
13700        final int NR = receivers.size();
13701        for (int i = 0; i < NR; i++) {
13702            final ResolveInfo info = receivers.get(i);
13703            if (info.activityInfo == null) {
13704                continue;
13705            }
13706
13707            if (packageName.equals(info.activityInfo.packageName)) {
13708                targetReceiver = info.activityInfo;
13709                break;
13710            }
13711        }
13712
13713        if (targetReceiver == null) {
13714            return null;
13715        }
13716
13717        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13718    }
13719
13720    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13721            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13722        if (pkgInfo.verifiers.length == 0) {
13723            return null;
13724        }
13725
13726        final int N = pkgInfo.verifiers.length;
13727        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13728        for (int i = 0; i < N; i++) {
13729            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13730
13731            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13732                    receivers);
13733            if (comp == null) {
13734                continue;
13735            }
13736
13737            final int verifierUid = getUidForVerifier(verifierInfo);
13738            if (verifierUid == -1) {
13739                continue;
13740            }
13741
13742            if (DEBUG_VERIFY) {
13743                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13744                        + " with the correct signature");
13745            }
13746            sufficientVerifiers.add(comp);
13747            verificationState.addSufficientVerifier(verifierUid);
13748        }
13749
13750        return sufficientVerifiers;
13751    }
13752
13753    private int getUidForVerifier(VerifierInfo verifierInfo) {
13754        synchronized (mPackages) {
13755            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13756            if (pkg == null) {
13757                return -1;
13758            } else if (pkg.mSignatures.length != 1) {
13759                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13760                        + " has more than one signature; ignoring");
13761                return -1;
13762            }
13763
13764            /*
13765             * If the public key of the package's signature does not match
13766             * our expected public key, then this is a different package and
13767             * we should skip.
13768             */
13769
13770            final byte[] expectedPublicKey;
13771            try {
13772                final Signature verifierSig = pkg.mSignatures[0];
13773                final PublicKey publicKey = verifierSig.getPublicKey();
13774                expectedPublicKey = publicKey.getEncoded();
13775            } catch (CertificateException e) {
13776                return -1;
13777            }
13778
13779            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13780
13781            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13782                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13783                        + " does not have the expected public key; ignoring");
13784                return -1;
13785            }
13786
13787            return pkg.applicationInfo.uid;
13788        }
13789    }
13790
13791    @Override
13792    public void finishPackageInstall(int token, boolean didLaunch) {
13793        enforceSystemOrRoot("Only the system is allowed to finish installs");
13794
13795        if (DEBUG_INSTALL) {
13796            Slog.v(TAG, "BM finishing package install for " + token);
13797        }
13798        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13799
13800        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13801        mHandler.sendMessage(msg);
13802    }
13803
13804    /**
13805     * Get the verification agent timeout.
13806     *
13807     * @return verification timeout in milliseconds
13808     */
13809    private long getVerificationTimeout() {
13810        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13811                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13812                DEFAULT_VERIFICATION_TIMEOUT);
13813    }
13814
13815    /**
13816     * Get the default verification agent response code.
13817     *
13818     * @return default verification response code
13819     */
13820    private int getDefaultVerificationResponse() {
13821        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13822                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13823                DEFAULT_VERIFICATION_RESPONSE);
13824    }
13825
13826    /**
13827     * Check whether or not package verification has been enabled.
13828     *
13829     * @return true if verification should be performed
13830     */
13831    private boolean isVerificationEnabled(int userId, int installFlags) {
13832        if (!DEFAULT_VERIFY_ENABLE) {
13833            return false;
13834        }
13835        // Ephemeral apps don't get the full verification treatment
13836        if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13837            if (DEBUG_EPHEMERAL) {
13838                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
13839            }
13840            return false;
13841        }
13842
13843        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13844
13845        // Check if installing from ADB
13846        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13847            // Do not run verification in a test harness environment
13848            if (ActivityManager.isRunningInTestHarness()) {
13849                return false;
13850            }
13851            if (ensureVerifyAppsEnabled) {
13852                return true;
13853            }
13854            // Check if the developer does not want package verification for ADB installs
13855            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13856                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13857                return false;
13858            }
13859        }
13860
13861        if (ensureVerifyAppsEnabled) {
13862            return true;
13863        }
13864
13865        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13866                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13867    }
13868
13869    @Override
13870    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13871            throws RemoteException {
13872        mContext.enforceCallingOrSelfPermission(
13873                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13874                "Only intentfilter verification agents can verify applications");
13875
13876        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13877        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13878                Binder.getCallingUid(), verificationCode, failedDomains);
13879        msg.arg1 = id;
13880        msg.obj = response;
13881        mHandler.sendMessage(msg);
13882    }
13883
13884    @Override
13885    public int getIntentVerificationStatus(String packageName, int userId) {
13886        synchronized (mPackages) {
13887            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13888        }
13889    }
13890
13891    @Override
13892    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13893        mContext.enforceCallingOrSelfPermission(
13894                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13895
13896        boolean result = false;
13897        synchronized (mPackages) {
13898            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13899        }
13900        if (result) {
13901            scheduleWritePackageRestrictionsLocked(userId);
13902        }
13903        return result;
13904    }
13905
13906    @Override
13907    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13908            String packageName) {
13909        synchronized (mPackages) {
13910            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13911        }
13912    }
13913
13914    @Override
13915    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13916        if (TextUtils.isEmpty(packageName)) {
13917            return ParceledListSlice.emptyList();
13918        }
13919        synchronized (mPackages) {
13920            PackageParser.Package pkg = mPackages.get(packageName);
13921            if (pkg == null || pkg.activities == null) {
13922                return ParceledListSlice.emptyList();
13923            }
13924            final int count = pkg.activities.size();
13925            ArrayList<IntentFilter> result = new ArrayList<>();
13926            for (int n=0; n<count; n++) {
13927                PackageParser.Activity activity = pkg.activities.get(n);
13928                if (activity.intents != null && activity.intents.size() > 0) {
13929                    result.addAll(activity.intents);
13930                }
13931            }
13932            return new ParceledListSlice<>(result);
13933        }
13934    }
13935
13936    @Override
13937    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13938        mContext.enforceCallingOrSelfPermission(
13939                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13940
13941        synchronized (mPackages) {
13942            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13943            if (packageName != null) {
13944                result |= updateIntentVerificationStatus(packageName,
13945                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13946                        userId);
13947                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13948                        packageName, userId);
13949            }
13950            return result;
13951        }
13952    }
13953
13954    @Override
13955    public String getDefaultBrowserPackageName(int userId) {
13956        synchronized (mPackages) {
13957            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13958        }
13959    }
13960
13961    /**
13962     * Get the "allow unknown sources" setting.
13963     *
13964     * @return the current "allow unknown sources" setting
13965     */
13966    private int getUnknownSourcesSettings() {
13967        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13968                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13969                -1);
13970    }
13971
13972    @Override
13973    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13974        final int uid = Binder.getCallingUid();
13975        // writer
13976        synchronized (mPackages) {
13977            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13978            if (targetPackageSetting == null) {
13979                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13980            }
13981
13982            PackageSetting installerPackageSetting;
13983            if (installerPackageName != null) {
13984                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13985                if (installerPackageSetting == null) {
13986                    throw new IllegalArgumentException("Unknown installer package: "
13987                            + installerPackageName);
13988                }
13989            } else {
13990                installerPackageSetting = null;
13991            }
13992
13993            Signature[] callerSignature;
13994            Object obj = mSettings.getUserIdLPr(uid);
13995            if (obj != null) {
13996                if (obj instanceof SharedUserSetting) {
13997                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13998                } else if (obj instanceof PackageSetting) {
13999                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14000                } else {
14001                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
14002                }
14003            } else {
14004                throw new SecurityException("Unknown calling UID: " + uid);
14005            }
14006
14007            // Verify: can't set installerPackageName to a package that is
14008            // not signed with the same cert as the caller.
14009            if (installerPackageSetting != null) {
14010                if (compareSignatures(callerSignature,
14011                        installerPackageSetting.signatures.mSignatures)
14012                        != PackageManager.SIGNATURE_MATCH) {
14013                    throw new SecurityException(
14014                            "Caller does not have same cert as new installer package "
14015                            + installerPackageName);
14016                }
14017            }
14018
14019            // Verify: if target already has an installer package, it must
14020            // be signed with the same cert as the caller.
14021            if (targetPackageSetting.installerPackageName != null) {
14022                PackageSetting setting = mSettings.mPackages.get(
14023                        targetPackageSetting.installerPackageName);
14024                // If the currently set package isn't valid, then it's always
14025                // okay to change it.
14026                if (setting != null) {
14027                    if (compareSignatures(callerSignature,
14028                            setting.signatures.mSignatures)
14029                            != PackageManager.SIGNATURE_MATCH) {
14030                        throw new SecurityException(
14031                                "Caller does not have same cert as old installer package "
14032                                + targetPackageSetting.installerPackageName);
14033                    }
14034                }
14035            }
14036
14037            // Okay!
14038            targetPackageSetting.installerPackageName = installerPackageName;
14039            if (installerPackageName != null) {
14040                mSettings.mInstallerPackages.add(installerPackageName);
14041            }
14042            scheduleWriteSettingsLocked();
14043        }
14044    }
14045
14046    @Override
14047    public void setApplicationCategoryHint(String packageName, int categoryHint,
14048            String callerPackageName) {
14049        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14050                callerPackageName);
14051        synchronized (mPackages) {
14052            PackageSetting ps = mSettings.mPackages.get(packageName);
14053            if (ps == null) {
14054                throw new IllegalArgumentException("Unknown target package " + packageName);
14055            }
14056
14057            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14058                throw new IllegalArgumentException("Calling package " + callerPackageName
14059                        + " is not installer for " + packageName);
14060            }
14061
14062            if (ps.categoryHint != categoryHint) {
14063                ps.categoryHint = categoryHint;
14064                scheduleWriteSettingsLocked();
14065            }
14066        }
14067    }
14068
14069    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14070        // Queue up an async operation since the package installation may take a little while.
14071        mHandler.post(new Runnable() {
14072            public void run() {
14073                mHandler.removeCallbacks(this);
14074                 // Result object to be returned
14075                PackageInstalledInfo res = new PackageInstalledInfo();
14076                res.setReturnCode(currentStatus);
14077                res.uid = -1;
14078                res.pkg = null;
14079                res.removedInfo = null;
14080                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14081                    args.doPreInstall(res.returnCode);
14082                    synchronized (mInstallLock) {
14083                        installPackageTracedLI(args, res);
14084                    }
14085                    args.doPostInstall(res.returnCode, res.uid);
14086                }
14087
14088                // A restore should be performed at this point if (a) the install
14089                // succeeded, (b) the operation is not an update, and (c) the new
14090                // package has not opted out of backup participation.
14091                final boolean update = res.removedInfo != null
14092                        && res.removedInfo.removedPackage != null;
14093                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14094                boolean doRestore = !update
14095                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14096
14097                // Set up the post-install work request bookkeeping.  This will be used
14098                // and cleaned up by the post-install event handling regardless of whether
14099                // there's a restore pass performed.  Token values are >= 1.
14100                int token;
14101                if (mNextInstallToken < 0) mNextInstallToken = 1;
14102                token = mNextInstallToken++;
14103
14104                PostInstallData data = new PostInstallData(args, res);
14105                mRunningInstalls.put(token, data);
14106                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14107
14108                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14109                    // Pass responsibility to the Backup Manager.  It will perform a
14110                    // restore if appropriate, then pass responsibility back to the
14111                    // Package Manager to run the post-install observer callbacks
14112                    // and broadcasts.
14113                    IBackupManager bm = IBackupManager.Stub.asInterface(
14114                            ServiceManager.getService(Context.BACKUP_SERVICE));
14115                    if (bm != null) {
14116                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14117                                + " to BM for possible restore");
14118                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14119                        try {
14120                            // TODO: http://b/22388012
14121                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14122                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14123                            } else {
14124                                doRestore = false;
14125                            }
14126                        } catch (RemoteException e) {
14127                            // can't happen; the backup manager is local
14128                        } catch (Exception e) {
14129                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14130                            doRestore = false;
14131                        }
14132                    } else {
14133                        Slog.e(TAG, "Backup Manager not found!");
14134                        doRestore = false;
14135                    }
14136                }
14137
14138                if (!doRestore) {
14139                    // No restore possible, or the Backup Manager was mysteriously not
14140                    // available -- just fire the post-install work request directly.
14141                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14142
14143                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14144
14145                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14146                    mHandler.sendMessage(msg);
14147                }
14148            }
14149        });
14150    }
14151
14152    /**
14153     * Callback from PackageSettings whenever an app is first transitioned out of the
14154     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14155     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14156     * here whether the app is the target of an ongoing install, and only send the
14157     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14158     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14159     * handling.
14160     */
14161    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14162        // Serialize this with the rest of the install-process message chain.  In the
14163        // restore-at-install case, this Runnable will necessarily run before the
14164        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14165        // are coherent.  In the non-restore case, the app has already completed install
14166        // and been launched through some other means, so it is not in a problematic
14167        // state for observers to see the FIRST_LAUNCH signal.
14168        mHandler.post(new Runnable() {
14169            @Override
14170            public void run() {
14171                for (int i = 0; i < mRunningInstalls.size(); i++) {
14172                    final PostInstallData data = mRunningInstalls.valueAt(i);
14173                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14174                        continue;
14175                    }
14176                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14177                        // right package; but is it for the right user?
14178                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14179                            if (userId == data.res.newUsers[uIndex]) {
14180                                if (DEBUG_BACKUP) {
14181                                    Slog.i(TAG, "Package " + pkgName
14182                                            + " being restored so deferring FIRST_LAUNCH");
14183                                }
14184                                return;
14185                            }
14186                        }
14187                    }
14188                }
14189                // didn't find it, so not being restored
14190                if (DEBUG_BACKUP) {
14191                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14192                }
14193                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14194            }
14195        });
14196    }
14197
14198    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14199        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14200                installerPkg, null, userIds);
14201    }
14202
14203    private abstract class HandlerParams {
14204        private static final int MAX_RETRIES = 4;
14205
14206        /**
14207         * Number of times startCopy() has been attempted and had a non-fatal
14208         * error.
14209         */
14210        private int mRetries = 0;
14211
14212        /** User handle for the user requesting the information or installation. */
14213        private final UserHandle mUser;
14214        String traceMethod;
14215        int traceCookie;
14216
14217        HandlerParams(UserHandle user) {
14218            mUser = user;
14219        }
14220
14221        UserHandle getUser() {
14222            return mUser;
14223        }
14224
14225        HandlerParams setTraceMethod(String traceMethod) {
14226            this.traceMethod = traceMethod;
14227            return this;
14228        }
14229
14230        HandlerParams setTraceCookie(int traceCookie) {
14231            this.traceCookie = traceCookie;
14232            return this;
14233        }
14234
14235        final boolean startCopy() {
14236            boolean res;
14237            try {
14238                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14239
14240                if (++mRetries > MAX_RETRIES) {
14241                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14242                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14243                    handleServiceError();
14244                    return false;
14245                } else {
14246                    handleStartCopy();
14247                    res = true;
14248                }
14249            } catch (RemoteException e) {
14250                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14251                mHandler.sendEmptyMessage(MCS_RECONNECT);
14252                res = false;
14253            }
14254            handleReturnCode();
14255            return res;
14256        }
14257
14258        final void serviceError() {
14259            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14260            handleServiceError();
14261            handleReturnCode();
14262        }
14263
14264        abstract void handleStartCopy() throws RemoteException;
14265        abstract void handleServiceError();
14266        abstract void handleReturnCode();
14267    }
14268
14269    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14270        for (File path : paths) {
14271            try {
14272                mcs.clearDirectory(path.getAbsolutePath());
14273            } catch (RemoteException e) {
14274            }
14275        }
14276    }
14277
14278    static class OriginInfo {
14279        /**
14280         * Location where install is coming from, before it has been
14281         * copied/renamed into place. This could be a single monolithic APK
14282         * file, or a cluster directory. This location may be untrusted.
14283         */
14284        final File file;
14285        final String cid;
14286
14287        /**
14288         * Flag indicating that {@link #file} or {@link #cid} has already been
14289         * staged, meaning downstream users don't need to defensively copy the
14290         * contents.
14291         */
14292        final boolean staged;
14293
14294        /**
14295         * Flag indicating that {@link #file} or {@link #cid} is an already
14296         * installed app that is being moved.
14297         */
14298        final boolean existing;
14299
14300        final String resolvedPath;
14301        final File resolvedFile;
14302
14303        static OriginInfo fromNothing() {
14304            return new OriginInfo(null, null, false, false);
14305        }
14306
14307        static OriginInfo fromUntrustedFile(File file) {
14308            return new OriginInfo(file, null, false, false);
14309        }
14310
14311        static OriginInfo fromExistingFile(File file) {
14312            return new OriginInfo(file, null, false, true);
14313        }
14314
14315        static OriginInfo fromStagedFile(File file) {
14316            return new OriginInfo(file, null, true, false);
14317        }
14318
14319        static OriginInfo fromStagedContainer(String cid) {
14320            return new OriginInfo(null, cid, true, false);
14321        }
14322
14323        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14324            this.file = file;
14325            this.cid = cid;
14326            this.staged = staged;
14327            this.existing = existing;
14328
14329            if (cid != null) {
14330                resolvedPath = PackageHelper.getSdDir(cid);
14331                resolvedFile = new File(resolvedPath);
14332            } else if (file != null) {
14333                resolvedPath = file.getAbsolutePath();
14334                resolvedFile = file;
14335            } else {
14336                resolvedPath = null;
14337                resolvedFile = null;
14338            }
14339        }
14340    }
14341
14342    static class MoveInfo {
14343        final int moveId;
14344        final String fromUuid;
14345        final String toUuid;
14346        final String packageName;
14347        final String dataAppName;
14348        final int appId;
14349        final String seinfo;
14350        final int targetSdkVersion;
14351
14352        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14353                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14354            this.moveId = moveId;
14355            this.fromUuid = fromUuid;
14356            this.toUuid = toUuid;
14357            this.packageName = packageName;
14358            this.dataAppName = dataAppName;
14359            this.appId = appId;
14360            this.seinfo = seinfo;
14361            this.targetSdkVersion = targetSdkVersion;
14362        }
14363    }
14364
14365    static class VerificationInfo {
14366        /** A constant used to indicate that a uid value is not present. */
14367        public static final int NO_UID = -1;
14368
14369        /** URI referencing where the package was downloaded from. */
14370        final Uri originatingUri;
14371
14372        /** HTTP referrer URI associated with the originatingURI. */
14373        final Uri referrer;
14374
14375        /** UID of the application that the install request originated from. */
14376        final int originatingUid;
14377
14378        /** UID of application requesting the install */
14379        final int installerUid;
14380
14381        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14382            this.originatingUri = originatingUri;
14383            this.referrer = referrer;
14384            this.originatingUid = originatingUid;
14385            this.installerUid = installerUid;
14386        }
14387    }
14388
14389    class InstallParams extends HandlerParams {
14390        final OriginInfo origin;
14391        final MoveInfo move;
14392        final IPackageInstallObserver2 observer;
14393        int installFlags;
14394        final String installerPackageName;
14395        final String volumeUuid;
14396        private InstallArgs mArgs;
14397        private int mRet;
14398        final String packageAbiOverride;
14399        final String[] grantedRuntimePermissions;
14400        final VerificationInfo verificationInfo;
14401        final Certificate[][] certificates;
14402        final int installReason;
14403
14404        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14405                int installFlags, String installerPackageName, String volumeUuid,
14406                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14407                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14408            super(user);
14409            this.origin = origin;
14410            this.move = move;
14411            this.observer = observer;
14412            this.installFlags = installFlags;
14413            this.installerPackageName = installerPackageName;
14414            this.volumeUuid = volumeUuid;
14415            this.verificationInfo = verificationInfo;
14416            this.packageAbiOverride = packageAbiOverride;
14417            this.grantedRuntimePermissions = grantedPermissions;
14418            this.certificates = certificates;
14419            this.installReason = installReason;
14420        }
14421
14422        @Override
14423        public String toString() {
14424            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14425                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14426        }
14427
14428        private int installLocationPolicy(PackageInfoLite pkgLite) {
14429            String packageName = pkgLite.packageName;
14430            int installLocation = pkgLite.installLocation;
14431            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14432            // reader
14433            synchronized (mPackages) {
14434                // Currently installed package which the new package is attempting to replace or
14435                // null if no such package is installed.
14436                PackageParser.Package installedPkg = mPackages.get(packageName);
14437                // Package which currently owns the data which the new package will own if installed.
14438                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14439                // will be null whereas dataOwnerPkg will contain information about the package
14440                // which was uninstalled while keeping its data.
14441                PackageParser.Package dataOwnerPkg = installedPkg;
14442                if (dataOwnerPkg  == null) {
14443                    PackageSetting ps = mSettings.mPackages.get(packageName);
14444                    if (ps != null) {
14445                        dataOwnerPkg = ps.pkg;
14446                    }
14447                }
14448
14449                if (dataOwnerPkg != null) {
14450                    // If installed, the package will get access to data left on the device by its
14451                    // predecessor. As a security measure, this is permited only if this is not a
14452                    // version downgrade or if the predecessor package is marked as debuggable and
14453                    // a downgrade is explicitly requested.
14454                    //
14455                    // On debuggable platform builds, downgrades are permitted even for
14456                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14457                    // not offer security guarantees and thus it's OK to disable some security
14458                    // mechanisms to make debugging/testing easier on those builds. However, even on
14459                    // debuggable builds downgrades of packages are permitted only if requested via
14460                    // installFlags. This is because we aim to keep the behavior of debuggable
14461                    // platform builds as close as possible to the behavior of non-debuggable
14462                    // platform builds.
14463                    final boolean downgradeRequested =
14464                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14465                    final boolean packageDebuggable =
14466                                (dataOwnerPkg.applicationInfo.flags
14467                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14468                    final boolean downgradePermitted =
14469                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14470                    if (!downgradePermitted) {
14471                        try {
14472                            checkDowngrade(dataOwnerPkg, pkgLite);
14473                        } catch (PackageManagerException e) {
14474                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14475                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14476                        }
14477                    }
14478                }
14479
14480                if (installedPkg != null) {
14481                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14482                        // Check for updated system application.
14483                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14484                            if (onSd) {
14485                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14486                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14487                            }
14488                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14489                        } else {
14490                            if (onSd) {
14491                                // Install flag overrides everything.
14492                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14493                            }
14494                            // If current upgrade specifies particular preference
14495                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14496                                // Application explicitly specified internal.
14497                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14498                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14499                                // App explictly prefers external. Let policy decide
14500                            } else {
14501                                // Prefer previous location
14502                                if (isExternal(installedPkg)) {
14503                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14504                                }
14505                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14506                            }
14507                        }
14508                    } else {
14509                        // Invalid install. Return error code
14510                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14511                    }
14512                }
14513            }
14514            // All the special cases have been taken care of.
14515            // Return result based on recommended install location.
14516            if (onSd) {
14517                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14518            }
14519            return pkgLite.recommendedInstallLocation;
14520        }
14521
14522        /*
14523         * Invoke remote method to get package information and install
14524         * location values. Override install location based on default
14525         * policy if needed and then create install arguments based
14526         * on the install location.
14527         */
14528        public void handleStartCopy() throws RemoteException {
14529            int ret = PackageManager.INSTALL_SUCCEEDED;
14530
14531            // If we're already staged, we've firmly committed to an install location
14532            if (origin.staged) {
14533                if (origin.file != null) {
14534                    installFlags |= PackageManager.INSTALL_INTERNAL;
14535                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14536                } else if (origin.cid != null) {
14537                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14538                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14539                } else {
14540                    throw new IllegalStateException("Invalid stage location");
14541                }
14542            }
14543
14544            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14545            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14546            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14547            PackageInfoLite pkgLite = null;
14548
14549            if (onInt && onSd) {
14550                // Check if both bits are set.
14551                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14552                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14553            } else if (onSd && ephemeral) {
14554                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14555                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14556            } else {
14557                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14558                        packageAbiOverride);
14559
14560                if (DEBUG_EPHEMERAL && ephemeral) {
14561                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14562                }
14563
14564                /*
14565                 * If we have too little free space, try to free cache
14566                 * before giving up.
14567                 */
14568                if (!origin.staged && pkgLite.recommendedInstallLocation
14569                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14570                    // TODO: focus freeing disk space on the target device
14571                    final StorageManager storage = StorageManager.from(mContext);
14572                    final long lowThreshold = storage.getStorageLowBytes(
14573                            Environment.getDataDirectory());
14574
14575                    final long sizeBytes = mContainerService.calculateInstalledSize(
14576                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14577
14578                    try {
14579                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14580                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14581                                installFlags, packageAbiOverride);
14582                    } catch (InstallerException e) {
14583                        Slog.w(TAG, "Failed to free cache", e);
14584                    }
14585
14586                    /*
14587                     * The cache free must have deleted the file we
14588                     * downloaded to install.
14589                     *
14590                     * TODO: fix the "freeCache" call to not delete
14591                     *       the file we care about.
14592                     */
14593                    if (pkgLite.recommendedInstallLocation
14594                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14595                        pkgLite.recommendedInstallLocation
14596                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14597                    }
14598                }
14599            }
14600
14601            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14602                int loc = pkgLite.recommendedInstallLocation;
14603                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14604                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14605                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14606                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14607                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14608                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14609                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14610                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14611                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14612                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14613                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14614                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14615                } else {
14616                    // Override with defaults if needed.
14617                    loc = installLocationPolicy(pkgLite);
14618                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14619                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14620                    } else if (!onSd && !onInt) {
14621                        // Override install location with flags
14622                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14623                            // Set the flag to install on external media.
14624                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14625                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14626                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14627                            if (DEBUG_EPHEMERAL) {
14628                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14629                            }
14630                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14631                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14632                                    |PackageManager.INSTALL_INTERNAL);
14633                        } else {
14634                            // Make sure the flag for installing on external
14635                            // media is unset
14636                            installFlags |= PackageManager.INSTALL_INTERNAL;
14637                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14638                        }
14639                    }
14640                }
14641            }
14642
14643            final InstallArgs args = createInstallArgs(this);
14644            mArgs = args;
14645
14646            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14647                // TODO: http://b/22976637
14648                // Apps installed for "all" users use the device owner to verify the app
14649                UserHandle verifierUser = getUser();
14650                if (verifierUser == UserHandle.ALL) {
14651                    verifierUser = UserHandle.SYSTEM;
14652                }
14653
14654                /*
14655                 * Determine if we have any installed package verifiers. If we
14656                 * do, then we'll defer to them to verify the packages.
14657                 */
14658                final int requiredUid = mRequiredVerifierPackage == null ? -1
14659                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14660                                verifierUser.getIdentifier());
14661                if (!origin.existing && requiredUid != -1
14662                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14663                    final Intent verification = new Intent(
14664                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14665                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14666                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14667                            PACKAGE_MIME_TYPE);
14668                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14669
14670                    // Query all live verifiers based on current user state
14671                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14672                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14673
14674                    if (DEBUG_VERIFY) {
14675                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14676                                + verification.toString() + " with " + pkgLite.verifiers.length
14677                                + " optional verifiers");
14678                    }
14679
14680                    final int verificationId = mPendingVerificationToken++;
14681
14682                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14683
14684                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14685                            installerPackageName);
14686
14687                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14688                            installFlags);
14689
14690                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14691                            pkgLite.packageName);
14692
14693                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14694                            pkgLite.versionCode);
14695
14696                    if (verificationInfo != null) {
14697                        if (verificationInfo.originatingUri != null) {
14698                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14699                                    verificationInfo.originatingUri);
14700                        }
14701                        if (verificationInfo.referrer != null) {
14702                            verification.putExtra(Intent.EXTRA_REFERRER,
14703                                    verificationInfo.referrer);
14704                        }
14705                        if (verificationInfo.originatingUid >= 0) {
14706                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14707                                    verificationInfo.originatingUid);
14708                        }
14709                        if (verificationInfo.installerUid >= 0) {
14710                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14711                                    verificationInfo.installerUid);
14712                        }
14713                    }
14714
14715                    final PackageVerificationState verificationState = new PackageVerificationState(
14716                            requiredUid, args);
14717
14718                    mPendingVerification.append(verificationId, verificationState);
14719
14720                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14721                            receivers, verificationState);
14722
14723                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14724                    final long idleDuration = getVerificationTimeout();
14725
14726                    /*
14727                     * If any sufficient verifiers were listed in the package
14728                     * manifest, attempt to ask them.
14729                     */
14730                    if (sufficientVerifiers != null) {
14731                        final int N = sufficientVerifiers.size();
14732                        if (N == 0) {
14733                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14734                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14735                        } else {
14736                            for (int i = 0; i < N; i++) {
14737                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14738                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14739                                        verifierComponent.getPackageName(), idleDuration,
14740                                        verifierUser.getIdentifier(), false, "package verifier");
14741
14742                                final Intent sufficientIntent = new Intent(verification);
14743                                sufficientIntent.setComponent(verifierComponent);
14744                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14745                            }
14746                        }
14747                    }
14748
14749                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14750                            mRequiredVerifierPackage, receivers);
14751                    if (ret == PackageManager.INSTALL_SUCCEEDED
14752                            && mRequiredVerifierPackage != null) {
14753                        Trace.asyncTraceBegin(
14754                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14755                        /*
14756                         * Send the intent to the required verification agent,
14757                         * but only start the verification timeout after the
14758                         * target BroadcastReceivers have run.
14759                         */
14760                        verification.setComponent(requiredVerifierComponent);
14761                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14762                                requiredVerifierComponent.getPackageName(), idleDuration,
14763                                verifierUser.getIdentifier(), false, "package verifier");
14764                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14765                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14766                                new BroadcastReceiver() {
14767                                    @Override
14768                                    public void onReceive(Context context, Intent intent) {
14769                                        final Message msg = mHandler
14770                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14771                                        msg.arg1 = verificationId;
14772                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14773                                    }
14774                                }, null, 0, null, null);
14775
14776                        /*
14777                         * We don't want the copy to proceed until verification
14778                         * succeeds, so null out this field.
14779                         */
14780                        mArgs = null;
14781                    }
14782                } else {
14783                    /*
14784                     * No package verification is enabled, so immediately start
14785                     * the remote call to initiate copy using temporary file.
14786                     */
14787                    ret = args.copyApk(mContainerService, true);
14788                }
14789            }
14790
14791            mRet = ret;
14792        }
14793
14794        @Override
14795        void handleReturnCode() {
14796            // If mArgs is null, then MCS couldn't be reached. When it
14797            // reconnects, it will try again to install. At that point, this
14798            // will succeed.
14799            if (mArgs != null) {
14800                processPendingInstall(mArgs, mRet);
14801            }
14802        }
14803
14804        @Override
14805        void handleServiceError() {
14806            mArgs = createInstallArgs(this);
14807            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14808        }
14809
14810        public boolean isForwardLocked() {
14811            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14812        }
14813    }
14814
14815    /**
14816     * Used during creation of InstallArgs
14817     *
14818     * @param installFlags package installation flags
14819     * @return true if should be installed on external storage
14820     */
14821    private static boolean installOnExternalAsec(int installFlags) {
14822        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14823            return false;
14824        }
14825        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14826            return true;
14827        }
14828        return false;
14829    }
14830
14831    /**
14832     * Used during creation of InstallArgs
14833     *
14834     * @param installFlags package installation flags
14835     * @return true if should be installed as forward locked
14836     */
14837    private static boolean installForwardLocked(int installFlags) {
14838        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14839    }
14840
14841    private InstallArgs createInstallArgs(InstallParams params) {
14842        if (params.move != null) {
14843            return new MoveInstallArgs(params);
14844        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14845            return new AsecInstallArgs(params);
14846        } else {
14847            return new FileInstallArgs(params);
14848        }
14849    }
14850
14851    /**
14852     * Create args that describe an existing installed package. Typically used
14853     * when cleaning up old installs, or used as a move source.
14854     */
14855    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14856            String resourcePath, String[] instructionSets) {
14857        final boolean isInAsec;
14858        if (installOnExternalAsec(installFlags)) {
14859            /* Apps on SD card are always in ASEC containers. */
14860            isInAsec = true;
14861        } else if (installForwardLocked(installFlags)
14862                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14863            /*
14864             * Forward-locked apps are only in ASEC containers if they're the
14865             * new style
14866             */
14867            isInAsec = true;
14868        } else {
14869            isInAsec = false;
14870        }
14871
14872        if (isInAsec) {
14873            return new AsecInstallArgs(codePath, instructionSets,
14874                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14875        } else {
14876            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14877        }
14878    }
14879
14880    static abstract class InstallArgs {
14881        /** @see InstallParams#origin */
14882        final OriginInfo origin;
14883        /** @see InstallParams#move */
14884        final MoveInfo move;
14885
14886        final IPackageInstallObserver2 observer;
14887        // Always refers to PackageManager flags only
14888        final int installFlags;
14889        final String installerPackageName;
14890        final String volumeUuid;
14891        final UserHandle user;
14892        final String abiOverride;
14893        final String[] installGrantPermissions;
14894        /** If non-null, drop an async trace when the install completes */
14895        final String traceMethod;
14896        final int traceCookie;
14897        final Certificate[][] certificates;
14898        final int installReason;
14899
14900        // The list of instruction sets supported by this app. This is currently
14901        // only used during the rmdex() phase to clean up resources. We can get rid of this
14902        // if we move dex files under the common app path.
14903        /* nullable */ String[] instructionSets;
14904
14905        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14906                int installFlags, String installerPackageName, String volumeUuid,
14907                UserHandle user, String[] instructionSets,
14908                String abiOverride, String[] installGrantPermissions,
14909                String traceMethod, int traceCookie, Certificate[][] certificates,
14910                int installReason) {
14911            this.origin = origin;
14912            this.move = move;
14913            this.installFlags = installFlags;
14914            this.observer = observer;
14915            this.installerPackageName = installerPackageName;
14916            this.volumeUuid = volumeUuid;
14917            this.user = user;
14918            this.instructionSets = instructionSets;
14919            this.abiOverride = abiOverride;
14920            this.installGrantPermissions = installGrantPermissions;
14921            this.traceMethod = traceMethod;
14922            this.traceCookie = traceCookie;
14923            this.certificates = certificates;
14924            this.installReason = installReason;
14925        }
14926
14927        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14928        abstract int doPreInstall(int status);
14929
14930        /**
14931         * Rename package into final resting place. All paths on the given
14932         * scanned package should be updated to reflect the rename.
14933         */
14934        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14935        abstract int doPostInstall(int status, int uid);
14936
14937        /** @see PackageSettingBase#codePathString */
14938        abstract String getCodePath();
14939        /** @see PackageSettingBase#resourcePathString */
14940        abstract String getResourcePath();
14941
14942        // Need installer lock especially for dex file removal.
14943        abstract void cleanUpResourcesLI();
14944        abstract boolean doPostDeleteLI(boolean delete);
14945
14946        /**
14947         * Called before the source arguments are copied. This is used mostly
14948         * for MoveParams when it needs to read the source file to put it in the
14949         * destination.
14950         */
14951        int doPreCopy() {
14952            return PackageManager.INSTALL_SUCCEEDED;
14953        }
14954
14955        /**
14956         * Called after the source arguments are copied. This is used mostly for
14957         * MoveParams when it needs to read the source file to put it in the
14958         * destination.
14959         */
14960        int doPostCopy(int uid) {
14961            return PackageManager.INSTALL_SUCCEEDED;
14962        }
14963
14964        protected boolean isFwdLocked() {
14965            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14966        }
14967
14968        protected boolean isExternalAsec() {
14969            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14970        }
14971
14972        protected boolean isEphemeral() {
14973            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14974        }
14975
14976        UserHandle getUser() {
14977            return user;
14978        }
14979    }
14980
14981    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14982        if (!allCodePaths.isEmpty()) {
14983            if (instructionSets == null) {
14984                throw new IllegalStateException("instructionSet == null");
14985            }
14986            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14987            for (String codePath : allCodePaths) {
14988                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14989                    try {
14990                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14991                    } catch (InstallerException ignored) {
14992                    }
14993                }
14994            }
14995        }
14996    }
14997
14998    /**
14999     * Logic to handle installation of non-ASEC applications, including copying
15000     * and renaming logic.
15001     */
15002    class FileInstallArgs extends InstallArgs {
15003        private File codeFile;
15004        private File resourceFile;
15005
15006        // Example topology:
15007        // /data/app/com.example/base.apk
15008        // /data/app/com.example/split_foo.apk
15009        // /data/app/com.example/lib/arm/libfoo.so
15010        // /data/app/com.example/lib/arm64/libfoo.so
15011        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15012
15013        /** New install */
15014        FileInstallArgs(InstallParams params) {
15015            super(params.origin, params.move, params.observer, params.installFlags,
15016                    params.installerPackageName, params.volumeUuid,
15017                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15018                    params.grantedRuntimePermissions,
15019                    params.traceMethod, params.traceCookie, params.certificates,
15020                    params.installReason);
15021            if (isFwdLocked()) {
15022                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15023            }
15024        }
15025
15026        /** Existing install */
15027        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15028            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15029                    null, null, null, 0, null /*certificates*/,
15030                    PackageManager.INSTALL_REASON_UNKNOWN);
15031            this.codeFile = (codePath != null) ? new File(codePath) : null;
15032            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15033        }
15034
15035        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15036            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15037            try {
15038                return doCopyApk(imcs, temp);
15039            } finally {
15040                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15041            }
15042        }
15043
15044        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15045            if (origin.staged) {
15046                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15047                codeFile = origin.file;
15048                resourceFile = origin.file;
15049                return PackageManager.INSTALL_SUCCEEDED;
15050            }
15051
15052            try {
15053                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15054                final File tempDir =
15055                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15056                codeFile = tempDir;
15057                resourceFile = tempDir;
15058            } catch (IOException e) {
15059                Slog.w(TAG, "Failed to create copy file: " + e);
15060                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15061            }
15062
15063            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15064                @Override
15065                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15066                    if (!FileUtils.isValidExtFilename(name)) {
15067                        throw new IllegalArgumentException("Invalid filename: " + name);
15068                    }
15069                    try {
15070                        final File file = new File(codeFile, name);
15071                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15072                                O_RDWR | O_CREAT, 0644);
15073                        Os.chmod(file.getAbsolutePath(), 0644);
15074                        return new ParcelFileDescriptor(fd);
15075                    } catch (ErrnoException e) {
15076                        throw new RemoteException("Failed to open: " + e.getMessage());
15077                    }
15078                }
15079            };
15080
15081            int ret = PackageManager.INSTALL_SUCCEEDED;
15082            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15083            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15084                Slog.e(TAG, "Failed to copy package");
15085                return ret;
15086            }
15087
15088            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15089            NativeLibraryHelper.Handle handle = null;
15090            try {
15091                handle = NativeLibraryHelper.Handle.create(codeFile);
15092                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15093                        abiOverride);
15094            } catch (IOException e) {
15095                Slog.e(TAG, "Copying native libraries failed", e);
15096                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15097            } finally {
15098                IoUtils.closeQuietly(handle);
15099            }
15100
15101            return ret;
15102        }
15103
15104        int doPreInstall(int status) {
15105            if (status != PackageManager.INSTALL_SUCCEEDED) {
15106                cleanUp();
15107            }
15108            return status;
15109        }
15110
15111        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15112            if (status != PackageManager.INSTALL_SUCCEEDED) {
15113                cleanUp();
15114                return false;
15115            }
15116
15117            final File targetDir = codeFile.getParentFile();
15118            final File beforeCodeFile = codeFile;
15119            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15120
15121            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15122            try {
15123                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15124            } catch (ErrnoException e) {
15125                Slog.w(TAG, "Failed to rename", e);
15126                return false;
15127            }
15128
15129            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15130                Slog.w(TAG, "Failed to restorecon");
15131                return false;
15132            }
15133
15134            // Reflect the rename internally
15135            codeFile = afterCodeFile;
15136            resourceFile = afterCodeFile;
15137
15138            // Reflect the rename in scanned details
15139            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15140            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15141                    afterCodeFile, pkg.baseCodePath));
15142            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15143                    afterCodeFile, pkg.splitCodePaths));
15144
15145            // Reflect the rename in app info
15146            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15147            pkg.setApplicationInfoCodePath(pkg.codePath);
15148            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15149            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15150            pkg.setApplicationInfoResourcePath(pkg.codePath);
15151            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15152            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15153
15154            return true;
15155        }
15156
15157        int doPostInstall(int status, int uid) {
15158            if (status != PackageManager.INSTALL_SUCCEEDED) {
15159                cleanUp();
15160            }
15161            return status;
15162        }
15163
15164        @Override
15165        String getCodePath() {
15166            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15167        }
15168
15169        @Override
15170        String getResourcePath() {
15171            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15172        }
15173
15174        private boolean cleanUp() {
15175            if (codeFile == null || !codeFile.exists()) {
15176                return false;
15177            }
15178
15179            removeCodePathLI(codeFile);
15180
15181            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15182                resourceFile.delete();
15183            }
15184
15185            return true;
15186        }
15187
15188        void cleanUpResourcesLI() {
15189            // Try enumerating all code paths before deleting
15190            List<String> allCodePaths = Collections.EMPTY_LIST;
15191            if (codeFile != null && codeFile.exists()) {
15192                try {
15193                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15194                    allCodePaths = pkg.getAllCodePaths();
15195                } catch (PackageParserException e) {
15196                    // Ignored; we tried our best
15197                }
15198            }
15199
15200            cleanUp();
15201            removeDexFiles(allCodePaths, instructionSets);
15202        }
15203
15204        boolean doPostDeleteLI(boolean delete) {
15205            // XXX err, shouldn't we respect the delete flag?
15206            cleanUpResourcesLI();
15207            return true;
15208        }
15209    }
15210
15211    private boolean isAsecExternal(String cid) {
15212        final String asecPath = PackageHelper.getSdFilesystem(cid);
15213        return !asecPath.startsWith(mAsecInternalPath);
15214    }
15215
15216    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15217            PackageManagerException {
15218        if (copyRet < 0) {
15219            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15220                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15221                throw new PackageManagerException(copyRet, message);
15222            }
15223        }
15224    }
15225
15226    /**
15227     * Extract the StorageManagerService "container ID" from the full code path of an
15228     * .apk.
15229     */
15230    static String cidFromCodePath(String fullCodePath) {
15231        int eidx = fullCodePath.lastIndexOf("/");
15232        String subStr1 = fullCodePath.substring(0, eidx);
15233        int sidx = subStr1.lastIndexOf("/");
15234        return subStr1.substring(sidx+1, eidx);
15235    }
15236
15237    /**
15238     * Logic to handle installation of ASEC applications, including copying and
15239     * renaming logic.
15240     */
15241    class AsecInstallArgs extends InstallArgs {
15242        static final String RES_FILE_NAME = "pkg.apk";
15243        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15244
15245        String cid;
15246        String packagePath;
15247        String resourcePath;
15248
15249        /** New install */
15250        AsecInstallArgs(InstallParams params) {
15251            super(params.origin, params.move, params.observer, params.installFlags,
15252                    params.installerPackageName, params.volumeUuid,
15253                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15254                    params.grantedRuntimePermissions,
15255                    params.traceMethod, params.traceCookie, params.certificates,
15256                    params.installReason);
15257        }
15258
15259        /** Existing install */
15260        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15261                        boolean isExternal, boolean isForwardLocked) {
15262            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15263                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15264                    instructionSets, null, null, null, 0, null /*certificates*/,
15265                    PackageManager.INSTALL_REASON_UNKNOWN);
15266            // Hackily pretend we're still looking at a full code path
15267            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15268                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15269            }
15270
15271            // Extract cid from fullCodePath
15272            int eidx = fullCodePath.lastIndexOf("/");
15273            String subStr1 = fullCodePath.substring(0, eidx);
15274            int sidx = subStr1.lastIndexOf("/");
15275            cid = subStr1.substring(sidx+1, eidx);
15276            setMountPath(subStr1);
15277        }
15278
15279        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15280            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15281                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15282                    instructionSets, null, null, null, 0, null /*certificates*/,
15283                    PackageManager.INSTALL_REASON_UNKNOWN);
15284            this.cid = cid;
15285            setMountPath(PackageHelper.getSdDir(cid));
15286        }
15287
15288        void createCopyFile() {
15289            cid = mInstallerService.allocateExternalStageCidLegacy();
15290        }
15291
15292        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15293            if (origin.staged && origin.cid != null) {
15294                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15295                cid = origin.cid;
15296                setMountPath(PackageHelper.getSdDir(cid));
15297                return PackageManager.INSTALL_SUCCEEDED;
15298            }
15299
15300            if (temp) {
15301                createCopyFile();
15302            } else {
15303                /*
15304                 * Pre-emptively destroy the container since it's destroyed if
15305                 * copying fails due to it existing anyway.
15306                 */
15307                PackageHelper.destroySdDir(cid);
15308            }
15309
15310            final String newMountPath = imcs.copyPackageToContainer(
15311                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15312                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15313
15314            if (newMountPath != null) {
15315                setMountPath(newMountPath);
15316                return PackageManager.INSTALL_SUCCEEDED;
15317            } else {
15318                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15319            }
15320        }
15321
15322        @Override
15323        String getCodePath() {
15324            return packagePath;
15325        }
15326
15327        @Override
15328        String getResourcePath() {
15329            return resourcePath;
15330        }
15331
15332        int doPreInstall(int status) {
15333            if (status != PackageManager.INSTALL_SUCCEEDED) {
15334                // Destroy container
15335                PackageHelper.destroySdDir(cid);
15336            } else {
15337                boolean mounted = PackageHelper.isContainerMounted(cid);
15338                if (!mounted) {
15339                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15340                            Process.SYSTEM_UID);
15341                    if (newMountPath != null) {
15342                        setMountPath(newMountPath);
15343                    } else {
15344                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15345                    }
15346                }
15347            }
15348            return status;
15349        }
15350
15351        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15352            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15353            String newMountPath = null;
15354            if (PackageHelper.isContainerMounted(cid)) {
15355                // Unmount the container
15356                if (!PackageHelper.unMountSdDir(cid)) {
15357                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15358                    return false;
15359                }
15360            }
15361            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15362                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15363                        " which might be stale. Will try to clean up.");
15364                // Clean up the stale container and proceed to recreate.
15365                if (!PackageHelper.destroySdDir(newCacheId)) {
15366                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15367                    return false;
15368                }
15369                // Successfully cleaned up stale container. Try to rename again.
15370                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15371                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15372                            + " inspite of cleaning it up.");
15373                    return false;
15374                }
15375            }
15376            if (!PackageHelper.isContainerMounted(newCacheId)) {
15377                Slog.w(TAG, "Mounting container " + newCacheId);
15378                newMountPath = PackageHelper.mountSdDir(newCacheId,
15379                        getEncryptKey(), Process.SYSTEM_UID);
15380            } else {
15381                newMountPath = PackageHelper.getSdDir(newCacheId);
15382            }
15383            if (newMountPath == null) {
15384                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15385                return false;
15386            }
15387            Log.i(TAG, "Succesfully renamed " + cid +
15388                    " to " + newCacheId +
15389                    " at new path: " + newMountPath);
15390            cid = newCacheId;
15391
15392            final File beforeCodeFile = new File(packagePath);
15393            setMountPath(newMountPath);
15394            final File afterCodeFile = new File(packagePath);
15395
15396            // Reflect the rename in scanned details
15397            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15398            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15399                    afterCodeFile, pkg.baseCodePath));
15400            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15401                    afterCodeFile, pkg.splitCodePaths));
15402
15403            // Reflect the rename in app info
15404            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15405            pkg.setApplicationInfoCodePath(pkg.codePath);
15406            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15407            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15408            pkg.setApplicationInfoResourcePath(pkg.codePath);
15409            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15410            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15411
15412            return true;
15413        }
15414
15415        private void setMountPath(String mountPath) {
15416            final File mountFile = new File(mountPath);
15417
15418            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15419            if (monolithicFile.exists()) {
15420                packagePath = monolithicFile.getAbsolutePath();
15421                if (isFwdLocked()) {
15422                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15423                } else {
15424                    resourcePath = packagePath;
15425                }
15426            } else {
15427                packagePath = mountFile.getAbsolutePath();
15428                resourcePath = packagePath;
15429            }
15430        }
15431
15432        int doPostInstall(int status, int uid) {
15433            if (status != PackageManager.INSTALL_SUCCEEDED) {
15434                cleanUp();
15435            } else {
15436                final int groupOwner;
15437                final String protectedFile;
15438                if (isFwdLocked()) {
15439                    groupOwner = UserHandle.getSharedAppGid(uid);
15440                    protectedFile = RES_FILE_NAME;
15441                } else {
15442                    groupOwner = -1;
15443                    protectedFile = null;
15444                }
15445
15446                if (uid < Process.FIRST_APPLICATION_UID
15447                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15448                    Slog.e(TAG, "Failed to finalize " + cid);
15449                    PackageHelper.destroySdDir(cid);
15450                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15451                }
15452
15453                boolean mounted = PackageHelper.isContainerMounted(cid);
15454                if (!mounted) {
15455                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15456                }
15457            }
15458            return status;
15459        }
15460
15461        private void cleanUp() {
15462            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15463
15464            // Destroy secure container
15465            PackageHelper.destroySdDir(cid);
15466        }
15467
15468        private List<String> getAllCodePaths() {
15469            final File codeFile = new File(getCodePath());
15470            if (codeFile != null && codeFile.exists()) {
15471                try {
15472                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15473                    return pkg.getAllCodePaths();
15474                } catch (PackageParserException e) {
15475                    // Ignored; we tried our best
15476                }
15477            }
15478            return Collections.EMPTY_LIST;
15479        }
15480
15481        void cleanUpResourcesLI() {
15482            // Enumerate all code paths before deleting
15483            cleanUpResourcesLI(getAllCodePaths());
15484        }
15485
15486        private void cleanUpResourcesLI(List<String> allCodePaths) {
15487            cleanUp();
15488            removeDexFiles(allCodePaths, instructionSets);
15489        }
15490
15491        String getPackageName() {
15492            return getAsecPackageName(cid);
15493        }
15494
15495        boolean doPostDeleteLI(boolean delete) {
15496            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15497            final List<String> allCodePaths = getAllCodePaths();
15498            boolean mounted = PackageHelper.isContainerMounted(cid);
15499            if (mounted) {
15500                // Unmount first
15501                if (PackageHelper.unMountSdDir(cid)) {
15502                    mounted = false;
15503                }
15504            }
15505            if (!mounted && delete) {
15506                cleanUpResourcesLI(allCodePaths);
15507            }
15508            return !mounted;
15509        }
15510
15511        @Override
15512        int doPreCopy() {
15513            if (isFwdLocked()) {
15514                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15515                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15516                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15517                }
15518            }
15519
15520            return PackageManager.INSTALL_SUCCEEDED;
15521        }
15522
15523        @Override
15524        int doPostCopy(int uid) {
15525            if (isFwdLocked()) {
15526                if (uid < Process.FIRST_APPLICATION_UID
15527                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15528                                RES_FILE_NAME)) {
15529                    Slog.e(TAG, "Failed to finalize " + cid);
15530                    PackageHelper.destroySdDir(cid);
15531                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15532                }
15533            }
15534
15535            return PackageManager.INSTALL_SUCCEEDED;
15536        }
15537    }
15538
15539    /**
15540     * Logic to handle movement of existing installed applications.
15541     */
15542    class MoveInstallArgs extends InstallArgs {
15543        private File codeFile;
15544        private File resourceFile;
15545
15546        /** New install */
15547        MoveInstallArgs(InstallParams params) {
15548            super(params.origin, params.move, params.observer, params.installFlags,
15549                    params.installerPackageName, params.volumeUuid,
15550                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15551                    params.grantedRuntimePermissions,
15552                    params.traceMethod, params.traceCookie, params.certificates,
15553                    params.installReason);
15554        }
15555
15556        int copyApk(IMediaContainerService imcs, boolean temp) {
15557            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15558                    + move.fromUuid + " to " + move.toUuid);
15559            synchronized (mInstaller) {
15560                try {
15561                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15562                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15563                } catch (InstallerException e) {
15564                    Slog.w(TAG, "Failed to move app", e);
15565                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15566                }
15567            }
15568
15569            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15570            resourceFile = codeFile;
15571            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15572
15573            return PackageManager.INSTALL_SUCCEEDED;
15574        }
15575
15576        int doPreInstall(int status) {
15577            if (status != PackageManager.INSTALL_SUCCEEDED) {
15578                cleanUp(move.toUuid);
15579            }
15580            return status;
15581        }
15582
15583        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15584            if (status != PackageManager.INSTALL_SUCCEEDED) {
15585                cleanUp(move.toUuid);
15586                return false;
15587            }
15588
15589            // Reflect the move in app info
15590            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15591            pkg.setApplicationInfoCodePath(pkg.codePath);
15592            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15593            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15594            pkg.setApplicationInfoResourcePath(pkg.codePath);
15595            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15596            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15597
15598            return true;
15599        }
15600
15601        int doPostInstall(int status, int uid) {
15602            if (status == PackageManager.INSTALL_SUCCEEDED) {
15603                cleanUp(move.fromUuid);
15604            } else {
15605                cleanUp(move.toUuid);
15606            }
15607            return status;
15608        }
15609
15610        @Override
15611        String getCodePath() {
15612            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15613        }
15614
15615        @Override
15616        String getResourcePath() {
15617            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15618        }
15619
15620        private boolean cleanUp(String volumeUuid) {
15621            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15622                    move.dataAppName);
15623            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15624            final int[] userIds = sUserManager.getUserIds();
15625            synchronized (mInstallLock) {
15626                // Clean up both app data and code
15627                // All package moves are frozen until finished
15628                for (int userId : userIds) {
15629                    try {
15630                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15631                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15632                    } catch (InstallerException e) {
15633                        Slog.w(TAG, String.valueOf(e));
15634                    }
15635                }
15636                removeCodePathLI(codeFile);
15637            }
15638            return true;
15639        }
15640
15641        void cleanUpResourcesLI() {
15642            throw new UnsupportedOperationException();
15643        }
15644
15645        boolean doPostDeleteLI(boolean delete) {
15646            throw new UnsupportedOperationException();
15647        }
15648    }
15649
15650    static String getAsecPackageName(String packageCid) {
15651        int idx = packageCid.lastIndexOf("-");
15652        if (idx == -1) {
15653            return packageCid;
15654        }
15655        return packageCid.substring(0, idx);
15656    }
15657
15658    // Utility method used to create code paths based on package name and available index.
15659    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15660        String idxStr = "";
15661        int idx = 1;
15662        // Fall back to default value of idx=1 if prefix is not
15663        // part of oldCodePath
15664        if (oldCodePath != null) {
15665            String subStr = oldCodePath;
15666            // Drop the suffix right away
15667            if (suffix != null && subStr.endsWith(suffix)) {
15668                subStr = subStr.substring(0, subStr.length() - suffix.length());
15669            }
15670            // If oldCodePath already contains prefix find out the
15671            // ending index to either increment or decrement.
15672            int sidx = subStr.lastIndexOf(prefix);
15673            if (sidx != -1) {
15674                subStr = subStr.substring(sidx + prefix.length());
15675                if (subStr != null) {
15676                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15677                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15678                    }
15679                    try {
15680                        idx = Integer.parseInt(subStr);
15681                        if (idx <= 1) {
15682                            idx++;
15683                        } else {
15684                            idx--;
15685                        }
15686                    } catch(NumberFormatException e) {
15687                    }
15688                }
15689            }
15690        }
15691        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15692        return prefix + idxStr;
15693    }
15694
15695    private File getNextCodePath(File targetDir, String packageName) {
15696        File result;
15697        SecureRandom random = new SecureRandom();
15698        byte[] bytes = new byte[16];
15699        do {
15700            random.nextBytes(bytes);
15701            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15702            result = new File(targetDir, packageName + "-" + suffix);
15703        } while (result.exists());
15704        return result;
15705    }
15706
15707    // Utility method that returns the relative package path with respect
15708    // to the installation directory. Like say for /data/data/com.test-1.apk
15709    // string com.test-1 is returned.
15710    static String deriveCodePathName(String codePath) {
15711        if (codePath == null) {
15712            return null;
15713        }
15714        final File codeFile = new File(codePath);
15715        final String name = codeFile.getName();
15716        if (codeFile.isDirectory()) {
15717            return name;
15718        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15719            final int lastDot = name.lastIndexOf('.');
15720            return name.substring(0, lastDot);
15721        } else {
15722            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15723            return null;
15724        }
15725    }
15726
15727    static class PackageInstalledInfo {
15728        String name;
15729        int uid;
15730        // The set of users that originally had this package installed.
15731        int[] origUsers;
15732        // The set of users that now have this package installed.
15733        int[] newUsers;
15734        PackageParser.Package pkg;
15735        int returnCode;
15736        String returnMsg;
15737        PackageRemovedInfo removedInfo;
15738        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15739
15740        public void setError(int code, String msg) {
15741            setReturnCode(code);
15742            setReturnMessage(msg);
15743            Slog.w(TAG, msg);
15744        }
15745
15746        public void setError(String msg, PackageParserException e) {
15747            setReturnCode(e.error);
15748            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15749            Slog.w(TAG, msg, e);
15750        }
15751
15752        public void setError(String msg, PackageManagerException e) {
15753            returnCode = e.error;
15754            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15755            Slog.w(TAG, msg, e);
15756        }
15757
15758        public void setReturnCode(int returnCode) {
15759            this.returnCode = returnCode;
15760            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15761            for (int i = 0; i < childCount; i++) {
15762                addedChildPackages.valueAt(i).returnCode = returnCode;
15763            }
15764        }
15765
15766        private void setReturnMessage(String returnMsg) {
15767            this.returnMsg = returnMsg;
15768            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15769            for (int i = 0; i < childCount; i++) {
15770                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15771            }
15772        }
15773
15774        // In some error cases we want to convey more info back to the observer
15775        String origPackage;
15776        String origPermission;
15777    }
15778
15779    /*
15780     * Install a non-existing package.
15781     */
15782    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15783            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15784            PackageInstalledInfo res, int installReason) {
15785        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15786
15787        // Remember this for later, in case we need to rollback this install
15788        String pkgName = pkg.packageName;
15789
15790        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15791
15792        synchronized(mPackages) {
15793            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15794            if (renamedPackage != null) {
15795                // A package with the same name is already installed, though
15796                // it has been renamed to an older name.  The package we
15797                // are trying to install should be installed as an update to
15798                // the existing one, but that has not been requested, so bail.
15799                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15800                        + " without first uninstalling package running as "
15801                        + renamedPackage);
15802                return;
15803            }
15804            if (mPackages.containsKey(pkgName)) {
15805                // Don't allow installation over an existing package with the same name.
15806                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15807                        + " without first uninstalling.");
15808                return;
15809            }
15810        }
15811
15812        try {
15813            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15814                    System.currentTimeMillis(), user);
15815
15816            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15817
15818            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15819                prepareAppDataAfterInstallLIF(newPackage);
15820
15821            } else {
15822                // Remove package from internal structures, but keep around any
15823                // data that might have already existed
15824                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15825                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15826            }
15827        } catch (PackageManagerException e) {
15828            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15829        }
15830
15831        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15832    }
15833
15834    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15835        // Can't rotate keys during boot or if sharedUser.
15836        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15837                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15838            return false;
15839        }
15840        // app is using upgradeKeySets; make sure all are valid
15841        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15842        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15843        for (int i = 0; i < upgradeKeySets.length; i++) {
15844            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15845                Slog.wtf(TAG, "Package "
15846                         + (oldPs.name != null ? oldPs.name : "<null>")
15847                         + " contains upgrade-key-set reference to unknown key-set: "
15848                         + upgradeKeySets[i]
15849                         + " reverting to signatures check.");
15850                return false;
15851            }
15852        }
15853        return true;
15854    }
15855
15856    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15857        // Upgrade keysets are being used.  Determine if new package has a superset of the
15858        // required keys.
15859        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15860        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15861        for (int i = 0; i < upgradeKeySets.length; i++) {
15862            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15863            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15864                return true;
15865            }
15866        }
15867        return false;
15868    }
15869
15870    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15871        try (DigestInputStream digestStream =
15872                new DigestInputStream(new FileInputStream(file), digest)) {
15873            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15874        }
15875    }
15876
15877    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15878            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15879            int installReason) {
15880        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15881
15882        final PackageParser.Package oldPackage;
15883        final String pkgName = pkg.packageName;
15884        final int[] allUsers;
15885        final int[] installedUsers;
15886
15887        synchronized(mPackages) {
15888            oldPackage = mPackages.get(pkgName);
15889            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15890
15891            // don't allow upgrade to target a release SDK from a pre-release SDK
15892            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15893                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15894            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15895                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15896            if (oldTargetsPreRelease
15897                    && !newTargetsPreRelease
15898                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15899                Slog.w(TAG, "Can't install package targeting released sdk");
15900                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15901                return;
15902            }
15903
15904            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15905
15906            // don't allow an upgrade from full to ephemeral
15907            if (isInstantApp && !ps.getInstantApp(user.getIdentifier())) {
15908                // can't downgrade from full to instant
15909                Slog.w(TAG, "Can't replace app with instant app: " + pkgName);
15910                res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15911                return;
15912            }
15913
15914            // verify signatures are valid
15915            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15916                if (!checkUpgradeKeySetLP(ps, pkg)) {
15917                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15918                            "New package not signed by keys specified by upgrade-keysets: "
15919                                    + pkgName);
15920                    return;
15921                }
15922            } else {
15923                // default to original signature matching
15924                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15925                        != PackageManager.SIGNATURE_MATCH) {
15926                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15927                            "New package has a different signature: " + pkgName);
15928                    return;
15929                }
15930            }
15931
15932            // don't allow a system upgrade unless the upgrade hash matches
15933            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15934                byte[] digestBytes = null;
15935                try {
15936                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15937                    updateDigest(digest, new File(pkg.baseCodePath));
15938                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15939                        for (String path : pkg.splitCodePaths) {
15940                            updateDigest(digest, new File(path));
15941                        }
15942                    }
15943                    digestBytes = digest.digest();
15944                } catch (NoSuchAlgorithmException | IOException e) {
15945                    res.setError(INSTALL_FAILED_INVALID_APK,
15946                            "Could not compute hash: " + pkgName);
15947                    return;
15948                }
15949                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15950                    res.setError(INSTALL_FAILED_INVALID_APK,
15951                            "New package fails restrict-update check: " + pkgName);
15952                    return;
15953                }
15954                // retain upgrade restriction
15955                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15956            }
15957
15958            // Check for shared user id changes
15959            String invalidPackageName =
15960                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15961            if (invalidPackageName != null) {
15962                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15963                        "Package " + invalidPackageName + " tried to change user "
15964                                + oldPackage.mSharedUserId);
15965                return;
15966            }
15967
15968            // In case of rollback, remember per-user/profile install state
15969            allUsers = sUserManager.getUserIds();
15970            installedUsers = ps.queryInstalledUsers(allUsers, true);
15971        }
15972
15973        // Update what is removed
15974        res.removedInfo = new PackageRemovedInfo();
15975        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15976        res.removedInfo.removedPackage = oldPackage.packageName;
15977        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15978        res.removedInfo.isUpdate = true;
15979        res.removedInfo.origUsers = installedUsers;
15980        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15981        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15982        for (int i = 0; i < installedUsers.length; i++) {
15983            final int userId = installedUsers[i];
15984            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15985        }
15986
15987        final int childCount = (oldPackage.childPackages != null)
15988                ? oldPackage.childPackages.size() : 0;
15989        for (int i = 0; i < childCount; i++) {
15990            boolean childPackageUpdated = false;
15991            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15992            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15993            if (res.addedChildPackages != null) {
15994                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15995                if (childRes != null) {
15996                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15997                    childRes.removedInfo.removedPackage = childPkg.packageName;
15998                    childRes.removedInfo.isUpdate = true;
15999                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16000                    childPackageUpdated = true;
16001                }
16002            }
16003            if (!childPackageUpdated) {
16004                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
16005                childRemovedRes.removedPackage = childPkg.packageName;
16006                childRemovedRes.isUpdate = false;
16007                childRemovedRes.dataRemoved = true;
16008                synchronized (mPackages) {
16009                    if (childPs != null) {
16010                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16011                    }
16012                }
16013                if (res.removedInfo.removedChildPackages == null) {
16014                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16015                }
16016                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16017            }
16018        }
16019
16020        boolean sysPkg = (isSystemApp(oldPackage));
16021        if (sysPkg) {
16022            // Set the system/privileged flags as needed
16023            final boolean privileged =
16024                    (oldPackage.applicationInfo.privateFlags
16025                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16026            final int systemPolicyFlags = policyFlags
16027                    | PackageParser.PARSE_IS_SYSTEM
16028                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16029
16030            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16031                    user, allUsers, installerPackageName, res, installReason);
16032        } else {
16033            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16034                    user, allUsers, installerPackageName, res, installReason);
16035        }
16036    }
16037
16038    public List<String> getPreviousCodePaths(String packageName) {
16039        final PackageSetting ps = mSettings.mPackages.get(packageName);
16040        final List<String> result = new ArrayList<String>();
16041        if (ps != null && ps.oldCodePaths != null) {
16042            result.addAll(ps.oldCodePaths);
16043        }
16044        return result;
16045    }
16046
16047    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16048            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16049            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16050            int installReason) {
16051        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16052                + deletedPackage);
16053
16054        String pkgName = deletedPackage.packageName;
16055        boolean deletedPkg = true;
16056        boolean addedPkg = false;
16057        boolean updatedSettings = false;
16058        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16059        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16060                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16061
16062        final long origUpdateTime = (pkg.mExtras != null)
16063                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16064
16065        // First delete the existing package while retaining the data directory
16066        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16067                res.removedInfo, true, pkg)) {
16068            // If the existing package wasn't successfully deleted
16069            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16070            deletedPkg = false;
16071        } else {
16072            // Successfully deleted the old package; proceed with replace.
16073
16074            // If deleted package lived in a container, give users a chance to
16075            // relinquish resources before killing.
16076            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16077                if (DEBUG_INSTALL) {
16078                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16079                }
16080                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16081                final ArrayList<String> pkgList = new ArrayList<String>(1);
16082                pkgList.add(deletedPackage.applicationInfo.packageName);
16083                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16084            }
16085
16086            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16087                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16088            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16089
16090            try {
16091                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16092                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16093                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16094                        installReason);
16095
16096                // Update the in-memory copy of the previous code paths.
16097                PackageSetting ps = mSettings.mPackages.get(pkgName);
16098                if (!killApp) {
16099                    if (ps.oldCodePaths == null) {
16100                        ps.oldCodePaths = new ArraySet<>();
16101                    }
16102                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16103                    if (deletedPackage.splitCodePaths != null) {
16104                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16105                    }
16106                } else {
16107                    ps.oldCodePaths = null;
16108                }
16109                if (ps.childPackageNames != null) {
16110                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16111                        final String childPkgName = ps.childPackageNames.get(i);
16112                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16113                        childPs.oldCodePaths = ps.oldCodePaths;
16114                    }
16115                }
16116                // set instant app status, but, only if it's explicitly specified
16117                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16118                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16119                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16120                prepareAppDataAfterInstallLIF(newPackage);
16121                addedPkg = true;
16122            } catch (PackageManagerException e) {
16123                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16124            }
16125        }
16126
16127        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16128            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16129
16130            // Revert all internal state mutations and added folders for the failed install
16131            if (addedPkg) {
16132                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16133                        res.removedInfo, true, null);
16134            }
16135
16136            // Restore the old package
16137            if (deletedPkg) {
16138                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16139                File restoreFile = new File(deletedPackage.codePath);
16140                // Parse old package
16141                boolean oldExternal = isExternal(deletedPackage);
16142                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16143                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16144                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16145                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16146                try {
16147                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16148                            null);
16149                } catch (PackageManagerException e) {
16150                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16151                            + e.getMessage());
16152                    return;
16153                }
16154
16155                synchronized (mPackages) {
16156                    // Ensure the installer package name up to date
16157                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16158
16159                    // Update permissions for restored package
16160                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16161
16162                    mSettings.writeLPr();
16163                }
16164
16165                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16166            }
16167        } else {
16168            synchronized (mPackages) {
16169                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16170                if (ps != null) {
16171                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16172                    if (res.removedInfo.removedChildPackages != null) {
16173                        final int childCount = res.removedInfo.removedChildPackages.size();
16174                        // Iterate in reverse as we may modify the collection
16175                        for (int i = childCount - 1; i >= 0; i--) {
16176                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16177                            if (res.addedChildPackages.containsKey(childPackageName)) {
16178                                res.removedInfo.removedChildPackages.removeAt(i);
16179                            } else {
16180                                PackageRemovedInfo childInfo = res.removedInfo
16181                                        .removedChildPackages.valueAt(i);
16182                                childInfo.removedForAllUsers = mPackages.get(
16183                                        childInfo.removedPackage) == null;
16184                            }
16185                        }
16186                    }
16187                }
16188            }
16189        }
16190    }
16191
16192    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16193            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16194            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16195            int installReason) {
16196        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16197                + ", old=" + deletedPackage);
16198
16199        final boolean disabledSystem;
16200
16201        // Remove existing system package
16202        removePackageLI(deletedPackage, true);
16203
16204        synchronized (mPackages) {
16205            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16206        }
16207        if (!disabledSystem) {
16208            // We didn't need to disable the .apk as a current system package,
16209            // which means we are replacing another update that is already
16210            // installed.  We need to make sure to delete the older one's .apk.
16211            res.removedInfo.args = createInstallArgsForExisting(0,
16212                    deletedPackage.applicationInfo.getCodePath(),
16213                    deletedPackage.applicationInfo.getResourcePath(),
16214                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16215        } else {
16216            res.removedInfo.args = null;
16217        }
16218
16219        // Successfully disabled the old package. Now proceed with re-installation
16220        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16221                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16222        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16223
16224        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16225        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16226                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16227
16228        PackageParser.Package newPackage = null;
16229        try {
16230            // Add the package to the internal data structures
16231            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16232
16233            // Set the update and install times
16234            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16235            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16236                    System.currentTimeMillis());
16237
16238            // Update the package dynamic state if succeeded
16239            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16240                // Now that the install succeeded make sure we remove data
16241                // directories for any child package the update removed.
16242                final int deletedChildCount = (deletedPackage.childPackages != null)
16243                        ? deletedPackage.childPackages.size() : 0;
16244                final int newChildCount = (newPackage.childPackages != null)
16245                        ? newPackage.childPackages.size() : 0;
16246                for (int i = 0; i < deletedChildCount; i++) {
16247                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16248                    boolean childPackageDeleted = true;
16249                    for (int j = 0; j < newChildCount; j++) {
16250                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16251                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16252                            childPackageDeleted = false;
16253                            break;
16254                        }
16255                    }
16256                    if (childPackageDeleted) {
16257                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16258                                deletedChildPkg.packageName);
16259                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16260                            PackageRemovedInfo removedChildRes = res.removedInfo
16261                                    .removedChildPackages.get(deletedChildPkg.packageName);
16262                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16263                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16264                        }
16265                    }
16266                }
16267
16268                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16269                        installReason);
16270                prepareAppDataAfterInstallLIF(newPackage);
16271            }
16272        } catch (PackageManagerException e) {
16273            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16274            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16275        }
16276
16277        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16278            // Re installation failed. Restore old information
16279            // Remove new pkg information
16280            if (newPackage != null) {
16281                removeInstalledPackageLI(newPackage, true);
16282            }
16283            // Add back the old system package
16284            try {
16285                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16286            } catch (PackageManagerException e) {
16287                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16288            }
16289
16290            synchronized (mPackages) {
16291                if (disabledSystem) {
16292                    enableSystemPackageLPw(deletedPackage);
16293                }
16294
16295                // Ensure the installer package name up to date
16296                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16297
16298                // Update permissions for restored package
16299                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16300
16301                mSettings.writeLPr();
16302            }
16303
16304            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16305                    + " after failed upgrade");
16306        }
16307    }
16308
16309    /**
16310     * Checks whether the parent or any of the child packages have a change shared
16311     * user. For a package to be a valid update the shred users of the parent and
16312     * the children should match. We may later support changing child shared users.
16313     * @param oldPkg The updated package.
16314     * @param newPkg The update package.
16315     * @return The shared user that change between the versions.
16316     */
16317    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16318            PackageParser.Package newPkg) {
16319        // Check parent shared user
16320        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16321            return newPkg.packageName;
16322        }
16323        // Check child shared users
16324        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16325        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16326        for (int i = 0; i < newChildCount; i++) {
16327            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16328            // If this child was present, did it have the same shared user?
16329            for (int j = 0; j < oldChildCount; j++) {
16330                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16331                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16332                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16333                    return newChildPkg.packageName;
16334                }
16335            }
16336        }
16337        return null;
16338    }
16339
16340    private void removeNativeBinariesLI(PackageSetting ps) {
16341        // Remove the lib path for the parent package
16342        if (ps != null) {
16343            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16344            // Remove the lib path for the child packages
16345            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16346            for (int i = 0; i < childCount; i++) {
16347                PackageSetting childPs = null;
16348                synchronized (mPackages) {
16349                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16350                }
16351                if (childPs != null) {
16352                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16353                            .legacyNativeLibraryPathString);
16354                }
16355            }
16356        }
16357    }
16358
16359    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16360        // Enable the parent package
16361        mSettings.enableSystemPackageLPw(pkg.packageName);
16362        // Enable the child packages
16363        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16364        for (int i = 0; i < childCount; i++) {
16365            PackageParser.Package childPkg = pkg.childPackages.get(i);
16366            mSettings.enableSystemPackageLPw(childPkg.packageName);
16367        }
16368    }
16369
16370    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16371            PackageParser.Package newPkg) {
16372        // Disable the parent package (parent always replaced)
16373        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16374        // Disable the child packages
16375        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16376        for (int i = 0; i < childCount; i++) {
16377            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16378            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16379            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16380        }
16381        return disabled;
16382    }
16383
16384    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16385            String installerPackageName) {
16386        // Enable the parent package
16387        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16388        // Enable the child packages
16389        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16390        for (int i = 0; i < childCount; i++) {
16391            PackageParser.Package childPkg = pkg.childPackages.get(i);
16392            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16393        }
16394    }
16395
16396    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16397        // Collect all used permissions in the UID
16398        ArraySet<String> usedPermissions = new ArraySet<>();
16399        final int packageCount = su.packages.size();
16400        for (int i = 0; i < packageCount; i++) {
16401            PackageSetting ps = su.packages.valueAt(i);
16402            if (ps.pkg == null) {
16403                continue;
16404            }
16405            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16406            for (int j = 0; j < requestedPermCount; j++) {
16407                String permission = ps.pkg.requestedPermissions.get(j);
16408                BasePermission bp = mSettings.mPermissions.get(permission);
16409                if (bp != null) {
16410                    usedPermissions.add(permission);
16411                }
16412            }
16413        }
16414
16415        PermissionsState permissionsState = su.getPermissionsState();
16416        // Prune install permissions
16417        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16418        final int installPermCount = installPermStates.size();
16419        for (int i = installPermCount - 1; i >= 0;  i--) {
16420            PermissionState permissionState = installPermStates.get(i);
16421            if (!usedPermissions.contains(permissionState.getName())) {
16422                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16423                if (bp != null) {
16424                    permissionsState.revokeInstallPermission(bp);
16425                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16426                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16427                }
16428            }
16429        }
16430
16431        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16432
16433        // Prune runtime permissions
16434        for (int userId : allUserIds) {
16435            List<PermissionState> runtimePermStates = permissionsState
16436                    .getRuntimePermissionStates(userId);
16437            final int runtimePermCount = runtimePermStates.size();
16438            for (int i = runtimePermCount - 1; i >= 0; i--) {
16439                PermissionState permissionState = runtimePermStates.get(i);
16440                if (!usedPermissions.contains(permissionState.getName())) {
16441                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16442                    if (bp != null) {
16443                        permissionsState.revokeRuntimePermission(bp, userId);
16444                        permissionsState.updatePermissionFlags(bp, userId,
16445                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16446                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16447                                runtimePermissionChangedUserIds, userId);
16448                    }
16449                }
16450            }
16451        }
16452
16453        return runtimePermissionChangedUserIds;
16454    }
16455
16456    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16457            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16458        // Update the parent package setting
16459        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16460                res, user, installReason);
16461        // Update the child packages setting
16462        final int childCount = (newPackage.childPackages != null)
16463                ? newPackage.childPackages.size() : 0;
16464        for (int i = 0; i < childCount; i++) {
16465            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16466            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16467            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16468                    childRes.origUsers, childRes, user, installReason);
16469        }
16470    }
16471
16472    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16473            String installerPackageName, int[] allUsers, int[] installedForUsers,
16474            PackageInstalledInfo res, UserHandle user, int installReason) {
16475        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16476
16477        String pkgName = newPackage.packageName;
16478        synchronized (mPackages) {
16479            //write settings. the installStatus will be incomplete at this stage.
16480            //note that the new package setting would have already been
16481            //added to mPackages. It hasn't been persisted yet.
16482            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16483            // TODO: Remove this write? It's also written at the end of this method
16484            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16485            mSettings.writeLPr();
16486            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16487        }
16488
16489        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16490        synchronized (mPackages) {
16491            updatePermissionsLPw(newPackage.packageName, newPackage,
16492                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16493                            ? UPDATE_PERMISSIONS_ALL : 0));
16494            // For system-bundled packages, we assume that installing an upgraded version
16495            // of the package implies that the user actually wants to run that new code,
16496            // so we enable the package.
16497            PackageSetting ps = mSettings.mPackages.get(pkgName);
16498            final int userId = user.getIdentifier();
16499            if (ps != null) {
16500                if (isSystemApp(newPackage)) {
16501                    if (DEBUG_INSTALL) {
16502                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16503                    }
16504                    // Enable system package for requested users
16505                    if (res.origUsers != null) {
16506                        for (int origUserId : res.origUsers) {
16507                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16508                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16509                                        origUserId, installerPackageName);
16510                            }
16511                        }
16512                    }
16513                    // Also convey the prior install/uninstall state
16514                    if (allUsers != null && installedForUsers != null) {
16515                        for (int currentUserId : allUsers) {
16516                            final boolean installed = ArrayUtils.contains(
16517                                    installedForUsers, currentUserId);
16518                            if (DEBUG_INSTALL) {
16519                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16520                            }
16521                            ps.setInstalled(installed, currentUserId);
16522                        }
16523                        // these install state changes will be persisted in the
16524                        // upcoming call to mSettings.writeLPr().
16525                    }
16526                }
16527                // It's implied that when a user requests installation, they want the app to be
16528                // installed and enabled.
16529                if (userId != UserHandle.USER_ALL) {
16530                    ps.setInstalled(true, userId);
16531                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16532                }
16533
16534                // When replacing an existing package, preserve the original install reason for all
16535                // users that had the package installed before.
16536                final Set<Integer> previousUserIds = new ArraySet<>();
16537                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16538                    final int installReasonCount = res.removedInfo.installReasons.size();
16539                    for (int i = 0; i < installReasonCount; i++) {
16540                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16541                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16542                        ps.setInstallReason(previousInstallReason, previousUserId);
16543                        previousUserIds.add(previousUserId);
16544                    }
16545                }
16546
16547                // Set install reason for users that are having the package newly installed.
16548                if (userId == UserHandle.USER_ALL) {
16549                    for (int currentUserId : sUserManager.getUserIds()) {
16550                        if (!previousUserIds.contains(currentUserId)) {
16551                            ps.setInstallReason(installReason, currentUserId);
16552                        }
16553                    }
16554                } else if (!previousUserIds.contains(userId)) {
16555                    ps.setInstallReason(installReason, userId);
16556                }
16557                mSettings.writeKernelMappingLPr(ps);
16558            }
16559            res.name = pkgName;
16560            res.uid = newPackage.applicationInfo.uid;
16561            res.pkg = newPackage;
16562            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16563            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16564            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16565            //to update install status
16566            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16567            mSettings.writeLPr();
16568            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16569        }
16570
16571        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16572    }
16573
16574    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16575        try {
16576            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16577            installPackageLI(args, res);
16578        } finally {
16579            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16580        }
16581    }
16582
16583    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16584        final int installFlags = args.installFlags;
16585        final String installerPackageName = args.installerPackageName;
16586        final String volumeUuid = args.volumeUuid;
16587        final File tmpPackageFile = new File(args.getCodePath());
16588        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16589        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16590                || (args.volumeUuid != null));
16591        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16592        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16593        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16594        boolean replace = false;
16595        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16596        if (args.move != null) {
16597            // moving a complete application; perform an initial scan on the new install location
16598            scanFlags |= SCAN_INITIAL;
16599        }
16600        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16601            scanFlags |= SCAN_DONT_KILL_APP;
16602        }
16603        if (instantApp) {
16604            scanFlags |= SCAN_AS_INSTANT_APP;
16605        }
16606        if (fullApp) {
16607            scanFlags |= SCAN_AS_FULL_APP;
16608        }
16609
16610        // Result object to be returned
16611        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16612
16613        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16614
16615        // Sanity check
16616        if (instantApp && (forwardLocked || onExternal)) {
16617            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16618                    + " external=" + onExternal);
16619            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16620            return;
16621        }
16622
16623        // Retrieve PackageSettings and parse package
16624        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16625                | PackageParser.PARSE_ENFORCE_CODE
16626                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16627                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16628                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16629                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16630        PackageParser pp = new PackageParser();
16631        pp.setSeparateProcesses(mSeparateProcesses);
16632        pp.setDisplayMetrics(mMetrics);
16633
16634        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16635        final PackageParser.Package pkg;
16636        try {
16637            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16638        } catch (PackageParserException e) {
16639            res.setError("Failed parse during installPackageLI", e);
16640            return;
16641        } finally {
16642            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16643        }
16644
16645//        // Ephemeral apps must have target SDK >= O.
16646//        // TODO: Update conditional and error message when O gets locked down
16647//        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16648//            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
16649//                    "Ephemeral apps must have target SDK version of at least O");
16650//            return;
16651//        }
16652
16653        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16654            // Static shared libraries have synthetic package names
16655            renameStaticSharedLibraryPackage(pkg);
16656
16657            // No static shared libs on external storage
16658            if (onExternal) {
16659                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16660                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16661                        "Packages declaring static-shared libs cannot be updated");
16662                return;
16663            }
16664        }
16665
16666        // If we are installing a clustered package add results for the children
16667        if (pkg.childPackages != null) {
16668            synchronized (mPackages) {
16669                final int childCount = pkg.childPackages.size();
16670                for (int i = 0; i < childCount; i++) {
16671                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16672                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16673                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16674                    childRes.pkg = childPkg;
16675                    childRes.name = childPkg.packageName;
16676                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16677                    if (childPs != null) {
16678                        childRes.origUsers = childPs.queryInstalledUsers(
16679                                sUserManager.getUserIds(), true);
16680                    }
16681                    if ((mPackages.containsKey(childPkg.packageName))) {
16682                        childRes.removedInfo = new PackageRemovedInfo();
16683                        childRes.removedInfo.removedPackage = childPkg.packageName;
16684                    }
16685                    if (res.addedChildPackages == null) {
16686                        res.addedChildPackages = new ArrayMap<>();
16687                    }
16688                    res.addedChildPackages.put(childPkg.packageName, childRes);
16689                }
16690            }
16691        }
16692
16693        // If package doesn't declare API override, mark that we have an install
16694        // time CPU ABI override.
16695        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16696            pkg.cpuAbiOverride = args.abiOverride;
16697        }
16698
16699        String pkgName = res.name = pkg.packageName;
16700        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16701            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16702                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16703                return;
16704            }
16705        }
16706
16707        try {
16708            // either use what we've been given or parse directly from the APK
16709            if (args.certificates != null) {
16710                try {
16711                    PackageParser.populateCertificates(pkg, args.certificates);
16712                } catch (PackageParserException e) {
16713                    // there was something wrong with the certificates we were given;
16714                    // try to pull them from the APK
16715                    PackageParser.collectCertificates(pkg, parseFlags);
16716                }
16717            } else {
16718                PackageParser.collectCertificates(pkg, parseFlags);
16719            }
16720        } catch (PackageParserException e) {
16721            res.setError("Failed collect during installPackageLI", e);
16722            return;
16723        }
16724
16725        // Get rid of all references to package scan path via parser.
16726        pp = null;
16727        String oldCodePath = null;
16728        boolean systemApp = false;
16729        synchronized (mPackages) {
16730            // Check if installing already existing package
16731            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16732                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16733                if (pkg.mOriginalPackages != null
16734                        && pkg.mOriginalPackages.contains(oldName)
16735                        && mPackages.containsKey(oldName)) {
16736                    // This package is derived from an original package,
16737                    // and this device has been updating from that original
16738                    // name.  We must continue using the original name, so
16739                    // rename the new package here.
16740                    pkg.setPackageName(oldName);
16741                    pkgName = pkg.packageName;
16742                    replace = true;
16743                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16744                            + oldName + " pkgName=" + pkgName);
16745                } else if (mPackages.containsKey(pkgName)) {
16746                    // This package, under its official name, already exists
16747                    // on the device; we should replace it.
16748                    replace = true;
16749                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16750                }
16751
16752                // Child packages are installed through the parent package
16753                if (pkg.parentPackage != null) {
16754                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16755                            "Package " + pkg.packageName + " is child of package "
16756                                    + pkg.parentPackage.parentPackage + ". Child packages "
16757                                    + "can be updated only through the parent package.");
16758                    return;
16759                }
16760
16761                if (replace) {
16762                    // Prevent apps opting out from runtime permissions
16763                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16764                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16765                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16766                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16767                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16768                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16769                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16770                                        + " doesn't support runtime permissions but the old"
16771                                        + " target SDK " + oldTargetSdk + " does.");
16772                        return;
16773                    }
16774
16775                    // Prevent installing of child packages
16776                    if (oldPackage.parentPackage != null) {
16777                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16778                                "Package " + pkg.packageName + " is child of package "
16779                                        + oldPackage.parentPackage + ". Child packages "
16780                                        + "can be updated only through the parent package.");
16781                        return;
16782                    }
16783                }
16784            }
16785
16786            PackageSetting ps = mSettings.mPackages.get(pkgName);
16787            if (ps != null) {
16788                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16789
16790                // Static shared libs have same package with different versions where
16791                // we internally use a synthetic package name to allow multiple versions
16792                // of the same package, therefore we need to compare signatures against
16793                // the package setting for the latest library version.
16794                PackageSetting signatureCheckPs = ps;
16795                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16796                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16797                    if (libraryEntry != null) {
16798                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16799                    }
16800                }
16801
16802                // Quick sanity check that we're signed correctly if updating;
16803                // we'll check this again later when scanning, but we want to
16804                // bail early here before tripping over redefined permissions.
16805                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16806                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16807                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16808                                + pkg.packageName + " upgrade keys do not match the "
16809                                + "previously installed version");
16810                        return;
16811                    }
16812                } else {
16813                    try {
16814                        verifySignaturesLP(signatureCheckPs, pkg);
16815                    } catch (PackageManagerException e) {
16816                        res.setError(e.error, e.getMessage());
16817                        return;
16818                    }
16819                }
16820
16821                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16822                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16823                    systemApp = (ps.pkg.applicationInfo.flags &
16824                            ApplicationInfo.FLAG_SYSTEM) != 0;
16825                }
16826                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16827            }
16828
16829            // Check whether the newly-scanned package wants to define an already-defined perm
16830            int N = pkg.permissions.size();
16831            for (int i = N-1; i >= 0; i--) {
16832                PackageParser.Permission perm = pkg.permissions.get(i);
16833                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16834                if (bp != null) {
16835                    // If the defining package is signed with our cert, it's okay.  This
16836                    // also includes the "updating the same package" case, of course.
16837                    // "updating same package" could also involve key-rotation.
16838                    final boolean sigsOk;
16839                    if (bp.sourcePackage.equals(pkg.packageName)
16840                            && (bp.packageSetting instanceof PackageSetting)
16841                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16842                                    scanFlags))) {
16843                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16844                    } else {
16845                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16846                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16847                    }
16848                    if (!sigsOk) {
16849                        // If the owning package is the system itself, we log but allow
16850                        // install to proceed; we fail the install on all other permission
16851                        // redefinitions.
16852                        if (!bp.sourcePackage.equals("android")) {
16853                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16854                                    + pkg.packageName + " attempting to redeclare permission "
16855                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16856                            res.origPermission = perm.info.name;
16857                            res.origPackage = bp.sourcePackage;
16858                            return;
16859                        } else {
16860                            Slog.w(TAG, "Package " + pkg.packageName
16861                                    + " attempting to redeclare system permission "
16862                                    + perm.info.name + "; ignoring new declaration");
16863                            pkg.permissions.remove(i);
16864                        }
16865                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16866                        // Prevent apps to change protection level to dangerous from any other
16867                        // type as this would allow a privilege escalation where an app adds a
16868                        // normal/signature permission in other app's group and later redefines
16869                        // it as dangerous leading to the group auto-grant.
16870                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16871                                == PermissionInfo.PROTECTION_DANGEROUS) {
16872                            if (bp != null && !bp.isRuntime()) {
16873                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16874                                        + "non-runtime permission " + perm.info.name
16875                                        + " to runtime; keeping old protection level");
16876                                perm.info.protectionLevel = bp.protectionLevel;
16877                            }
16878                        }
16879                    }
16880                }
16881            }
16882        }
16883
16884        if (systemApp) {
16885            if (onExternal) {
16886                // Abort update; system app can't be replaced with app on sdcard
16887                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16888                        "Cannot install updates to system apps on sdcard");
16889                return;
16890            } else if (instantApp) {
16891                // Abort update; system app can't be replaced with an instant app
16892                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16893                        "Cannot update a system app with an instant app");
16894                return;
16895            }
16896        }
16897
16898        if (args.move != null) {
16899            // We did an in-place move, so dex is ready to roll
16900            scanFlags |= SCAN_NO_DEX;
16901            scanFlags |= SCAN_MOVE;
16902
16903            synchronized (mPackages) {
16904                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16905                if (ps == null) {
16906                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16907                            "Missing settings for moved package " + pkgName);
16908                }
16909
16910                // We moved the entire application as-is, so bring over the
16911                // previously derived ABI information.
16912                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16913                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16914            }
16915
16916        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16917            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16918            scanFlags |= SCAN_NO_DEX;
16919
16920            try {
16921                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16922                    args.abiOverride : pkg.cpuAbiOverride);
16923                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16924                        true /*extractLibs*/, mAppLib32InstallDir);
16925            } catch (PackageManagerException pme) {
16926                Slog.e(TAG, "Error deriving application ABI", pme);
16927                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16928                return;
16929            }
16930
16931            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16932            // Do not run PackageDexOptimizer through the local performDexOpt
16933            // method because `pkg` may not be in `mPackages` yet.
16934            //
16935            // Also, don't fail application installs if the dexopt step fails.
16936            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16937                    null /* instructionSets */, false /* checkProfiles */,
16938                    getCompilerFilterForReason(REASON_INSTALL),
16939                    getOrCreateCompilerPackageStats(pkg));
16940            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16941
16942            // Notify BackgroundDexOptJobService that the package has been changed.
16943            // If this is an update of a package which used to fail to compile,
16944            // BDOS will remove it from its blacklist.
16945            // TODO: Layering violation
16946            BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName);
16947        }
16948
16949        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16950            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16951            return;
16952        }
16953
16954        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16955
16956        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16957                "installPackageLI")) {
16958            if (replace) {
16959                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16960                    // Static libs have a synthetic package name containing the version
16961                    // and cannot be updated as an update would get a new package name,
16962                    // unless this is the exact same version code which is useful for
16963                    // development.
16964                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16965                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16966                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16967                                + "static-shared libs cannot be updated");
16968                        return;
16969                    }
16970                }
16971                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16972                        installerPackageName, res, args.installReason);
16973            } else {
16974                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16975                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16976            }
16977        }
16978        synchronized (mPackages) {
16979            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16980            if (ps != null) {
16981                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16982            }
16983
16984            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16985            for (int i = 0; i < childCount; i++) {
16986                PackageParser.Package childPkg = pkg.childPackages.get(i);
16987                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16988                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16989                if (childPs != null) {
16990                    childRes.newUsers = childPs.queryInstalledUsers(
16991                            sUserManager.getUserIds(), true);
16992                }
16993            }
16994
16995            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16996                updateSequenceNumberLP(pkgName, res.newUsers);
16997            }
16998        }
16999    }
17000
17001    private void startIntentFilterVerifications(int userId, boolean replacing,
17002            PackageParser.Package pkg) {
17003        if (mIntentFilterVerifierComponent == null) {
17004            Slog.w(TAG, "No IntentFilter verification will not be done as "
17005                    + "there is no IntentFilterVerifier available!");
17006            return;
17007        }
17008
17009        final int verifierUid = getPackageUid(
17010                mIntentFilterVerifierComponent.getPackageName(),
17011                MATCH_DEBUG_TRIAGED_MISSING,
17012                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17013
17014        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17015        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17016        mHandler.sendMessage(msg);
17017
17018        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17019        for (int i = 0; i < childCount; i++) {
17020            PackageParser.Package childPkg = pkg.childPackages.get(i);
17021            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17022            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17023            mHandler.sendMessage(msg);
17024        }
17025    }
17026
17027    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17028            PackageParser.Package pkg) {
17029        int size = pkg.activities.size();
17030        if (size == 0) {
17031            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17032                    "No activity, so no need to verify any IntentFilter!");
17033            return;
17034        }
17035
17036        final boolean hasDomainURLs = hasDomainURLs(pkg);
17037        if (!hasDomainURLs) {
17038            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17039                    "No domain URLs, so no need to verify any IntentFilter!");
17040            return;
17041        }
17042
17043        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17044                + " if any IntentFilter from the " + size
17045                + " Activities needs verification ...");
17046
17047        int count = 0;
17048        final String packageName = pkg.packageName;
17049
17050        synchronized (mPackages) {
17051            // If this is a new install and we see that we've already run verification for this
17052            // package, we have nothing to do: it means the state was restored from backup.
17053            if (!replacing) {
17054                IntentFilterVerificationInfo ivi =
17055                        mSettings.getIntentFilterVerificationLPr(packageName);
17056                if (ivi != null) {
17057                    if (DEBUG_DOMAIN_VERIFICATION) {
17058                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17059                                + ivi.getStatusString());
17060                    }
17061                    return;
17062                }
17063            }
17064
17065            // If any filters need to be verified, then all need to be.
17066            boolean needToVerify = false;
17067            for (PackageParser.Activity a : pkg.activities) {
17068                for (ActivityIntentInfo filter : a.intents) {
17069                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17070                        if (DEBUG_DOMAIN_VERIFICATION) {
17071                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17072                        }
17073                        needToVerify = true;
17074                        break;
17075                    }
17076                }
17077            }
17078
17079            if (needToVerify) {
17080                final int verificationId = mIntentFilterVerificationToken++;
17081                for (PackageParser.Activity a : pkg.activities) {
17082                    for (ActivityIntentInfo filter : a.intents) {
17083                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17084                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17085                                    "Verification needed for IntentFilter:" + filter.toString());
17086                            mIntentFilterVerifier.addOneIntentFilterVerification(
17087                                    verifierUid, userId, verificationId, filter, packageName);
17088                            count++;
17089                        }
17090                    }
17091                }
17092            }
17093        }
17094
17095        if (count > 0) {
17096            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17097                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17098                    +  " for userId:" + userId);
17099            mIntentFilterVerifier.startVerifications(userId);
17100        } else {
17101            if (DEBUG_DOMAIN_VERIFICATION) {
17102                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17103            }
17104        }
17105    }
17106
17107    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17108        final ComponentName cn  = filter.activity.getComponentName();
17109        final String packageName = cn.getPackageName();
17110
17111        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17112                packageName);
17113        if (ivi == null) {
17114            return true;
17115        }
17116        int status = ivi.getStatus();
17117        switch (status) {
17118            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17119            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17120                return true;
17121
17122            default:
17123                // Nothing to do
17124                return false;
17125        }
17126    }
17127
17128    private static boolean isMultiArch(ApplicationInfo info) {
17129        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17130    }
17131
17132    private static boolean isExternal(PackageParser.Package pkg) {
17133        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17134    }
17135
17136    private static boolean isExternal(PackageSetting ps) {
17137        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17138    }
17139
17140    private static boolean isSystemApp(PackageParser.Package pkg) {
17141        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17142    }
17143
17144    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17145        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17146    }
17147
17148    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17149        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17150    }
17151
17152    private static boolean isSystemApp(PackageSetting ps) {
17153        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17154    }
17155
17156    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17157        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17158    }
17159
17160    private int packageFlagsToInstallFlags(PackageSetting ps) {
17161        int installFlags = 0;
17162        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17163            // This existing package was an external ASEC install when we have
17164            // the external flag without a UUID
17165            installFlags |= PackageManager.INSTALL_EXTERNAL;
17166        }
17167        if (ps.isForwardLocked()) {
17168            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17169        }
17170        return installFlags;
17171    }
17172
17173    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17174        if (isExternal(pkg)) {
17175            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17176                return StorageManager.UUID_PRIMARY_PHYSICAL;
17177            } else {
17178                return pkg.volumeUuid;
17179            }
17180        } else {
17181            return StorageManager.UUID_PRIVATE_INTERNAL;
17182        }
17183    }
17184
17185    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17186        if (isExternal(pkg)) {
17187            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17188                return mSettings.getExternalVersion();
17189            } else {
17190                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17191            }
17192        } else {
17193            return mSettings.getInternalVersion();
17194        }
17195    }
17196
17197    private void deleteTempPackageFiles() {
17198        final FilenameFilter filter = new FilenameFilter() {
17199            public boolean accept(File dir, String name) {
17200                return name.startsWith("vmdl") && name.endsWith(".tmp");
17201            }
17202        };
17203        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17204            file.delete();
17205        }
17206    }
17207
17208    @Override
17209    public void deletePackageAsUser(String packageName, int versionCode,
17210            IPackageDeleteObserver observer, int userId, int flags) {
17211        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17212                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17213    }
17214
17215    @Override
17216    public void deletePackageVersioned(VersionedPackage versionedPackage,
17217            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17218        mContext.enforceCallingOrSelfPermission(
17219                android.Manifest.permission.DELETE_PACKAGES, null);
17220        Preconditions.checkNotNull(versionedPackage);
17221        Preconditions.checkNotNull(observer);
17222        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17223                PackageManager.VERSION_CODE_HIGHEST,
17224                Integer.MAX_VALUE, "versionCode must be >= -1");
17225
17226        final String packageName = versionedPackage.getPackageName();
17227        // TODO: We will change version code to long, so in the new API it is long
17228        final int versionCode = (int) versionedPackage.getVersionCode();
17229        final String internalPackageName;
17230        synchronized (mPackages) {
17231            // Normalize package name to handle renamed packages and static libs
17232            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17233                    // TODO: We will change version code to long, so in the new API it is long
17234                    (int) versionedPackage.getVersionCode());
17235        }
17236
17237        final int uid = Binder.getCallingUid();
17238        if (!isOrphaned(internalPackageName)
17239                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17240            try {
17241                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17242                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17243                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17244                observer.onUserActionRequired(intent);
17245            } catch (RemoteException re) {
17246            }
17247            return;
17248        }
17249        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17250        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17251        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17252            mContext.enforceCallingOrSelfPermission(
17253                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17254                    "deletePackage for user " + userId);
17255        }
17256
17257        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17258            try {
17259                observer.onPackageDeleted(packageName,
17260                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17261            } catch (RemoteException re) {
17262            }
17263            return;
17264        }
17265
17266        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17267            try {
17268                observer.onPackageDeleted(packageName,
17269                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17270            } catch (RemoteException re) {
17271            }
17272            return;
17273        }
17274
17275        if (DEBUG_REMOVE) {
17276            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17277                    + " deleteAllUsers: " + deleteAllUsers + " version="
17278                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17279                    ? "VERSION_CODE_HIGHEST" : versionCode));
17280        }
17281        // Queue up an async operation since the package deletion may take a little while.
17282        mHandler.post(new Runnable() {
17283            public void run() {
17284                mHandler.removeCallbacks(this);
17285                int returnCode;
17286                if (!deleteAllUsers) {
17287                    returnCode = deletePackageX(internalPackageName, versionCode,
17288                            userId, deleteFlags);
17289                } else {
17290                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17291                            internalPackageName, users);
17292                    // If nobody is blocking uninstall, proceed with delete for all users
17293                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17294                        returnCode = deletePackageX(internalPackageName, versionCode,
17295                                userId, deleteFlags);
17296                    } else {
17297                        // Otherwise uninstall individually for users with blockUninstalls=false
17298                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17299                        for (int userId : users) {
17300                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17301                                returnCode = deletePackageX(internalPackageName, versionCode,
17302                                        userId, userFlags);
17303                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17304                                    Slog.w(TAG, "Package delete failed for user " + userId
17305                                            + ", returnCode " + returnCode);
17306                                }
17307                            }
17308                        }
17309                        // The app has only been marked uninstalled for certain users.
17310                        // We still need to report that delete was blocked
17311                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17312                    }
17313                }
17314                try {
17315                    observer.onPackageDeleted(packageName, returnCode, null);
17316                } catch (RemoteException e) {
17317                    Log.i(TAG, "Observer no longer exists.");
17318                } //end catch
17319            } //end run
17320        });
17321    }
17322
17323    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17324        if (pkg.staticSharedLibName != null) {
17325            return pkg.manifestPackageName;
17326        }
17327        return pkg.packageName;
17328    }
17329
17330    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17331        // Handle renamed packages
17332        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17333        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17334
17335        // Is this a static library?
17336        SparseArray<SharedLibraryEntry> versionedLib =
17337                mStaticLibsByDeclaringPackage.get(packageName);
17338        if (versionedLib == null || versionedLib.size() <= 0) {
17339            return packageName;
17340        }
17341
17342        // Figure out which lib versions the caller can see
17343        SparseIntArray versionsCallerCanSee = null;
17344        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17345        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17346                && callingAppId != Process.ROOT_UID) {
17347            versionsCallerCanSee = new SparseIntArray();
17348            String libName = versionedLib.valueAt(0).info.getName();
17349            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17350            if (uidPackages != null) {
17351                for (String uidPackage : uidPackages) {
17352                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17353                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17354                    if (libIdx >= 0) {
17355                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17356                        versionsCallerCanSee.append(libVersion, libVersion);
17357                    }
17358                }
17359            }
17360        }
17361
17362        // Caller can see nothing - done
17363        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17364            return packageName;
17365        }
17366
17367        // Find the version the caller can see and the app version code
17368        SharedLibraryEntry highestVersion = null;
17369        final int versionCount = versionedLib.size();
17370        for (int i = 0; i < versionCount; i++) {
17371            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17372            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17373                    libEntry.info.getVersion()) < 0) {
17374                continue;
17375            }
17376            // TODO: We will change version code to long, so in the new API it is long
17377            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17378            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17379                if (libVersionCode == versionCode) {
17380                    return libEntry.apk;
17381                }
17382            } else if (highestVersion == null) {
17383                highestVersion = libEntry;
17384            } else if (libVersionCode  > highestVersion.info
17385                    .getDeclaringPackage().getVersionCode()) {
17386                highestVersion = libEntry;
17387            }
17388        }
17389
17390        if (highestVersion != null) {
17391            return highestVersion.apk;
17392        }
17393
17394        return packageName;
17395    }
17396
17397    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17398        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17399              || callingUid == Process.SYSTEM_UID) {
17400            return true;
17401        }
17402        final int callingUserId = UserHandle.getUserId(callingUid);
17403        // If the caller installed the pkgName, then allow it to silently uninstall.
17404        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17405            return true;
17406        }
17407
17408        // Allow package verifier to silently uninstall.
17409        if (mRequiredVerifierPackage != null &&
17410                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17411            return true;
17412        }
17413
17414        // Allow package uninstaller to silently uninstall.
17415        if (mRequiredUninstallerPackage != null &&
17416                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17417            return true;
17418        }
17419
17420        // Allow storage manager to silently uninstall.
17421        if (mStorageManagerPackage != null &&
17422                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17423            return true;
17424        }
17425        return false;
17426    }
17427
17428    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17429        int[] result = EMPTY_INT_ARRAY;
17430        for (int userId : userIds) {
17431            if (getBlockUninstallForUser(packageName, userId)) {
17432                result = ArrayUtils.appendInt(result, userId);
17433            }
17434        }
17435        return result;
17436    }
17437
17438    @Override
17439    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17440        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17441    }
17442
17443    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17444        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17445                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17446        try {
17447            if (dpm != null) {
17448                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17449                        /* callingUserOnly =*/ false);
17450                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17451                        : deviceOwnerComponentName.getPackageName();
17452                // Does the package contains the device owner?
17453                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17454                // this check is probably not needed, since DO should be registered as a device
17455                // admin on some user too. (Original bug for this: b/17657954)
17456                if (packageName.equals(deviceOwnerPackageName)) {
17457                    return true;
17458                }
17459                // Does it contain a device admin for any user?
17460                int[] users;
17461                if (userId == UserHandle.USER_ALL) {
17462                    users = sUserManager.getUserIds();
17463                } else {
17464                    users = new int[]{userId};
17465                }
17466                for (int i = 0; i < users.length; ++i) {
17467                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17468                        return true;
17469                    }
17470                }
17471            }
17472        } catch (RemoteException e) {
17473        }
17474        return false;
17475    }
17476
17477    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17478        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17479    }
17480
17481    /**
17482     *  This method is an internal method that could be get invoked either
17483     *  to delete an installed package or to clean up a failed installation.
17484     *  After deleting an installed package, a broadcast is sent to notify any
17485     *  listeners that the package has been removed. For cleaning up a failed
17486     *  installation, the broadcast is not necessary since the package's
17487     *  installation wouldn't have sent the initial broadcast either
17488     *  The key steps in deleting a package are
17489     *  deleting the package information in internal structures like mPackages,
17490     *  deleting the packages base directories through installd
17491     *  updating mSettings to reflect current status
17492     *  persisting settings for later use
17493     *  sending a broadcast if necessary
17494     */
17495    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17496        final PackageRemovedInfo info = new PackageRemovedInfo();
17497        final boolean res;
17498
17499        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17500                ? UserHandle.USER_ALL : userId;
17501
17502        if (isPackageDeviceAdmin(packageName, removeUser)) {
17503            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17504            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17505        }
17506
17507        PackageSetting uninstalledPs = null;
17508
17509        // for the uninstall-updates case and restricted profiles, remember the per-
17510        // user handle installed state
17511        int[] allUsers;
17512        synchronized (mPackages) {
17513            uninstalledPs = mSettings.mPackages.get(packageName);
17514            if (uninstalledPs == null) {
17515                Slog.w(TAG, "Not removing non-existent package " + packageName);
17516                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17517            }
17518
17519            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17520                    && uninstalledPs.versionCode != versionCode) {
17521                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17522                        + uninstalledPs.versionCode + " != " + versionCode);
17523                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17524            }
17525
17526            // Static shared libs can be declared by any package, so let us not
17527            // allow removing a package if it provides a lib others depend on.
17528            PackageParser.Package pkg = mPackages.get(packageName);
17529            if (pkg != null && pkg.staticSharedLibName != null) {
17530                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17531                        pkg.staticSharedLibVersion);
17532                if (libEntry != null) {
17533                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17534                            libEntry.info, 0, userId);
17535                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17536                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17537                                + " hosting lib " + libEntry.info.getName() + " version "
17538                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17539                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17540                    }
17541                }
17542            }
17543
17544            allUsers = sUserManager.getUserIds();
17545            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17546        }
17547
17548        final int freezeUser;
17549        if (isUpdatedSystemApp(uninstalledPs)
17550                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17551            // We're downgrading a system app, which will apply to all users, so
17552            // freeze them all during the downgrade
17553            freezeUser = UserHandle.USER_ALL;
17554        } else {
17555            freezeUser = removeUser;
17556        }
17557
17558        synchronized (mInstallLock) {
17559            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17560            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17561                    deleteFlags, "deletePackageX")) {
17562                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17563                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17564            }
17565            synchronized (mPackages) {
17566                if (res) {
17567                    mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg,
17568                            info.removedUsers);
17569                    updateSequenceNumberLP(packageName, info.removedUsers);
17570                }
17571            }
17572        }
17573
17574        if (res) {
17575            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17576            info.sendPackageRemovedBroadcasts(killApp);
17577            info.sendSystemPackageUpdatedBroadcasts();
17578            info.sendSystemPackageAppearedBroadcasts();
17579        }
17580        // Force a gc here.
17581        Runtime.getRuntime().gc();
17582        // Delete the resources here after sending the broadcast to let
17583        // other processes clean up before deleting resources.
17584        if (info.args != null) {
17585            synchronized (mInstallLock) {
17586                info.args.doPostDeleteLI(true);
17587            }
17588        }
17589
17590        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17591    }
17592
17593    class PackageRemovedInfo {
17594        String removedPackage;
17595        int uid = -1;
17596        int removedAppId = -1;
17597        int[] origUsers;
17598        int[] removedUsers = null;
17599        SparseArray<Integer> installReasons;
17600        boolean isRemovedPackageSystemUpdate = false;
17601        boolean isUpdate;
17602        boolean dataRemoved;
17603        boolean removedForAllUsers;
17604        boolean isStaticSharedLib;
17605        // Clean up resources deleted packages.
17606        InstallArgs args = null;
17607        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17608        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17609
17610        void sendPackageRemovedBroadcasts(boolean killApp) {
17611            sendPackageRemovedBroadcastInternal(killApp);
17612            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17613            for (int i = 0; i < childCount; i++) {
17614                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17615                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17616            }
17617        }
17618
17619        void sendSystemPackageUpdatedBroadcasts() {
17620            if (isRemovedPackageSystemUpdate) {
17621                sendSystemPackageUpdatedBroadcastsInternal();
17622                final int childCount = (removedChildPackages != null)
17623                        ? removedChildPackages.size() : 0;
17624                for (int i = 0; i < childCount; i++) {
17625                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17626                    if (childInfo.isRemovedPackageSystemUpdate) {
17627                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17628                    }
17629                }
17630            }
17631        }
17632
17633        void sendSystemPackageAppearedBroadcasts() {
17634            final int packageCount = (appearedChildPackages != null)
17635                    ? appearedChildPackages.size() : 0;
17636            for (int i = 0; i < packageCount; i++) {
17637                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17638                sendPackageAddedForNewUsers(installedInfo.name, true,
17639                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17640            }
17641        }
17642
17643        private void sendSystemPackageUpdatedBroadcastsInternal() {
17644            Bundle extras = new Bundle(2);
17645            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17646            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17647            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17648                    extras, 0, null, null, null);
17649            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17650                    extras, 0, null, null, null);
17651            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17652                    null, 0, removedPackage, null, null);
17653        }
17654
17655        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17656            // Don't send static shared library removal broadcasts as these
17657            // libs are visible only the the apps that depend on them an one
17658            // cannot remove the library if it has a dependency.
17659            if (isStaticSharedLib) {
17660                return;
17661            }
17662            Bundle extras = new Bundle(2);
17663            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17664            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17665            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17666            if (isUpdate || isRemovedPackageSystemUpdate) {
17667                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17668            }
17669            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17670            if (removedPackage != null) {
17671                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17672                        extras, 0, null, null, removedUsers);
17673                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17674                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17675                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17676                            null, null, removedUsers);
17677                }
17678            }
17679            if (removedAppId >= 0) {
17680                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17681                        removedUsers);
17682            }
17683        }
17684    }
17685
17686    /*
17687     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17688     * flag is not set, the data directory is removed as well.
17689     * make sure this flag is set for partially installed apps. If not its meaningless to
17690     * delete a partially installed application.
17691     */
17692    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17693            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17694        String packageName = ps.name;
17695        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17696        // Retrieve object to delete permissions for shared user later on
17697        final PackageParser.Package deletedPkg;
17698        final PackageSetting deletedPs;
17699        // reader
17700        synchronized (mPackages) {
17701            deletedPkg = mPackages.get(packageName);
17702            deletedPs = mSettings.mPackages.get(packageName);
17703            if (outInfo != null) {
17704                outInfo.removedPackage = packageName;
17705                outInfo.isStaticSharedLib = deletedPkg != null
17706                        && deletedPkg.staticSharedLibName != null;
17707                outInfo.removedUsers = deletedPs != null
17708                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17709                        : null;
17710            }
17711        }
17712
17713        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17714
17715        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17716            final PackageParser.Package resolvedPkg;
17717            if (deletedPkg != null) {
17718                resolvedPkg = deletedPkg;
17719            } else {
17720                // We don't have a parsed package when it lives on an ejected
17721                // adopted storage device, so fake something together
17722                resolvedPkg = new PackageParser.Package(ps.name);
17723                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17724            }
17725            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17726                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17727            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17728            if (outInfo != null) {
17729                outInfo.dataRemoved = true;
17730            }
17731            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17732        }
17733
17734        int removedAppId = -1;
17735
17736        // writer
17737        synchronized (mPackages) {
17738            boolean installedStateChanged = false;
17739            if (deletedPs != null) {
17740                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17741                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17742                    clearDefaultBrowserIfNeeded(packageName);
17743                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17744                    removedAppId = mSettings.removePackageLPw(packageName);
17745                    if (outInfo != null) {
17746                        outInfo.removedAppId = removedAppId;
17747                    }
17748                    updatePermissionsLPw(deletedPs.name, null, 0);
17749                    if (deletedPs.sharedUser != null) {
17750                        // Remove permissions associated with package. Since runtime
17751                        // permissions are per user we have to kill the removed package
17752                        // or packages running under the shared user of the removed
17753                        // package if revoking the permissions requested only by the removed
17754                        // package is successful and this causes a change in gids.
17755                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17756                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17757                                    userId);
17758                            if (userIdToKill == UserHandle.USER_ALL
17759                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17760                                // If gids changed for this user, kill all affected packages.
17761                                mHandler.post(new Runnable() {
17762                                    @Override
17763                                    public void run() {
17764                                        // This has to happen with no lock held.
17765                                        killApplication(deletedPs.name, deletedPs.appId,
17766                                                KILL_APP_REASON_GIDS_CHANGED);
17767                                    }
17768                                });
17769                                break;
17770                            }
17771                        }
17772                    }
17773                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17774                }
17775                // make sure to preserve per-user disabled state if this removal was just
17776                // a downgrade of a system app to the factory package
17777                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17778                    if (DEBUG_REMOVE) {
17779                        Slog.d(TAG, "Propagating install state across downgrade");
17780                    }
17781                    for (int userId : allUserHandles) {
17782                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17783                        if (DEBUG_REMOVE) {
17784                            Slog.d(TAG, "    user " + userId + " => " + installed);
17785                        }
17786                        if (installed != ps.getInstalled(userId)) {
17787                            installedStateChanged = true;
17788                        }
17789                        ps.setInstalled(installed, userId);
17790                    }
17791                }
17792            }
17793            // can downgrade to reader
17794            if (writeSettings) {
17795                // Save settings now
17796                mSettings.writeLPr();
17797            }
17798            if (installedStateChanged) {
17799                mSettings.writeKernelMappingLPr(ps);
17800            }
17801        }
17802        if (removedAppId != -1) {
17803            // A user ID was deleted here. Go through all users and remove it
17804            // from KeyStore.
17805            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17806        }
17807    }
17808
17809    static boolean locationIsPrivileged(File path) {
17810        try {
17811            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17812                    .getCanonicalPath();
17813            return path.getCanonicalPath().startsWith(privilegedAppDir);
17814        } catch (IOException e) {
17815            Slog.e(TAG, "Unable to access code path " + path);
17816        }
17817        return false;
17818    }
17819
17820    /*
17821     * Tries to delete system package.
17822     */
17823    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17824            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17825            boolean writeSettings) {
17826        if (deletedPs.parentPackageName != null) {
17827            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17828            return false;
17829        }
17830
17831        final boolean applyUserRestrictions
17832                = (allUserHandles != null) && (outInfo.origUsers != null);
17833        final PackageSetting disabledPs;
17834        // Confirm if the system package has been updated
17835        // An updated system app can be deleted. This will also have to restore
17836        // the system pkg from system partition
17837        // reader
17838        synchronized (mPackages) {
17839            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17840        }
17841
17842        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17843                + " disabledPs=" + disabledPs);
17844
17845        if (disabledPs == null) {
17846            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17847            return false;
17848        } else if (DEBUG_REMOVE) {
17849            Slog.d(TAG, "Deleting system pkg from data partition");
17850        }
17851
17852        if (DEBUG_REMOVE) {
17853            if (applyUserRestrictions) {
17854                Slog.d(TAG, "Remembering install states:");
17855                for (int userId : allUserHandles) {
17856                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17857                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17858                }
17859            }
17860        }
17861
17862        // Delete the updated package
17863        outInfo.isRemovedPackageSystemUpdate = true;
17864        if (outInfo.removedChildPackages != null) {
17865            final int childCount = (deletedPs.childPackageNames != null)
17866                    ? deletedPs.childPackageNames.size() : 0;
17867            for (int i = 0; i < childCount; i++) {
17868                String childPackageName = deletedPs.childPackageNames.get(i);
17869                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17870                        .contains(childPackageName)) {
17871                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17872                            childPackageName);
17873                    if (childInfo != null) {
17874                        childInfo.isRemovedPackageSystemUpdate = true;
17875                    }
17876                }
17877            }
17878        }
17879
17880        if (disabledPs.versionCode < deletedPs.versionCode) {
17881            // Delete data for downgrades
17882            flags &= ~PackageManager.DELETE_KEEP_DATA;
17883        } else {
17884            // Preserve data by setting flag
17885            flags |= PackageManager.DELETE_KEEP_DATA;
17886        }
17887
17888        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17889                outInfo, writeSettings, disabledPs.pkg);
17890        if (!ret) {
17891            return false;
17892        }
17893
17894        // writer
17895        synchronized (mPackages) {
17896            // Reinstate the old system package
17897            enableSystemPackageLPw(disabledPs.pkg);
17898            // Remove any native libraries from the upgraded package.
17899            removeNativeBinariesLI(deletedPs);
17900        }
17901
17902        // Install the system package
17903        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17904        int parseFlags = mDefParseFlags
17905                | PackageParser.PARSE_MUST_BE_APK
17906                | PackageParser.PARSE_IS_SYSTEM
17907                | PackageParser.PARSE_IS_SYSTEM_DIR;
17908        if (locationIsPrivileged(disabledPs.codePath)) {
17909            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17910        }
17911
17912        final PackageParser.Package newPkg;
17913        try {
17914            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17915                0 /* currentTime */, null);
17916        } catch (PackageManagerException e) {
17917            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17918                    + e.getMessage());
17919            return false;
17920        }
17921
17922        try {
17923            // update shared libraries for the newly re-installed system package
17924            updateSharedLibrariesLPr(newPkg, null);
17925        } catch (PackageManagerException e) {
17926            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17927        }
17928
17929        prepareAppDataAfterInstallLIF(newPkg);
17930
17931        // writer
17932        synchronized (mPackages) {
17933            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17934
17935            // Propagate the permissions state as we do not want to drop on the floor
17936            // runtime permissions. The update permissions method below will take
17937            // care of removing obsolete permissions and grant install permissions.
17938            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17939            updatePermissionsLPw(newPkg.packageName, newPkg,
17940                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17941
17942            if (applyUserRestrictions) {
17943                boolean installedStateChanged = false;
17944                if (DEBUG_REMOVE) {
17945                    Slog.d(TAG, "Propagating install state across reinstall");
17946                }
17947                for (int userId : allUserHandles) {
17948                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17949                    if (DEBUG_REMOVE) {
17950                        Slog.d(TAG, "    user " + userId + " => " + installed);
17951                    }
17952                    if (installed != ps.getInstalled(userId)) {
17953                        installedStateChanged = true;
17954                    }
17955                    ps.setInstalled(installed, userId);
17956
17957                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17958                }
17959                // Regardless of writeSettings we need to ensure that this restriction
17960                // state propagation is persisted
17961                mSettings.writeAllUsersPackageRestrictionsLPr();
17962                if (installedStateChanged) {
17963                    mSettings.writeKernelMappingLPr(ps);
17964                }
17965            }
17966            // can downgrade to reader here
17967            if (writeSettings) {
17968                mSettings.writeLPr();
17969            }
17970        }
17971        return true;
17972    }
17973
17974    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17975            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17976            PackageRemovedInfo outInfo, boolean writeSettings,
17977            PackageParser.Package replacingPackage) {
17978        synchronized (mPackages) {
17979            if (outInfo != null) {
17980                outInfo.uid = ps.appId;
17981            }
17982
17983            if (outInfo != null && outInfo.removedChildPackages != null) {
17984                final int childCount = (ps.childPackageNames != null)
17985                        ? ps.childPackageNames.size() : 0;
17986                for (int i = 0; i < childCount; i++) {
17987                    String childPackageName = ps.childPackageNames.get(i);
17988                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17989                    if (childPs == null) {
17990                        return false;
17991                    }
17992                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17993                            childPackageName);
17994                    if (childInfo != null) {
17995                        childInfo.uid = childPs.appId;
17996                    }
17997                }
17998            }
17999        }
18000
18001        // Delete package data from internal structures and also remove data if flag is set
18002        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18003
18004        // Delete the child packages data
18005        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18006        for (int i = 0; i < childCount; i++) {
18007            PackageSetting childPs;
18008            synchronized (mPackages) {
18009                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18010            }
18011            if (childPs != null) {
18012                PackageRemovedInfo childOutInfo = (outInfo != null
18013                        && outInfo.removedChildPackages != null)
18014                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18015                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18016                        && (replacingPackage != null
18017                        && !replacingPackage.hasChildPackage(childPs.name))
18018                        ? flags & ~DELETE_KEEP_DATA : flags;
18019                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18020                        deleteFlags, writeSettings);
18021            }
18022        }
18023
18024        // Delete application code and resources only for parent packages
18025        if (ps.parentPackageName == null) {
18026            if (deleteCodeAndResources && (outInfo != null)) {
18027                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18028                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18029                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18030            }
18031        }
18032
18033        return true;
18034    }
18035
18036    @Override
18037    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18038            int userId) {
18039        mContext.enforceCallingOrSelfPermission(
18040                android.Manifest.permission.DELETE_PACKAGES, null);
18041        synchronized (mPackages) {
18042            PackageSetting ps = mSettings.mPackages.get(packageName);
18043            if (ps == null) {
18044                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
18045                return false;
18046            }
18047            // Cannot block uninstall of static shared libs as they are
18048            // considered a part of the using app (emulating static linking).
18049            // Also static libs are installed always on internal storage.
18050            PackageParser.Package pkg = mPackages.get(packageName);
18051            if (pkg != null && pkg.staticSharedLibName != null) {
18052                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18053                        + " providing static shared library: " + pkg.staticSharedLibName);
18054                return false;
18055            }
18056            if (!ps.getInstalled(userId)) {
18057                // Can't block uninstall for an app that is not installed or enabled.
18058                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18059                return false;
18060            }
18061            ps.setBlockUninstall(blockUninstall, userId);
18062            mSettings.writePackageRestrictionsLPr(userId);
18063        }
18064        return true;
18065    }
18066
18067    @Override
18068    public boolean getBlockUninstallForUser(String packageName, int userId) {
18069        synchronized (mPackages) {
18070            PackageSetting ps = mSettings.mPackages.get(packageName);
18071            if (ps == null) {
18072                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18073                return false;
18074            }
18075            return ps.getBlockUninstall(userId);
18076        }
18077    }
18078
18079    @Override
18080    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18081        int callingUid = Binder.getCallingUid();
18082        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18083            throw new SecurityException(
18084                    "setRequiredForSystemUser can only be run by the system or root");
18085        }
18086        synchronized (mPackages) {
18087            PackageSetting ps = mSettings.mPackages.get(packageName);
18088            if (ps == null) {
18089                Log.w(TAG, "Package doesn't exist: " + packageName);
18090                return false;
18091            }
18092            if (systemUserApp) {
18093                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18094            } else {
18095                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18096            }
18097            mSettings.writeLPr();
18098        }
18099        return true;
18100    }
18101
18102    /*
18103     * This method handles package deletion in general
18104     */
18105    private boolean deletePackageLIF(String packageName, UserHandle user,
18106            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18107            PackageRemovedInfo outInfo, boolean writeSettings,
18108            PackageParser.Package replacingPackage) {
18109        if (packageName == null) {
18110            Slog.w(TAG, "Attempt to delete null packageName.");
18111            return false;
18112        }
18113
18114        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18115
18116        PackageSetting ps;
18117        synchronized (mPackages) {
18118            ps = mSettings.mPackages.get(packageName);
18119            if (ps == null) {
18120                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18121                return false;
18122            }
18123
18124            if (ps.parentPackageName != null && (!isSystemApp(ps)
18125                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18126                if (DEBUG_REMOVE) {
18127                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18128                            + ((user == null) ? UserHandle.USER_ALL : user));
18129                }
18130                final int removedUserId = (user != null) ? user.getIdentifier()
18131                        : UserHandle.USER_ALL;
18132                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18133                    return false;
18134                }
18135                markPackageUninstalledForUserLPw(ps, user);
18136                scheduleWritePackageRestrictionsLocked(user);
18137                return true;
18138            }
18139        }
18140
18141        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18142                && user.getIdentifier() != UserHandle.USER_ALL)) {
18143            // The caller is asking that the package only be deleted for a single
18144            // user.  To do this, we just mark its uninstalled state and delete
18145            // its data. If this is a system app, we only allow this to happen if
18146            // they have set the special DELETE_SYSTEM_APP which requests different
18147            // semantics than normal for uninstalling system apps.
18148            markPackageUninstalledForUserLPw(ps, user);
18149
18150            if (!isSystemApp(ps)) {
18151                // Do not uninstall the APK if an app should be cached
18152                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18153                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18154                    // Other user still have this package installed, so all
18155                    // we need to do is clear this user's data and save that
18156                    // it is uninstalled.
18157                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18158                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18159                        return false;
18160                    }
18161                    scheduleWritePackageRestrictionsLocked(user);
18162                    return true;
18163                } else {
18164                    // We need to set it back to 'installed' so the uninstall
18165                    // broadcasts will be sent correctly.
18166                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18167                    ps.setInstalled(true, user.getIdentifier());
18168                    mSettings.writeKernelMappingLPr(ps);
18169                }
18170            } else {
18171                // This is a system app, so we assume that the
18172                // other users still have this package installed, so all
18173                // we need to do is clear this user's data and save that
18174                // it is uninstalled.
18175                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18176                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18177                    return false;
18178                }
18179                scheduleWritePackageRestrictionsLocked(user);
18180                return true;
18181            }
18182        }
18183
18184        // If we are deleting a composite package for all users, keep track
18185        // of result for each child.
18186        if (ps.childPackageNames != null && outInfo != null) {
18187            synchronized (mPackages) {
18188                final int childCount = ps.childPackageNames.size();
18189                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18190                for (int i = 0; i < childCount; i++) {
18191                    String childPackageName = ps.childPackageNames.get(i);
18192                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18193                    childInfo.removedPackage = childPackageName;
18194                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18195                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18196                    if (childPs != null) {
18197                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18198                    }
18199                }
18200            }
18201        }
18202
18203        boolean ret = false;
18204        if (isSystemApp(ps)) {
18205            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18206            // When an updated system application is deleted we delete the existing resources
18207            // as well and fall back to existing code in system partition
18208            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18209        } else {
18210            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18211            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18212                    outInfo, writeSettings, replacingPackage);
18213        }
18214
18215        // Take a note whether we deleted the package for all users
18216        if (outInfo != null) {
18217            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18218            if (outInfo.removedChildPackages != null) {
18219                synchronized (mPackages) {
18220                    final int childCount = outInfo.removedChildPackages.size();
18221                    for (int i = 0; i < childCount; i++) {
18222                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18223                        if (childInfo != null) {
18224                            childInfo.removedForAllUsers = mPackages.get(
18225                                    childInfo.removedPackage) == null;
18226                        }
18227                    }
18228                }
18229            }
18230            // If we uninstalled an update to a system app there may be some
18231            // child packages that appeared as they are declared in the system
18232            // app but were not declared in the update.
18233            if (isSystemApp(ps)) {
18234                synchronized (mPackages) {
18235                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18236                    final int childCount = (updatedPs.childPackageNames != null)
18237                            ? updatedPs.childPackageNames.size() : 0;
18238                    for (int i = 0; i < childCount; i++) {
18239                        String childPackageName = updatedPs.childPackageNames.get(i);
18240                        if (outInfo.removedChildPackages == null
18241                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18242                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18243                            if (childPs == null) {
18244                                continue;
18245                            }
18246                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18247                            installRes.name = childPackageName;
18248                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18249                            installRes.pkg = mPackages.get(childPackageName);
18250                            installRes.uid = childPs.pkg.applicationInfo.uid;
18251                            if (outInfo.appearedChildPackages == null) {
18252                                outInfo.appearedChildPackages = new ArrayMap<>();
18253                            }
18254                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18255                        }
18256                    }
18257                }
18258            }
18259        }
18260
18261        return ret;
18262    }
18263
18264    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18265        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18266                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18267        for (int nextUserId : userIds) {
18268            if (DEBUG_REMOVE) {
18269                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18270            }
18271            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18272                    false /*installed*/,
18273                    true /*stopped*/,
18274                    true /*notLaunched*/,
18275                    false /*hidden*/,
18276                    false /*suspended*/,
18277                    false /*instantApp*/,
18278                    null /*lastDisableAppCaller*/,
18279                    null /*enabledComponents*/,
18280                    null /*disabledComponents*/,
18281                    false /*blockUninstall*/,
18282                    ps.readUserState(nextUserId).domainVerificationStatus,
18283                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18284        }
18285        mSettings.writeKernelMappingLPr(ps);
18286    }
18287
18288    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18289            PackageRemovedInfo outInfo) {
18290        final PackageParser.Package pkg;
18291        synchronized (mPackages) {
18292            pkg = mPackages.get(ps.name);
18293        }
18294
18295        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18296                : new int[] {userId};
18297        for (int nextUserId : userIds) {
18298            if (DEBUG_REMOVE) {
18299                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18300                        + nextUserId);
18301            }
18302
18303            destroyAppDataLIF(pkg, userId,
18304                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18305            destroyAppProfilesLIF(pkg, userId);
18306            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18307            schedulePackageCleaning(ps.name, nextUserId, false);
18308            synchronized (mPackages) {
18309                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18310                    scheduleWritePackageRestrictionsLocked(nextUserId);
18311                }
18312                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18313            }
18314        }
18315
18316        if (outInfo != null) {
18317            outInfo.removedPackage = ps.name;
18318            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18319            outInfo.removedAppId = ps.appId;
18320            outInfo.removedUsers = userIds;
18321        }
18322
18323        return true;
18324    }
18325
18326    private final class ClearStorageConnection implements ServiceConnection {
18327        IMediaContainerService mContainerService;
18328
18329        @Override
18330        public void onServiceConnected(ComponentName name, IBinder service) {
18331            synchronized (this) {
18332                mContainerService = IMediaContainerService.Stub
18333                        .asInterface(Binder.allowBlocking(service));
18334                notifyAll();
18335            }
18336        }
18337
18338        @Override
18339        public void onServiceDisconnected(ComponentName name) {
18340        }
18341    }
18342
18343    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18344        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18345
18346        final boolean mounted;
18347        if (Environment.isExternalStorageEmulated()) {
18348            mounted = true;
18349        } else {
18350            final String status = Environment.getExternalStorageState();
18351
18352            mounted = status.equals(Environment.MEDIA_MOUNTED)
18353                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18354        }
18355
18356        if (!mounted) {
18357            return;
18358        }
18359
18360        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18361        int[] users;
18362        if (userId == UserHandle.USER_ALL) {
18363            users = sUserManager.getUserIds();
18364        } else {
18365            users = new int[] { userId };
18366        }
18367        final ClearStorageConnection conn = new ClearStorageConnection();
18368        if (mContext.bindServiceAsUser(
18369                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18370            try {
18371                for (int curUser : users) {
18372                    long timeout = SystemClock.uptimeMillis() + 5000;
18373                    synchronized (conn) {
18374                        long now;
18375                        while (conn.mContainerService == null &&
18376                                (now = SystemClock.uptimeMillis()) < timeout) {
18377                            try {
18378                                conn.wait(timeout - now);
18379                            } catch (InterruptedException e) {
18380                            }
18381                        }
18382                    }
18383                    if (conn.mContainerService == null) {
18384                        return;
18385                    }
18386
18387                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18388                    clearDirectory(conn.mContainerService,
18389                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18390                    if (allData) {
18391                        clearDirectory(conn.mContainerService,
18392                                userEnv.buildExternalStorageAppDataDirs(packageName));
18393                        clearDirectory(conn.mContainerService,
18394                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18395                    }
18396                }
18397            } finally {
18398                mContext.unbindService(conn);
18399            }
18400        }
18401    }
18402
18403    @Override
18404    public void clearApplicationProfileData(String packageName) {
18405        enforceSystemOrRoot("Only the system can clear all profile data");
18406
18407        final PackageParser.Package pkg;
18408        synchronized (mPackages) {
18409            pkg = mPackages.get(packageName);
18410        }
18411
18412        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18413            synchronized (mInstallLock) {
18414                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18415                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
18416                        true /* removeBaseMarker */);
18417            }
18418        }
18419    }
18420
18421    @Override
18422    public void clearApplicationUserData(final String packageName,
18423            final IPackageDataObserver observer, final int userId) {
18424        mContext.enforceCallingOrSelfPermission(
18425                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18426
18427        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18428                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18429
18430        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18431            throw new SecurityException("Cannot clear data for a protected package: "
18432                    + packageName);
18433        }
18434        // Queue up an async operation since the package deletion may take a little while.
18435        mHandler.post(new Runnable() {
18436            public void run() {
18437                mHandler.removeCallbacks(this);
18438                final boolean succeeded;
18439                try (PackageFreezer freezer = freezePackage(packageName,
18440                        "clearApplicationUserData")) {
18441                    synchronized (mInstallLock) {
18442                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18443                    }
18444                    clearExternalStorageDataSync(packageName, userId, true);
18445                    synchronized (mPackages) {
18446                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18447                                packageName, userId);
18448                    }
18449                }
18450                if (succeeded) {
18451                    // invoke DeviceStorageMonitor's update method to clear any notifications
18452                    DeviceStorageMonitorInternal dsm = LocalServices
18453                            .getService(DeviceStorageMonitorInternal.class);
18454                    if (dsm != null) {
18455                        dsm.checkMemory();
18456                    }
18457                }
18458                if(observer != null) {
18459                    try {
18460                        observer.onRemoveCompleted(packageName, succeeded);
18461                    } catch (RemoteException e) {
18462                        Log.i(TAG, "Observer no longer exists.");
18463                    }
18464                } //end if observer
18465            } //end run
18466        });
18467    }
18468
18469    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18470        if (packageName == null) {
18471            Slog.w(TAG, "Attempt to delete null packageName.");
18472            return false;
18473        }
18474
18475        // Try finding details about the requested package
18476        PackageParser.Package pkg;
18477        synchronized (mPackages) {
18478            pkg = mPackages.get(packageName);
18479            if (pkg == null) {
18480                final PackageSetting ps = mSettings.mPackages.get(packageName);
18481                if (ps != null) {
18482                    pkg = ps.pkg;
18483                }
18484            }
18485
18486            if (pkg == null) {
18487                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18488                return false;
18489            }
18490
18491            PackageSetting ps = (PackageSetting) pkg.mExtras;
18492            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18493        }
18494
18495        clearAppDataLIF(pkg, userId,
18496                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18497
18498        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18499        removeKeystoreDataIfNeeded(userId, appId);
18500
18501        UserManagerInternal umInternal = getUserManagerInternal();
18502        final int flags;
18503        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18504            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18505        } else if (umInternal.isUserRunning(userId)) {
18506            flags = StorageManager.FLAG_STORAGE_DE;
18507        } else {
18508            flags = 0;
18509        }
18510        prepareAppDataContentsLIF(pkg, userId, flags);
18511
18512        return true;
18513    }
18514
18515    /**
18516     * Reverts user permission state changes (permissions and flags) in
18517     * all packages for a given user.
18518     *
18519     * @param userId The device user for which to do a reset.
18520     */
18521    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18522        final int packageCount = mPackages.size();
18523        for (int i = 0; i < packageCount; i++) {
18524            PackageParser.Package pkg = mPackages.valueAt(i);
18525            PackageSetting ps = (PackageSetting) pkg.mExtras;
18526            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18527        }
18528    }
18529
18530    private void resetNetworkPolicies(int userId) {
18531        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18532    }
18533
18534    /**
18535     * Reverts user permission state changes (permissions and flags).
18536     *
18537     * @param ps The package for which to reset.
18538     * @param userId The device user for which to do a reset.
18539     */
18540    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18541            final PackageSetting ps, final int userId) {
18542        if (ps.pkg == null) {
18543            return;
18544        }
18545
18546        // These are flags that can change base on user actions.
18547        final int userSettableMask = FLAG_PERMISSION_USER_SET
18548                | FLAG_PERMISSION_USER_FIXED
18549                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18550                | FLAG_PERMISSION_REVIEW_REQUIRED;
18551
18552        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18553                | FLAG_PERMISSION_POLICY_FIXED;
18554
18555        boolean writeInstallPermissions = false;
18556        boolean writeRuntimePermissions = false;
18557
18558        final int permissionCount = ps.pkg.requestedPermissions.size();
18559        for (int i = 0; i < permissionCount; i++) {
18560            String permission = ps.pkg.requestedPermissions.get(i);
18561
18562            BasePermission bp = mSettings.mPermissions.get(permission);
18563            if (bp == null) {
18564                continue;
18565            }
18566
18567            // If shared user we just reset the state to which only this app contributed.
18568            if (ps.sharedUser != null) {
18569                boolean used = false;
18570                final int packageCount = ps.sharedUser.packages.size();
18571                for (int j = 0; j < packageCount; j++) {
18572                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18573                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18574                            && pkg.pkg.requestedPermissions.contains(permission)) {
18575                        used = true;
18576                        break;
18577                    }
18578                }
18579                if (used) {
18580                    continue;
18581                }
18582            }
18583
18584            PermissionsState permissionsState = ps.getPermissionsState();
18585
18586            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18587
18588            // Always clear the user settable flags.
18589            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18590                    bp.name) != null;
18591            // If permission review is enabled and this is a legacy app, mark the
18592            // permission as requiring a review as this is the initial state.
18593            int flags = 0;
18594            if (mPermissionReviewRequired
18595                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18596                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18597            }
18598            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18599                if (hasInstallState) {
18600                    writeInstallPermissions = true;
18601                } else {
18602                    writeRuntimePermissions = true;
18603                }
18604            }
18605
18606            // Below is only runtime permission handling.
18607            if (!bp.isRuntime()) {
18608                continue;
18609            }
18610
18611            // Never clobber system or policy.
18612            if ((oldFlags & policyOrSystemFlags) != 0) {
18613                continue;
18614            }
18615
18616            // If this permission was granted by default, make sure it is.
18617            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18618                if (permissionsState.grantRuntimePermission(bp, userId)
18619                        != PERMISSION_OPERATION_FAILURE) {
18620                    writeRuntimePermissions = true;
18621                }
18622            // If permission review is enabled the permissions for a legacy apps
18623            // are represented as constantly granted runtime ones, so don't revoke.
18624            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18625                // Otherwise, reset the permission.
18626                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18627                switch (revokeResult) {
18628                    case PERMISSION_OPERATION_SUCCESS:
18629                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18630                        writeRuntimePermissions = true;
18631                        final int appId = ps.appId;
18632                        mHandler.post(new Runnable() {
18633                            @Override
18634                            public void run() {
18635                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18636                            }
18637                        });
18638                    } break;
18639                }
18640            }
18641        }
18642
18643        // Synchronously write as we are taking permissions away.
18644        if (writeRuntimePermissions) {
18645            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18646        }
18647
18648        // Synchronously write as we are taking permissions away.
18649        if (writeInstallPermissions) {
18650            mSettings.writeLPr();
18651        }
18652    }
18653
18654    /**
18655     * Remove entries from the keystore daemon. Will only remove it if the
18656     * {@code appId} is valid.
18657     */
18658    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18659        if (appId < 0) {
18660            return;
18661        }
18662
18663        final KeyStore keyStore = KeyStore.getInstance();
18664        if (keyStore != null) {
18665            if (userId == UserHandle.USER_ALL) {
18666                for (final int individual : sUserManager.getUserIds()) {
18667                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18668                }
18669            } else {
18670                keyStore.clearUid(UserHandle.getUid(userId, appId));
18671            }
18672        } else {
18673            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18674        }
18675    }
18676
18677    @Override
18678    public void deleteApplicationCacheFiles(final String packageName,
18679            final IPackageDataObserver observer) {
18680        final int userId = UserHandle.getCallingUserId();
18681        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18682    }
18683
18684    @Override
18685    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18686            final IPackageDataObserver observer) {
18687        mContext.enforceCallingOrSelfPermission(
18688                android.Manifest.permission.DELETE_CACHE_FILES, null);
18689        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18690                /* requireFullPermission= */ true, /* checkShell= */ false,
18691                "delete application cache files");
18692
18693        final PackageParser.Package pkg;
18694        synchronized (mPackages) {
18695            pkg = mPackages.get(packageName);
18696        }
18697
18698        // Queue up an async operation since the package deletion may take a little while.
18699        mHandler.post(new Runnable() {
18700            public void run() {
18701                synchronized (mInstallLock) {
18702                    final int flags = StorageManager.FLAG_STORAGE_DE
18703                            | StorageManager.FLAG_STORAGE_CE;
18704                    // We're only clearing cache files, so we don't care if the
18705                    // app is unfrozen and still able to run
18706                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18707                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18708                }
18709                clearExternalStorageDataSync(packageName, userId, false);
18710                if (observer != null) {
18711                    try {
18712                        observer.onRemoveCompleted(packageName, true);
18713                    } catch (RemoteException e) {
18714                        Log.i(TAG, "Observer no longer exists.");
18715                    }
18716                }
18717            }
18718        });
18719    }
18720
18721    @Override
18722    public void getPackageSizeInfo(final String packageName, int userHandle,
18723            final IPackageStatsObserver observer) {
18724        Slog.w(TAG, "Shame on you for calling a hidden API. Shame!");
18725        try {
18726            observer.onGetStatsCompleted(null, false);
18727        } catch (Throwable ignored) {
18728        }
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    public void waitForAppDataPrepared() {
20144        if (mPrepareAppDataFuture == null) {
20145            return;
20146        }
20147        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20148        mPrepareAppDataFuture = null;
20149    }
20150
20151    @Override
20152    public boolean isSafeMode() {
20153        return mSafeMode;
20154    }
20155
20156    @Override
20157    public boolean hasSystemUidErrors() {
20158        return mHasSystemUidErrors;
20159    }
20160
20161    static String arrayToString(int[] array) {
20162        StringBuffer buf = new StringBuffer(128);
20163        buf.append('[');
20164        if (array != null) {
20165            for (int i=0; i<array.length; i++) {
20166                if (i > 0) buf.append(", ");
20167                buf.append(array[i]);
20168            }
20169        }
20170        buf.append(']');
20171        return buf.toString();
20172    }
20173
20174    static class DumpState {
20175        public static final int DUMP_LIBS = 1 << 0;
20176        public static final int DUMP_FEATURES = 1 << 1;
20177        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20178        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20179        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20180        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20181        public static final int DUMP_PERMISSIONS = 1 << 6;
20182        public static final int DUMP_PACKAGES = 1 << 7;
20183        public static final int DUMP_SHARED_USERS = 1 << 8;
20184        public static final int DUMP_MESSAGES = 1 << 9;
20185        public static final int DUMP_PROVIDERS = 1 << 10;
20186        public static final int DUMP_VERIFIERS = 1 << 11;
20187        public static final int DUMP_PREFERRED = 1 << 12;
20188        public static final int DUMP_PREFERRED_XML = 1 << 13;
20189        public static final int DUMP_KEYSETS = 1 << 14;
20190        public static final int DUMP_VERSION = 1 << 15;
20191        public static final int DUMP_INSTALLS = 1 << 16;
20192        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20193        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20194        public static final int DUMP_FROZEN = 1 << 19;
20195        public static final int DUMP_DEXOPT = 1 << 20;
20196        public static final int DUMP_COMPILER_STATS = 1 << 21;
20197        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20198
20199        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20200
20201        private int mTypes;
20202
20203        private int mOptions;
20204
20205        private boolean mTitlePrinted;
20206
20207        private SharedUserSetting mSharedUser;
20208
20209        public boolean isDumping(int type) {
20210            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20211                return true;
20212            }
20213
20214            return (mTypes & type) != 0;
20215        }
20216
20217        public void setDump(int type) {
20218            mTypes |= type;
20219        }
20220
20221        public boolean isOptionEnabled(int option) {
20222            return (mOptions & option) != 0;
20223        }
20224
20225        public void setOptionEnabled(int option) {
20226            mOptions |= option;
20227        }
20228
20229        public boolean onTitlePrinted() {
20230            final boolean printed = mTitlePrinted;
20231            mTitlePrinted = true;
20232            return printed;
20233        }
20234
20235        public boolean getTitlePrinted() {
20236            return mTitlePrinted;
20237        }
20238
20239        public void setTitlePrinted(boolean enabled) {
20240            mTitlePrinted = enabled;
20241        }
20242
20243        public SharedUserSetting getSharedUser() {
20244            return mSharedUser;
20245        }
20246
20247        public void setSharedUser(SharedUserSetting user) {
20248            mSharedUser = user;
20249        }
20250    }
20251
20252    @Override
20253    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20254            FileDescriptor err, String[] args, ShellCallback callback,
20255            ResultReceiver resultReceiver) {
20256        (new PackageManagerShellCommand(this)).exec(
20257                this, in, out, err, args, callback, resultReceiver);
20258    }
20259
20260    @Override
20261    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20262        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20263                != PackageManager.PERMISSION_GRANTED) {
20264            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20265                    + Binder.getCallingPid()
20266                    + ", uid=" + Binder.getCallingUid()
20267                    + " without permission "
20268                    + android.Manifest.permission.DUMP);
20269            return;
20270        }
20271
20272        DumpState dumpState = new DumpState();
20273        boolean fullPreferred = false;
20274        boolean checkin = false;
20275
20276        String packageName = null;
20277        ArraySet<String> permissionNames = null;
20278
20279        int opti = 0;
20280        while (opti < args.length) {
20281            String opt = args[opti];
20282            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20283                break;
20284            }
20285            opti++;
20286
20287            if ("-a".equals(opt)) {
20288                // Right now we only know how to print all.
20289            } else if ("-h".equals(opt)) {
20290                pw.println("Package manager dump options:");
20291                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20292                pw.println("    --checkin: dump for a checkin");
20293                pw.println("    -f: print details of intent filters");
20294                pw.println("    -h: print this help");
20295                pw.println("  cmd may be one of:");
20296                pw.println("    l[ibraries]: list known shared libraries");
20297                pw.println("    f[eatures]: list device features");
20298                pw.println("    k[eysets]: print known keysets");
20299                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20300                pw.println("    perm[issions]: dump permissions");
20301                pw.println("    permission [name ...]: dump declaration and use of given permission");
20302                pw.println("    pref[erred]: print preferred package settings");
20303                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20304                pw.println("    prov[iders]: dump content providers");
20305                pw.println("    p[ackages]: dump installed packages");
20306                pw.println("    s[hared-users]: dump shared user IDs");
20307                pw.println("    m[essages]: print collected runtime messages");
20308                pw.println("    v[erifiers]: print package verifier info");
20309                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20310                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20311                pw.println("    version: print database version info");
20312                pw.println("    write: write current settings now");
20313                pw.println("    installs: details about install sessions");
20314                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20315                pw.println("    dexopt: dump dexopt state");
20316                pw.println("    compiler-stats: dump compiler statistics");
20317                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20318                pw.println("    <package.name>: info about given package");
20319                return;
20320            } else if ("--checkin".equals(opt)) {
20321                checkin = true;
20322            } else if ("-f".equals(opt)) {
20323                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20324            } else if ("--proto".equals(opt)) {
20325                dumpProto(fd);
20326                return;
20327            } else {
20328                pw.println("Unknown argument: " + opt + "; use -h for help");
20329            }
20330        }
20331
20332        // Is the caller requesting to dump a particular piece of data?
20333        if (opti < args.length) {
20334            String cmd = args[opti];
20335            opti++;
20336            // Is this a package name?
20337            if ("android".equals(cmd) || cmd.contains(".")) {
20338                packageName = cmd;
20339                // When dumping a single package, we always dump all of its
20340                // filter information since the amount of data will be reasonable.
20341                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20342            } else if ("check-permission".equals(cmd)) {
20343                if (opti >= args.length) {
20344                    pw.println("Error: check-permission missing permission argument");
20345                    return;
20346                }
20347                String perm = args[opti];
20348                opti++;
20349                if (opti >= args.length) {
20350                    pw.println("Error: check-permission missing package argument");
20351                    return;
20352                }
20353
20354                String pkg = args[opti];
20355                opti++;
20356                int user = UserHandle.getUserId(Binder.getCallingUid());
20357                if (opti < args.length) {
20358                    try {
20359                        user = Integer.parseInt(args[opti]);
20360                    } catch (NumberFormatException e) {
20361                        pw.println("Error: check-permission user argument is not a number: "
20362                                + args[opti]);
20363                        return;
20364                    }
20365                }
20366
20367                // Normalize package name to handle renamed packages and static libs
20368                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20369
20370                pw.println(checkPermission(perm, pkg, user));
20371                return;
20372            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20373                dumpState.setDump(DumpState.DUMP_LIBS);
20374            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20375                dumpState.setDump(DumpState.DUMP_FEATURES);
20376            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20377                if (opti >= args.length) {
20378                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20379                            | DumpState.DUMP_SERVICE_RESOLVERS
20380                            | DumpState.DUMP_RECEIVER_RESOLVERS
20381                            | DumpState.DUMP_CONTENT_RESOLVERS);
20382                } else {
20383                    while (opti < args.length) {
20384                        String name = args[opti];
20385                        if ("a".equals(name) || "activity".equals(name)) {
20386                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20387                        } else if ("s".equals(name) || "service".equals(name)) {
20388                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20389                        } else if ("r".equals(name) || "receiver".equals(name)) {
20390                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20391                        } else if ("c".equals(name) || "content".equals(name)) {
20392                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20393                        } else {
20394                            pw.println("Error: unknown resolver table type: " + name);
20395                            return;
20396                        }
20397                        opti++;
20398                    }
20399                }
20400            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20401                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20402            } else if ("permission".equals(cmd)) {
20403                if (opti >= args.length) {
20404                    pw.println("Error: permission requires permission name");
20405                    return;
20406                }
20407                permissionNames = new ArraySet<>();
20408                while (opti < args.length) {
20409                    permissionNames.add(args[opti]);
20410                    opti++;
20411                }
20412                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20413                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20414            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20415                dumpState.setDump(DumpState.DUMP_PREFERRED);
20416            } else if ("preferred-xml".equals(cmd)) {
20417                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20418                if (opti < args.length && "--full".equals(args[opti])) {
20419                    fullPreferred = true;
20420                    opti++;
20421                }
20422            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20423                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20424            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20425                dumpState.setDump(DumpState.DUMP_PACKAGES);
20426            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20427                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20428            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20429                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20430            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20431                dumpState.setDump(DumpState.DUMP_MESSAGES);
20432            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20433                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20434            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20435                    || "intent-filter-verifiers".equals(cmd)) {
20436                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20437            } else if ("version".equals(cmd)) {
20438                dumpState.setDump(DumpState.DUMP_VERSION);
20439            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20440                dumpState.setDump(DumpState.DUMP_KEYSETS);
20441            } else if ("installs".equals(cmd)) {
20442                dumpState.setDump(DumpState.DUMP_INSTALLS);
20443            } else if ("frozen".equals(cmd)) {
20444                dumpState.setDump(DumpState.DUMP_FROZEN);
20445            } else if ("dexopt".equals(cmd)) {
20446                dumpState.setDump(DumpState.DUMP_DEXOPT);
20447            } else if ("compiler-stats".equals(cmd)) {
20448                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20449            } else if ("enabled-overlays".equals(cmd)) {
20450                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20451            } else if ("write".equals(cmd)) {
20452                synchronized (mPackages) {
20453                    mSettings.writeLPr();
20454                    pw.println("Settings written.");
20455                    return;
20456                }
20457            }
20458        }
20459
20460        if (checkin) {
20461            pw.println("vers,1");
20462        }
20463
20464        // reader
20465        synchronized (mPackages) {
20466            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20467                if (!checkin) {
20468                    if (dumpState.onTitlePrinted())
20469                        pw.println();
20470                    pw.println("Database versions:");
20471                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20472                }
20473            }
20474
20475            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20476                if (!checkin) {
20477                    if (dumpState.onTitlePrinted())
20478                        pw.println();
20479                    pw.println("Verifiers:");
20480                    pw.print("  Required: ");
20481                    pw.print(mRequiredVerifierPackage);
20482                    pw.print(" (uid=");
20483                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20484                            UserHandle.USER_SYSTEM));
20485                    pw.println(")");
20486                } else if (mRequiredVerifierPackage != null) {
20487                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20488                    pw.print(",");
20489                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20490                            UserHandle.USER_SYSTEM));
20491                }
20492            }
20493
20494            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20495                    packageName == null) {
20496                if (mIntentFilterVerifierComponent != null) {
20497                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20498                    if (!checkin) {
20499                        if (dumpState.onTitlePrinted())
20500                            pw.println();
20501                        pw.println("Intent Filter Verifier:");
20502                        pw.print("  Using: ");
20503                        pw.print(verifierPackageName);
20504                        pw.print(" (uid=");
20505                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20506                                UserHandle.USER_SYSTEM));
20507                        pw.println(")");
20508                    } else if (verifierPackageName != null) {
20509                        pw.print("ifv,"); pw.print(verifierPackageName);
20510                        pw.print(",");
20511                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20512                                UserHandle.USER_SYSTEM));
20513                    }
20514                } else {
20515                    pw.println();
20516                    pw.println("No Intent Filter Verifier available!");
20517                }
20518            }
20519
20520            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20521                boolean printedHeader = false;
20522                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20523                while (it.hasNext()) {
20524                    String libName = it.next();
20525                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20526                    if (versionedLib == null) {
20527                        continue;
20528                    }
20529                    final int versionCount = versionedLib.size();
20530                    for (int i = 0; i < versionCount; i++) {
20531                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20532                        if (!checkin) {
20533                            if (!printedHeader) {
20534                                if (dumpState.onTitlePrinted())
20535                                    pw.println();
20536                                pw.println("Libraries:");
20537                                printedHeader = true;
20538                            }
20539                            pw.print("  ");
20540                        } else {
20541                            pw.print("lib,");
20542                        }
20543                        pw.print(libEntry.info.getName());
20544                        if (libEntry.info.isStatic()) {
20545                            pw.print(" version=" + libEntry.info.getVersion());
20546                        }
20547                        if (!checkin) {
20548                            pw.print(" -> ");
20549                        }
20550                        if (libEntry.path != null) {
20551                            pw.print(" (jar) ");
20552                            pw.print(libEntry.path);
20553                        } else {
20554                            pw.print(" (apk) ");
20555                            pw.print(libEntry.apk);
20556                        }
20557                        pw.println();
20558                    }
20559                }
20560            }
20561
20562            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20563                if (dumpState.onTitlePrinted())
20564                    pw.println();
20565                if (!checkin) {
20566                    pw.println("Features:");
20567                }
20568
20569                synchronized (mAvailableFeatures) {
20570                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20571                        if (checkin) {
20572                            pw.print("feat,");
20573                            pw.print(feat.name);
20574                            pw.print(",");
20575                            pw.println(feat.version);
20576                        } else {
20577                            pw.print("  ");
20578                            pw.print(feat.name);
20579                            if (feat.version > 0) {
20580                                pw.print(" version=");
20581                                pw.print(feat.version);
20582                            }
20583                            pw.println();
20584                        }
20585                    }
20586                }
20587            }
20588
20589            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20590                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20591                        : "Activity Resolver Table:", "  ", packageName,
20592                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20593                    dumpState.setTitlePrinted(true);
20594                }
20595            }
20596            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20597                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20598                        : "Receiver Resolver Table:", "  ", packageName,
20599                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20600                    dumpState.setTitlePrinted(true);
20601                }
20602            }
20603            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20604                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20605                        : "Service Resolver Table:", "  ", packageName,
20606                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20607                    dumpState.setTitlePrinted(true);
20608                }
20609            }
20610            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20611                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20612                        : "Provider Resolver Table:", "  ", packageName,
20613                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20614                    dumpState.setTitlePrinted(true);
20615                }
20616            }
20617
20618            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20619                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20620                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20621                    int user = mSettings.mPreferredActivities.keyAt(i);
20622                    if (pir.dump(pw,
20623                            dumpState.getTitlePrinted()
20624                                ? "\nPreferred Activities User " + user + ":"
20625                                : "Preferred Activities User " + user + ":", "  ",
20626                            packageName, true, false)) {
20627                        dumpState.setTitlePrinted(true);
20628                    }
20629                }
20630            }
20631
20632            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20633                pw.flush();
20634                FileOutputStream fout = new FileOutputStream(fd);
20635                BufferedOutputStream str = new BufferedOutputStream(fout);
20636                XmlSerializer serializer = new FastXmlSerializer();
20637                try {
20638                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20639                    serializer.startDocument(null, true);
20640                    serializer.setFeature(
20641                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20642                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20643                    serializer.endDocument();
20644                    serializer.flush();
20645                } catch (IllegalArgumentException e) {
20646                    pw.println("Failed writing: " + e);
20647                } catch (IllegalStateException e) {
20648                    pw.println("Failed writing: " + e);
20649                } catch (IOException e) {
20650                    pw.println("Failed writing: " + e);
20651                }
20652            }
20653
20654            if (!checkin
20655                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20656                    && packageName == null) {
20657                pw.println();
20658                int count = mSettings.mPackages.size();
20659                if (count == 0) {
20660                    pw.println("No applications!");
20661                    pw.println();
20662                } else {
20663                    final String prefix = "  ";
20664                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20665                    if (allPackageSettings.size() == 0) {
20666                        pw.println("No domain preferred apps!");
20667                        pw.println();
20668                    } else {
20669                        pw.println("App verification status:");
20670                        pw.println();
20671                        count = 0;
20672                        for (PackageSetting ps : allPackageSettings) {
20673                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20674                            if (ivi == null || ivi.getPackageName() == null) continue;
20675                            pw.println(prefix + "Package: " + ivi.getPackageName());
20676                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20677                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20678                            pw.println();
20679                            count++;
20680                        }
20681                        if (count == 0) {
20682                            pw.println(prefix + "No app verification established.");
20683                            pw.println();
20684                        }
20685                        for (int userId : sUserManager.getUserIds()) {
20686                            pw.println("App linkages for user " + userId + ":");
20687                            pw.println();
20688                            count = 0;
20689                            for (PackageSetting ps : allPackageSettings) {
20690                                final long status = ps.getDomainVerificationStatusForUser(userId);
20691                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20692                                        && !DEBUG_DOMAIN_VERIFICATION) {
20693                                    continue;
20694                                }
20695                                pw.println(prefix + "Package: " + ps.name);
20696                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20697                                String statusStr = IntentFilterVerificationInfo.
20698                                        getStatusStringFromValue(status);
20699                                pw.println(prefix + "Status:  " + statusStr);
20700                                pw.println();
20701                                count++;
20702                            }
20703                            if (count == 0) {
20704                                pw.println(prefix + "No configured app linkages.");
20705                                pw.println();
20706                            }
20707                        }
20708                    }
20709                }
20710            }
20711
20712            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20713                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20714                if (packageName == null && permissionNames == null) {
20715                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20716                        if (iperm == 0) {
20717                            if (dumpState.onTitlePrinted())
20718                                pw.println();
20719                            pw.println("AppOp Permissions:");
20720                        }
20721                        pw.print("  AppOp Permission ");
20722                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20723                        pw.println(":");
20724                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20725                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20726                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20727                        }
20728                    }
20729                }
20730            }
20731
20732            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20733                boolean printedSomething = false;
20734                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20735                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20736                        continue;
20737                    }
20738                    if (!printedSomething) {
20739                        if (dumpState.onTitlePrinted())
20740                            pw.println();
20741                        pw.println("Registered ContentProviders:");
20742                        printedSomething = true;
20743                    }
20744                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20745                    pw.print("    "); pw.println(p.toString());
20746                }
20747                printedSomething = false;
20748                for (Map.Entry<String, PackageParser.Provider> entry :
20749                        mProvidersByAuthority.entrySet()) {
20750                    PackageParser.Provider p = entry.getValue();
20751                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20752                        continue;
20753                    }
20754                    if (!printedSomething) {
20755                        if (dumpState.onTitlePrinted())
20756                            pw.println();
20757                        pw.println("ContentProvider Authorities:");
20758                        printedSomething = true;
20759                    }
20760                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20761                    pw.print("    "); pw.println(p.toString());
20762                    if (p.info != null && p.info.applicationInfo != null) {
20763                        final String appInfo = p.info.applicationInfo.toString();
20764                        pw.print("      applicationInfo="); pw.println(appInfo);
20765                    }
20766                }
20767            }
20768
20769            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20770                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20771            }
20772
20773            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20774                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20775            }
20776
20777            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20778                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20779            }
20780
20781            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20782                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20783            }
20784
20785            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20786                // XXX should handle packageName != null by dumping only install data that
20787                // the given package is involved with.
20788                if (dumpState.onTitlePrinted()) pw.println();
20789                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20790            }
20791
20792            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20793                // XXX should handle packageName != null by dumping only install data that
20794                // the given package is involved with.
20795                if (dumpState.onTitlePrinted()) pw.println();
20796
20797                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20798                ipw.println();
20799                ipw.println("Frozen packages:");
20800                ipw.increaseIndent();
20801                if (mFrozenPackages.size() == 0) {
20802                    ipw.println("(none)");
20803                } else {
20804                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20805                        ipw.println(mFrozenPackages.valueAt(i));
20806                    }
20807                }
20808                ipw.decreaseIndent();
20809            }
20810
20811            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20812                if (dumpState.onTitlePrinted()) pw.println();
20813                dumpDexoptStateLPr(pw, packageName);
20814            }
20815
20816            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20817                if (dumpState.onTitlePrinted()) pw.println();
20818                dumpCompilerStatsLPr(pw, packageName);
20819            }
20820
20821            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
20822                if (dumpState.onTitlePrinted()) pw.println();
20823                dumpEnabledOverlaysLPr(pw);
20824            }
20825
20826            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20827                if (dumpState.onTitlePrinted()) pw.println();
20828                mSettings.dumpReadMessagesLPr(pw, dumpState);
20829
20830                pw.println();
20831                pw.println("Package warning messages:");
20832                BufferedReader in = null;
20833                String line = null;
20834                try {
20835                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20836                    while ((line = in.readLine()) != null) {
20837                        if (line.contains("ignored: updated version")) continue;
20838                        pw.println(line);
20839                    }
20840                } catch (IOException ignored) {
20841                } finally {
20842                    IoUtils.closeQuietly(in);
20843                }
20844            }
20845
20846            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20847                BufferedReader in = null;
20848                String line = null;
20849                try {
20850                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20851                    while ((line = in.readLine()) != null) {
20852                        if (line.contains("ignored: updated version")) continue;
20853                        pw.print("msg,");
20854                        pw.println(line);
20855                    }
20856                } catch (IOException ignored) {
20857                } finally {
20858                    IoUtils.closeQuietly(in);
20859                }
20860            }
20861        }
20862    }
20863
20864    private void dumpProto(FileDescriptor fd) {
20865        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20866
20867        synchronized (mPackages) {
20868            final long requiredVerifierPackageToken =
20869                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20870            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20871            proto.write(
20872                    PackageServiceDumpProto.PackageShortProto.UID,
20873                    getPackageUid(
20874                            mRequiredVerifierPackage,
20875                            MATCH_DEBUG_TRIAGED_MISSING,
20876                            UserHandle.USER_SYSTEM));
20877            proto.end(requiredVerifierPackageToken);
20878
20879            if (mIntentFilterVerifierComponent != null) {
20880                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20881                final long verifierPackageToken =
20882                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20883                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20884                proto.write(
20885                        PackageServiceDumpProto.PackageShortProto.UID,
20886                        getPackageUid(
20887                                verifierPackageName,
20888                                MATCH_DEBUG_TRIAGED_MISSING,
20889                                UserHandle.USER_SYSTEM));
20890                proto.end(verifierPackageToken);
20891            }
20892
20893            dumpSharedLibrariesProto(proto);
20894            dumpFeaturesProto(proto);
20895            mSettings.dumpPackagesProto(proto);
20896            mSettings.dumpSharedUsersProto(proto);
20897            dumpMessagesProto(proto);
20898        }
20899        proto.flush();
20900    }
20901
20902    private void dumpMessagesProto(ProtoOutputStream proto) {
20903        BufferedReader in = null;
20904        String line = null;
20905        try {
20906            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20907            while ((line = in.readLine()) != null) {
20908                if (line.contains("ignored: updated version")) continue;
20909                proto.write(PackageServiceDumpProto.MESSAGES, line);
20910            }
20911        } catch (IOException ignored) {
20912        } finally {
20913            IoUtils.closeQuietly(in);
20914        }
20915    }
20916
20917    private void dumpFeaturesProto(ProtoOutputStream proto) {
20918        synchronized (mAvailableFeatures) {
20919            final int count = mAvailableFeatures.size();
20920            for (int i = 0; i < count; i++) {
20921                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
20922                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
20923                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
20924                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
20925                proto.end(featureToken);
20926            }
20927        }
20928    }
20929
20930    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
20931        final int count = mSharedLibraries.size();
20932        for (int i = 0; i < count; i++) {
20933            final String libName = mSharedLibraries.keyAt(i);
20934            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20935            if (versionedLib == null) {
20936                continue;
20937            }
20938            final int versionCount = versionedLib.size();
20939            for (int j = 0; j < versionCount; j++) {
20940                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
20941                final long sharedLibraryToken =
20942                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
20943                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
20944                final boolean isJar = (libEntry.path != null);
20945                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
20946                if (isJar) {
20947                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
20948                } else {
20949                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
20950                }
20951                proto.end(sharedLibraryToken);
20952            }
20953        }
20954    }
20955
20956    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20957        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20958        ipw.println();
20959        ipw.println("Dexopt state:");
20960        ipw.increaseIndent();
20961        Collection<PackageParser.Package> packages = null;
20962        if (packageName != null) {
20963            PackageParser.Package targetPackage = mPackages.get(packageName);
20964            if (targetPackage != null) {
20965                packages = Collections.singletonList(targetPackage);
20966            } else {
20967                ipw.println("Unable to find package: " + packageName);
20968                return;
20969            }
20970        } else {
20971            packages = mPackages.values();
20972        }
20973
20974        for (PackageParser.Package pkg : packages) {
20975            ipw.println("[" + pkg.packageName + "]");
20976            ipw.increaseIndent();
20977            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20978            ipw.decreaseIndent();
20979        }
20980    }
20981
20982    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20983        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20984        ipw.println();
20985        ipw.println("Compiler stats:");
20986        ipw.increaseIndent();
20987        Collection<PackageParser.Package> packages = null;
20988        if (packageName != null) {
20989            PackageParser.Package targetPackage = mPackages.get(packageName);
20990            if (targetPackage != null) {
20991                packages = Collections.singletonList(targetPackage);
20992            } else {
20993                ipw.println("Unable to find package: " + packageName);
20994                return;
20995            }
20996        } else {
20997            packages = mPackages.values();
20998        }
20999
21000        for (PackageParser.Package pkg : packages) {
21001            ipw.println("[" + pkg.packageName + "]");
21002            ipw.increaseIndent();
21003
21004            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21005            if (stats == null) {
21006                ipw.println("(No recorded stats)");
21007            } else {
21008                stats.dump(ipw);
21009            }
21010            ipw.decreaseIndent();
21011        }
21012    }
21013
21014    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
21015        pw.println("Enabled overlay paths:");
21016        final int N = mEnabledOverlayPaths.size();
21017        for (int i = 0; i < N; i++) {
21018            final int userId = mEnabledOverlayPaths.keyAt(i);
21019            pw.println(String.format("    User %d:", userId));
21020            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
21021                mEnabledOverlayPaths.valueAt(i);
21022            final int M = userSpecificOverlays.size();
21023            for (int j = 0; j < M; j++) {
21024                final String targetPackageName = userSpecificOverlays.keyAt(j);
21025                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
21026                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
21027            }
21028        }
21029    }
21030
21031    private String dumpDomainString(String packageName) {
21032        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21033                .getList();
21034        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21035
21036        ArraySet<String> result = new ArraySet<>();
21037        if (iviList.size() > 0) {
21038            for (IntentFilterVerificationInfo ivi : iviList) {
21039                for (String host : ivi.getDomains()) {
21040                    result.add(host);
21041                }
21042            }
21043        }
21044        if (filters != null && filters.size() > 0) {
21045            for (IntentFilter filter : filters) {
21046                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21047                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21048                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21049                    result.addAll(filter.getHostsList());
21050                }
21051            }
21052        }
21053
21054        StringBuilder sb = new StringBuilder(result.size() * 16);
21055        for (String domain : result) {
21056            if (sb.length() > 0) sb.append(" ");
21057            sb.append(domain);
21058        }
21059        return sb.toString();
21060    }
21061
21062    // ------- apps on sdcard specific code -------
21063    static final boolean DEBUG_SD_INSTALL = false;
21064
21065    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21066
21067    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21068
21069    private boolean mMediaMounted = false;
21070
21071    static String getEncryptKey() {
21072        try {
21073            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21074                    SD_ENCRYPTION_KEYSTORE_NAME);
21075            if (sdEncKey == null) {
21076                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21077                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21078                if (sdEncKey == null) {
21079                    Slog.e(TAG, "Failed to create encryption keys");
21080                    return null;
21081                }
21082            }
21083            return sdEncKey;
21084        } catch (NoSuchAlgorithmException nsae) {
21085            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21086            return null;
21087        } catch (IOException ioe) {
21088            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21089            return null;
21090        }
21091    }
21092
21093    /*
21094     * Update media status on PackageManager.
21095     */
21096    @Override
21097    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21098        int callingUid = Binder.getCallingUid();
21099        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21100            throw new SecurityException("Media status can only be updated by the system");
21101        }
21102        // reader; this apparently protects mMediaMounted, but should probably
21103        // be a different lock in that case.
21104        synchronized (mPackages) {
21105            Log.i(TAG, "Updating external media status from "
21106                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21107                    + (mediaStatus ? "mounted" : "unmounted"));
21108            if (DEBUG_SD_INSTALL)
21109                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21110                        + ", mMediaMounted=" + mMediaMounted);
21111            if (mediaStatus == mMediaMounted) {
21112                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21113                        : 0, -1);
21114                mHandler.sendMessage(msg);
21115                return;
21116            }
21117            mMediaMounted = mediaStatus;
21118        }
21119        // Queue up an async operation since the package installation may take a
21120        // little while.
21121        mHandler.post(new Runnable() {
21122            public void run() {
21123                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21124            }
21125        });
21126    }
21127
21128    /**
21129     * Called by StorageManagerService when the initial ASECs to scan are available.
21130     * Should block until all the ASEC containers are finished being scanned.
21131     */
21132    public void scanAvailableAsecs() {
21133        updateExternalMediaStatusInner(true, false, false);
21134    }
21135
21136    /*
21137     * Collect information of applications on external media, map them against
21138     * existing containers and update information based on current mount status.
21139     * Please note that we always have to report status if reportStatus has been
21140     * set to true especially when unloading packages.
21141     */
21142    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21143            boolean externalStorage) {
21144        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21145        int[] uidArr = EmptyArray.INT;
21146
21147        final String[] list = PackageHelper.getSecureContainerList();
21148        if (ArrayUtils.isEmpty(list)) {
21149            Log.i(TAG, "No secure containers found");
21150        } else {
21151            // Process list of secure containers and categorize them
21152            // as active or stale based on their package internal state.
21153
21154            // reader
21155            synchronized (mPackages) {
21156                for (String cid : list) {
21157                    // Leave stages untouched for now; installer service owns them
21158                    if (PackageInstallerService.isStageName(cid)) continue;
21159
21160                    if (DEBUG_SD_INSTALL)
21161                        Log.i(TAG, "Processing container " + cid);
21162                    String pkgName = getAsecPackageName(cid);
21163                    if (pkgName == null) {
21164                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21165                        continue;
21166                    }
21167                    if (DEBUG_SD_INSTALL)
21168                        Log.i(TAG, "Looking for pkg : " + pkgName);
21169
21170                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21171                    if (ps == null) {
21172                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21173                        continue;
21174                    }
21175
21176                    /*
21177                     * Skip packages that are not external if we're unmounting
21178                     * external storage.
21179                     */
21180                    if (externalStorage && !isMounted && !isExternal(ps)) {
21181                        continue;
21182                    }
21183
21184                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21185                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21186                    // The package status is changed only if the code path
21187                    // matches between settings and the container id.
21188                    if (ps.codePathString != null
21189                            && ps.codePathString.startsWith(args.getCodePath())) {
21190                        if (DEBUG_SD_INSTALL) {
21191                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21192                                    + " at code path: " + ps.codePathString);
21193                        }
21194
21195                        // We do have a valid package installed on sdcard
21196                        processCids.put(args, ps.codePathString);
21197                        final int uid = ps.appId;
21198                        if (uid != -1) {
21199                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21200                        }
21201                    } else {
21202                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21203                                + ps.codePathString);
21204                    }
21205                }
21206            }
21207
21208            Arrays.sort(uidArr);
21209        }
21210
21211        // Process packages with valid entries.
21212        if (isMounted) {
21213            if (DEBUG_SD_INSTALL)
21214                Log.i(TAG, "Loading packages");
21215            loadMediaPackages(processCids, uidArr, externalStorage);
21216            startCleaningPackages();
21217            mInstallerService.onSecureContainersAvailable();
21218        } else {
21219            if (DEBUG_SD_INSTALL)
21220                Log.i(TAG, "Unloading packages");
21221            unloadMediaPackages(processCids, uidArr, reportStatus);
21222        }
21223    }
21224
21225    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21226            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21227        final int size = infos.size();
21228        final String[] packageNames = new String[size];
21229        final int[] packageUids = new int[size];
21230        for (int i = 0; i < size; i++) {
21231            final ApplicationInfo info = infos.get(i);
21232            packageNames[i] = info.packageName;
21233            packageUids[i] = info.uid;
21234        }
21235        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21236                finishedReceiver);
21237    }
21238
21239    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21240            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21241        sendResourcesChangedBroadcast(mediaStatus, replacing,
21242                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21243    }
21244
21245    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21246            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21247        int size = pkgList.length;
21248        if (size > 0) {
21249            // Send broadcasts here
21250            Bundle extras = new Bundle();
21251            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21252            if (uidArr != null) {
21253                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21254            }
21255            if (replacing) {
21256                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21257            }
21258            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21259                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21260            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21261        }
21262    }
21263
21264   /*
21265     * Look at potentially valid container ids from processCids If package
21266     * information doesn't match the one on record or package scanning fails,
21267     * the cid is added to list of removeCids. We currently don't delete stale
21268     * containers.
21269     */
21270    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21271            boolean externalStorage) {
21272        ArrayList<String> pkgList = new ArrayList<String>();
21273        Set<AsecInstallArgs> keys = processCids.keySet();
21274
21275        for (AsecInstallArgs args : keys) {
21276            String codePath = processCids.get(args);
21277            if (DEBUG_SD_INSTALL)
21278                Log.i(TAG, "Loading container : " + args.cid);
21279            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21280            try {
21281                // Make sure there are no container errors first.
21282                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21283                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21284                            + " when installing from sdcard");
21285                    continue;
21286                }
21287                // Check code path here.
21288                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21289                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21290                            + " does not match one in settings " + codePath);
21291                    continue;
21292                }
21293                // Parse package
21294                int parseFlags = mDefParseFlags;
21295                if (args.isExternalAsec()) {
21296                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21297                }
21298                if (args.isFwdLocked()) {
21299                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21300                }
21301
21302                synchronized (mInstallLock) {
21303                    PackageParser.Package pkg = null;
21304                    try {
21305                        // Sadly we don't know the package name yet to freeze it
21306                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21307                                SCAN_IGNORE_FROZEN, 0, null);
21308                    } catch (PackageManagerException e) {
21309                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21310                    }
21311                    // Scan the package
21312                    if (pkg != null) {
21313                        /*
21314                         * TODO why is the lock being held? doPostInstall is
21315                         * called in other places without the lock. This needs
21316                         * to be straightened out.
21317                         */
21318                        // writer
21319                        synchronized (mPackages) {
21320                            retCode = PackageManager.INSTALL_SUCCEEDED;
21321                            pkgList.add(pkg.packageName);
21322                            // Post process args
21323                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21324                                    pkg.applicationInfo.uid);
21325                        }
21326                    } else {
21327                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21328                    }
21329                }
21330
21331            } finally {
21332                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21333                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21334                }
21335            }
21336        }
21337        // writer
21338        synchronized (mPackages) {
21339            // If the platform SDK has changed since the last time we booted,
21340            // we need to re-grant app permission to catch any new ones that
21341            // appear. This is really a hack, and means that apps can in some
21342            // cases get permissions that the user didn't initially explicitly
21343            // allow... it would be nice to have some better way to handle
21344            // this situation.
21345            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21346                    : mSettings.getInternalVersion();
21347            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21348                    : StorageManager.UUID_PRIVATE_INTERNAL;
21349
21350            int updateFlags = UPDATE_PERMISSIONS_ALL;
21351            if (ver.sdkVersion != mSdkVersion) {
21352                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21353                        + mSdkVersion + "; regranting permissions for external");
21354                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21355            }
21356            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21357
21358            // Yay, everything is now upgraded
21359            ver.forceCurrent();
21360
21361            // can downgrade to reader
21362            // Persist settings
21363            mSettings.writeLPr();
21364        }
21365        // Send a broadcast to let everyone know we are done processing
21366        if (pkgList.size() > 0) {
21367            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21368        }
21369    }
21370
21371   /*
21372     * Utility method to unload a list of specified containers
21373     */
21374    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21375        // Just unmount all valid containers.
21376        for (AsecInstallArgs arg : cidArgs) {
21377            synchronized (mInstallLock) {
21378                arg.doPostDeleteLI(false);
21379           }
21380       }
21381   }
21382
21383    /*
21384     * Unload packages mounted on external media. This involves deleting package
21385     * data from internal structures, sending broadcasts about disabled packages,
21386     * gc'ing to free up references, unmounting all secure containers
21387     * corresponding to packages on external media, and posting a
21388     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21389     * that we always have to post this message if status has been requested no
21390     * matter what.
21391     */
21392    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21393            final boolean reportStatus) {
21394        if (DEBUG_SD_INSTALL)
21395            Log.i(TAG, "unloading media packages");
21396        ArrayList<String> pkgList = new ArrayList<String>();
21397        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21398        final Set<AsecInstallArgs> keys = processCids.keySet();
21399        for (AsecInstallArgs args : keys) {
21400            String pkgName = args.getPackageName();
21401            if (DEBUG_SD_INSTALL)
21402                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21403            // Delete package internally
21404            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21405            synchronized (mInstallLock) {
21406                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21407                final boolean res;
21408                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21409                        "unloadMediaPackages")) {
21410                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21411                            null);
21412                }
21413                if (res) {
21414                    pkgList.add(pkgName);
21415                } else {
21416                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21417                    failedList.add(args);
21418                }
21419            }
21420        }
21421
21422        // reader
21423        synchronized (mPackages) {
21424            // We didn't update the settings after removing each package;
21425            // write them now for all packages.
21426            mSettings.writeLPr();
21427        }
21428
21429        // We have to absolutely send UPDATED_MEDIA_STATUS only
21430        // after confirming that all the receivers processed the ordered
21431        // broadcast when packages get disabled, force a gc to clean things up.
21432        // and unload all the containers.
21433        if (pkgList.size() > 0) {
21434            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21435                    new IIntentReceiver.Stub() {
21436                public void performReceive(Intent intent, int resultCode, String data,
21437                        Bundle extras, boolean ordered, boolean sticky,
21438                        int sendingUser) throws RemoteException {
21439                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21440                            reportStatus ? 1 : 0, 1, keys);
21441                    mHandler.sendMessage(msg);
21442                }
21443            });
21444        } else {
21445            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21446                    keys);
21447            mHandler.sendMessage(msg);
21448        }
21449    }
21450
21451    private void loadPrivatePackages(final VolumeInfo vol) {
21452        mHandler.post(new Runnable() {
21453            @Override
21454            public void run() {
21455                loadPrivatePackagesInner(vol);
21456            }
21457        });
21458    }
21459
21460    private void loadPrivatePackagesInner(VolumeInfo vol) {
21461        final String volumeUuid = vol.fsUuid;
21462        if (TextUtils.isEmpty(volumeUuid)) {
21463            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21464            return;
21465        }
21466
21467        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21468        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21469        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21470
21471        final VersionInfo ver;
21472        final List<PackageSetting> packages;
21473        synchronized (mPackages) {
21474            ver = mSettings.findOrCreateVersion(volumeUuid);
21475            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21476        }
21477
21478        for (PackageSetting ps : packages) {
21479            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21480            synchronized (mInstallLock) {
21481                final PackageParser.Package pkg;
21482                try {
21483                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21484                    loaded.add(pkg.applicationInfo);
21485
21486                } catch (PackageManagerException e) {
21487                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21488                }
21489
21490                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21491                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21492                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21493                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21494                }
21495            }
21496        }
21497
21498        // Reconcile app data for all started/unlocked users
21499        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21500        final UserManager um = mContext.getSystemService(UserManager.class);
21501        UserManagerInternal umInternal = getUserManagerInternal();
21502        for (UserInfo user : um.getUsers()) {
21503            final int flags;
21504            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21505                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21506            } else if (umInternal.isUserRunning(user.id)) {
21507                flags = StorageManager.FLAG_STORAGE_DE;
21508            } else {
21509                continue;
21510            }
21511
21512            try {
21513                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21514                synchronized (mInstallLock) {
21515                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21516                }
21517            } catch (IllegalStateException e) {
21518                // Device was probably ejected, and we'll process that event momentarily
21519                Slog.w(TAG, "Failed to prepare storage: " + e);
21520            }
21521        }
21522
21523        synchronized (mPackages) {
21524            int updateFlags = UPDATE_PERMISSIONS_ALL;
21525            if (ver.sdkVersion != mSdkVersion) {
21526                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21527                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21528                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21529            }
21530            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21531
21532            // Yay, everything is now upgraded
21533            ver.forceCurrent();
21534
21535            mSettings.writeLPr();
21536        }
21537
21538        for (PackageFreezer freezer : freezers) {
21539            freezer.close();
21540        }
21541
21542        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21543        sendResourcesChangedBroadcast(true, false, loaded, null);
21544    }
21545
21546    private void unloadPrivatePackages(final VolumeInfo vol) {
21547        mHandler.post(new Runnable() {
21548            @Override
21549            public void run() {
21550                unloadPrivatePackagesInner(vol);
21551            }
21552        });
21553    }
21554
21555    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21556        final String volumeUuid = vol.fsUuid;
21557        if (TextUtils.isEmpty(volumeUuid)) {
21558            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21559            return;
21560        }
21561
21562        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21563        synchronized (mInstallLock) {
21564        synchronized (mPackages) {
21565            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21566            for (PackageSetting ps : packages) {
21567                if (ps.pkg == null) continue;
21568
21569                final ApplicationInfo info = ps.pkg.applicationInfo;
21570                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21571                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21572
21573                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21574                        "unloadPrivatePackagesInner")) {
21575                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21576                            false, null)) {
21577                        unloaded.add(info);
21578                    } else {
21579                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21580                    }
21581                }
21582
21583                // Try very hard to release any references to this package
21584                // so we don't risk the system server being killed due to
21585                // open FDs
21586                AttributeCache.instance().removePackage(ps.name);
21587            }
21588
21589            mSettings.writeLPr();
21590        }
21591        }
21592
21593        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21594        sendResourcesChangedBroadcast(false, false, unloaded, null);
21595
21596        // Try very hard to release any references to this path so we don't risk
21597        // the system server being killed due to open FDs
21598        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21599
21600        for (int i = 0; i < 3; i++) {
21601            System.gc();
21602            System.runFinalization();
21603        }
21604    }
21605
21606    private void assertPackageKnown(String volumeUuid, String packageName)
21607            throws PackageManagerException {
21608        synchronized (mPackages) {
21609            // Normalize package name to handle renamed packages
21610            packageName = normalizePackageNameLPr(packageName);
21611
21612            final PackageSetting ps = mSettings.mPackages.get(packageName);
21613            if (ps == null) {
21614                throw new PackageManagerException("Package " + packageName + " is unknown");
21615            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21616                throw new PackageManagerException(
21617                        "Package " + packageName + " found on unknown volume " + volumeUuid
21618                                + "; expected volume " + ps.volumeUuid);
21619            }
21620        }
21621    }
21622
21623    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21624            throws PackageManagerException {
21625        synchronized (mPackages) {
21626            // Normalize package name to handle renamed packages
21627            packageName = normalizePackageNameLPr(packageName);
21628
21629            final PackageSetting ps = mSettings.mPackages.get(packageName);
21630            if (ps == null) {
21631                throw new PackageManagerException("Package " + packageName + " is unknown");
21632            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21633                throw new PackageManagerException(
21634                        "Package " + packageName + " found on unknown volume " + volumeUuid
21635                                + "; expected volume " + ps.volumeUuid);
21636            } else if (!ps.getInstalled(userId)) {
21637                throw new PackageManagerException(
21638                        "Package " + packageName + " not installed for user " + userId);
21639            }
21640        }
21641    }
21642
21643    private List<String> collectAbsoluteCodePaths() {
21644        synchronized (mPackages) {
21645            List<String> codePaths = new ArrayList<>();
21646            final int packageCount = mSettings.mPackages.size();
21647            for (int i = 0; i < packageCount; i++) {
21648                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21649                codePaths.add(ps.codePath.getAbsolutePath());
21650            }
21651            return codePaths;
21652        }
21653    }
21654
21655    /**
21656     * Examine all apps present on given mounted volume, and destroy apps that
21657     * aren't expected, either due to uninstallation or reinstallation on
21658     * another volume.
21659     */
21660    private void reconcileApps(String volumeUuid) {
21661        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21662        List<File> filesToDelete = null;
21663
21664        final File[] files = FileUtils.listFilesOrEmpty(
21665                Environment.getDataAppDirectory(volumeUuid));
21666        for (File file : files) {
21667            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21668                    && !PackageInstallerService.isStageName(file.getName());
21669            if (!isPackage) {
21670                // Ignore entries which are not packages
21671                continue;
21672            }
21673
21674            String absolutePath = file.getAbsolutePath();
21675
21676            boolean pathValid = false;
21677            final int absoluteCodePathCount = absoluteCodePaths.size();
21678            for (int i = 0; i < absoluteCodePathCount; i++) {
21679                String absoluteCodePath = absoluteCodePaths.get(i);
21680                if (absolutePath.startsWith(absoluteCodePath)) {
21681                    pathValid = true;
21682                    break;
21683                }
21684            }
21685
21686            if (!pathValid) {
21687                if (filesToDelete == null) {
21688                    filesToDelete = new ArrayList<>();
21689                }
21690                filesToDelete.add(file);
21691            }
21692        }
21693
21694        if (filesToDelete != null) {
21695            final int fileToDeleteCount = filesToDelete.size();
21696            for (int i = 0; i < fileToDeleteCount; i++) {
21697                File fileToDelete = filesToDelete.get(i);
21698                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21699                synchronized (mInstallLock) {
21700                    removeCodePathLI(fileToDelete);
21701                }
21702            }
21703        }
21704    }
21705
21706    /**
21707     * Reconcile all app data for the given user.
21708     * <p>
21709     * Verifies that directories exist and that ownership and labeling is
21710     * correct for all installed apps on all mounted volumes.
21711     */
21712    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21713        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21714        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21715            final String volumeUuid = vol.getFsUuid();
21716            synchronized (mInstallLock) {
21717                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21718            }
21719        }
21720    }
21721
21722    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21723            boolean migrateAppData) {
21724        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21725    }
21726
21727    /**
21728     * Reconcile all app data on given mounted volume.
21729     * <p>
21730     * Destroys app data that isn't expected, either due to uninstallation or
21731     * reinstallation on another volume.
21732     * <p>
21733     * Verifies that directories exist and that ownership and labeling is
21734     * correct for all installed apps.
21735     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21736     */
21737    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21738            boolean migrateAppData, boolean onlyCoreApps) {
21739        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21740                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21741        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21742
21743        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21744        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21745
21746        // First look for stale data that doesn't belong, and check if things
21747        // have changed since we did our last restorecon
21748        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21749            if (StorageManager.isFileEncryptedNativeOrEmulated()
21750                    && !StorageManager.isUserKeyUnlocked(userId)) {
21751                throw new RuntimeException(
21752                        "Yikes, someone asked us to reconcile CE storage while " + userId
21753                                + " was still locked; this would have caused massive data loss!");
21754            }
21755
21756            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21757            for (File file : files) {
21758                final String packageName = file.getName();
21759                try {
21760                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21761                } catch (PackageManagerException e) {
21762                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21763                    try {
21764                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21765                                StorageManager.FLAG_STORAGE_CE, 0);
21766                    } catch (InstallerException e2) {
21767                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21768                    }
21769                }
21770            }
21771        }
21772        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21773            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21774            for (File file : files) {
21775                final String packageName = file.getName();
21776                try {
21777                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21778                } catch (PackageManagerException e) {
21779                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21780                    try {
21781                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21782                                StorageManager.FLAG_STORAGE_DE, 0);
21783                    } catch (InstallerException e2) {
21784                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21785                    }
21786                }
21787            }
21788        }
21789
21790        // Ensure that data directories are ready to roll for all packages
21791        // installed for this volume and user
21792        final List<PackageSetting> packages;
21793        synchronized (mPackages) {
21794            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21795        }
21796        int preparedCount = 0;
21797        for (PackageSetting ps : packages) {
21798            final String packageName = ps.name;
21799            if (ps.pkg == null) {
21800                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21801                // TODO: might be due to legacy ASEC apps; we should circle back
21802                // and reconcile again once they're scanned
21803                continue;
21804            }
21805            // Skip non-core apps if requested
21806            if (onlyCoreApps && !ps.pkg.coreApp) {
21807                result.add(packageName);
21808                continue;
21809            }
21810
21811            if (ps.getInstalled(userId)) {
21812                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21813                preparedCount++;
21814            }
21815        }
21816
21817        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21818        return result;
21819    }
21820
21821    /**
21822     * Prepare app data for the given app just after it was installed or
21823     * upgraded. This method carefully only touches users that it's installed
21824     * for, and it forces a restorecon to handle any seinfo changes.
21825     * <p>
21826     * Verifies that directories exist and that ownership and labeling is
21827     * correct for all installed apps. If there is an ownership mismatch, it
21828     * will try recovering system apps by wiping data; third-party app data is
21829     * left intact.
21830     * <p>
21831     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21832     */
21833    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21834        final PackageSetting ps;
21835        synchronized (mPackages) {
21836            ps = mSettings.mPackages.get(pkg.packageName);
21837            mSettings.writeKernelMappingLPr(ps);
21838        }
21839
21840        final UserManager um = mContext.getSystemService(UserManager.class);
21841        UserManagerInternal umInternal = getUserManagerInternal();
21842        for (UserInfo user : um.getUsers()) {
21843            final int flags;
21844            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21845                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21846            } else if (umInternal.isUserRunning(user.id)) {
21847                flags = StorageManager.FLAG_STORAGE_DE;
21848            } else {
21849                continue;
21850            }
21851
21852            if (ps.getInstalled(user.id)) {
21853                // TODO: when user data is locked, mark that we're still dirty
21854                prepareAppDataLIF(pkg, user.id, flags);
21855            }
21856        }
21857    }
21858
21859    /**
21860     * Prepare app data for the given app.
21861     * <p>
21862     * Verifies that directories exist and that ownership and labeling is
21863     * correct for all installed apps. If there is an ownership mismatch, this
21864     * will try recovering system apps by wiping data; third-party app data is
21865     * left intact.
21866     */
21867    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21868        if (pkg == null) {
21869            Slog.wtf(TAG, "Package was null!", new Throwable());
21870            return;
21871        }
21872        prepareAppDataLeafLIF(pkg, userId, flags);
21873        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21874        for (int i = 0; i < childCount; i++) {
21875            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21876        }
21877    }
21878
21879    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21880            boolean maybeMigrateAppData) {
21881        prepareAppDataLIF(pkg, userId, flags);
21882
21883        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21884            // We may have just shuffled around app data directories, so
21885            // prepare them one more time
21886            prepareAppDataLIF(pkg, userId, flags);
21887        }
21888    }
21889
21890    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21891        if (DEBUG_APP_DATA) {
21892            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21893                    + Integer.toHexString(flags));
21894        }
21895
21896        final String volumeUuid = pkg.volumeUuid;
21897        final String packageName = pkg.packageName;
21898        final ApplicationInfo app = pkg.applicationInfo;
21899        final int appId = UserHandle.getAppId(app.uid);
21900
21901        Preconditions.checkNotNull(app.seInfo);
21902
21903        long ceDataInode = -1;
21904        try {
21905            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21906                    appId, app.seInfo, app.targetSdkVersion);
21907        } catch (InstallerException e) {
21908            if (app.isSystemApp()) {
21909                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21910                        + ", but trying to recover: " + e);
21911                destroyAppDataLeafLIF(pkg, userId, flags);
21912                try {
21913                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21914                            appId, app.seInfo, app.targetSdkVersion);
21915                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21916                } catch (InstallerException e2) {
21917                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21918                }
21919            } else {
21920                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21921            }
21922        }
21923
21924        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21925            // TODO: mark this structure as dirty so we persist it!
21926            synchronized (mPackages) {
21927                final PackageSetting ps = mSettings.mPackages.get(packageName);
21928                if (ps != null) {
21929                    ps.setCeDataInode(ceDataInode, userId);
21930                }
21931            }
21932        }
21933
21934        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21935    }
21936
21937    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21938        if (pkg == null) {
21939            Slog.wtf(TAG, "Package was null!", new Throwable());
21940            return;
21941        }
21942        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21943        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21944        for (int i = 0; i < childCount; i++) {
21945            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21946        }
21947    }
21948
21949    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21950        final String volumeUuid = pkg.volumeUuid;
21951        final String packageName = pkg.packageName;
21952        final ApplicationInfo app = pkg.applicationInfo;
21953
21954        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21955            // Create a native library symlink only if we have native libraries
21956            // and if the native libraries are 32 bit libraries. We do not provide
21957            // this symlink for 64 bit libraries.
21958            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21959                final String nativeLibPath = app.nativeLibraryDir;
21960                try {
21961                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21962                            nativeLibPath, userId);
21963                } catch (InstallerException e) {
21964                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21965                }
21966            }
21967        }
21968    }
21969
21970    /**
21971     * For system apps on non-FBE devices, this method migrates any existing
21972     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21973     * requested by the app.
21974     */
21975    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21976        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21977                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21978            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21979                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21980            try {
21981                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21982                        storageTarget);
21983            } catch (InstallerException e) {
21984                logCriticalInfo(Log.WARN,
21985                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21986            }
21987            return true;
21988        } else {
21989            return false;
21990        }
21991    }
21992
21993    public PackageFreezer freezePackage(String packageName, String killReason) {
21994        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21995    }
21996
21997    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21998        return new PackageFreezer(packageName, userId, killReason);
21999    }
22000
22001    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22002            String killReason) {
22003        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22004    }
22005
22006    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22007            String killReason) {
22008        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22009            return new PackageFreezer();
22010        } else {
22011            return freezePackage(packageName, userId, killReason);
22012        }
22013    }
22014
22015    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22016            String killReason) {
22017        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22018    }
22019
22020    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22021            String killReason) {
22022        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22023            return new PackageFreezer();
22024        } else {
22025            return freezePackage(packageName, userId, killReason);
22026        }
22027    }
22028
22029    /**
22030     * Class that freezes and kills the given package upon creation, and
22031     * unfreezes it upon closing. This is typically used when doing surgery on
22032     * app code/data to prevent the app from running while you're working.
22033     */
22034    private class PackageFreezer implements AutoCloseable {
22035        private final String mPackageName;
22036        private final PackageFreezer[] mChildren;
22037
22038        private final boolean mWeFroze;
22039
22040        private final AtomicBoolean mClosed = new AtomicBoolean();
22041        private final CloseGuard mCloseGuard = CloseGuard.get();
22042
22043        /**
22044         * Create and return a stub freezer that doesn't actually do anything,
22045         * typically used when someone requested
22046         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22047         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22048         */
22049        public PackageFreezer() {
22050            mPackageName = null;
22051            mChildren = null;
22052            mWeFroze = false;
22053            mCloseGuard.open("close");
22054        }
22055
22056        public PackageFreezer(String packageName, int userId, String killReason) {
22057            synchronized (mPackages) {
22058                mPackageName = packageName;
22059                mWeFroze = mFrozenPackages.add(mPackageName);
22060
22061                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22062                if (ps != null) {
22063                    killApplication(ps.name, ps.appId, userId, killReason);
22064                }
22065
22066                final PackageParser.Package p = mPackages.get(packageName);
22067                if (p != null && p.childPackages != null) {
22068                    final int N = p.childPackages.size();
22069                    mChildren = new PackageFreezer[N];
22070                    for (int i = 0; i < N; i++) {
22071                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22072                                userId, killReason);
22073                    }
22074                } else {
22075                    mChildren = null;
22076                }
22077            }
22078            mCloseGuard.open("close");
22079        }
22080
22081        @Override
22082        protected void finalize() throws Throwable {
22083            try {
22084                mCloseGuard.warnIfOpen();
22085                close();
22086            } finally {
22087                super.finalize();
22088            }
22089        }
22090
22091        @Override
22092        public void close() {
22093            mCloseGuard.close();
22094            if (mClosed.compareAndSet(false, true)) {
22095                synchronized (mPackages) {
22096                    if (mWeFroze) {
22097                        mFrozenPackages.remove(mPackageName);
22098                    }
22099
22100                    if (mChildren != null) {
22101                        for (PackageFreezer freezer : mChildren) {
22102                            freezer.close();
22103                        }
22104                    }
22105                }
22106            }
22107        }
22108    }
22109
22110    /**
22111     * Verify that given package is currently frozen.
22112     */
22113    private void checkPackageFrozen(String packageName) {
22114        synchronized (mPackages) {
22115            if (!mFrozenPackages.contains(packageName)) {
22116                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22117            }
22118        }
22119    }
22120
22121    @Override
22122    public int movePackage(final String packageName, final String volumeUuid) {
22123        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22124
22125        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22126        final int moveId = mNextMoveId.getAndIncrement();
22127        mHandler.post(new Runnable() {
22128            @Override
22129            public void run() {
22130                try {
22131                    movePackageInternal(packageName, volumeUuid, moveId, user);
22132                } catch (PackageManagerException e) {
22133                    Slog.w(TAG, "Failed to move " + packageName, e);
22134                    mMoveCallbacks.notifyStatusChanged(moveId,
22135                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22136                }
22137            }
22138        });
22139        return moveId;
22140    }
22141
22142    private void movePackageInternal(final String packageName, final String volumeUuid,
22143            final int moveId, UserHandle user) throws PackageManagerException {
22144        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22145        final PackageManager pm = mContext.getPackageManager();
22146
22147        final boolean currentAsec;
22148        final String currentVolumeUuid;
22149        final File codeFile;
22150        final String installerPackageName;
22151        final String packageAbiOverride;
22152        final int appId;
22153        final String seinfo;
22154        final String label;
22155        final int targetSdkVersion;
22156        final PackageFreezer freezer;
22157        final int[] installedUserIds;
22158
22159        // reader
22160        synchronized (mPackages) {
22161            final PackageParser.Package pkg = mPackages.get(packageName);
22162            final PackageSetting ps = mSettings.mPackages.get(packageName);
22163            if (pkg == null || ps == null) {
22164                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22165            }
22166
22167            if (pkg.applicationInfo.isSystemApp()) {
22168                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22169                        "Cannot move system application");
22170            }
22171
22172            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22173            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22174                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22175            if (isInternalStorage && !allow3rdPartyOnInternal) {
22176                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22177                        "3rd party apps are not allowed on internal storage");
22178            }
22179
22180            if (pkg.applicationInfo.isExternalAsec()) {
22181                currentAsec = true;
22182                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22183            } else if (pkg.applicationInfo.isForwardLocked()) {
22184                currentAsec = true;
22185                currentVolumeUuid = "forward_locked";
22186            } else {
22187                currentAsec = false;
22188                currentVolumeUuid = ps.volumeUuid;
22189
22190                final File probe = new File(pkg.codePath);
22191                final File probeOat = new File(probe, "oat");
22192                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22193                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22194                            "Move only supported for modern cluster style installs");
22195                }
22196            }
22197
22198            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22199                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22200                        "Package already moved to " + volumeUuid);
22201            }
22202            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22203                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22204                        "Device admin cannot be moved");
22205            }
22206
22207            if (mFrozenPackages.contains(packageName)) {
22208                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22209                        "Failed to move already frozen package");
22210            }
22211
22212            codeFile = new File(pkg.codePath);
22213            installerPackageName = ps.installerPackageName;
22214            packageAbiOverride = ps.cpuAbiOverrideString;
22215            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22216            seinfo = pkg.applicationInfo.seInfo;
22217            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22218            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22219            freezer = freezePackage(packageName, "movePackageInternal");
22220            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22221        }
22222
22223        final Bundle extras = new Bundle();
22224        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22225        extras.putString(Intent.EXTRA_TITLE, label);
22226        mMoveCallbacks.notifyCreated(moveId, extras);
22227
22228        int installFlags;
22229        final boolean moveCompleteApp;
22230        final File measurePath;
22231
22232        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22233            installFlags = INSTALL_INTERNAL;
22234            moveCompleteApp = !currentAsec;
22235            measurePath = Environment.getDataAppDirectory(volumeUuid);
22236        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22237            installFlags = INSTALL_EXTERNAL;
22238            moveCompleteApp = false;
22239            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22240        } else {
22241            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22242            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22243                    || !volume.isMountedWritable()) {
22244                freezer.close();
22245                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22246                        "Move location not mounted private volume");
22247            }
22248
22249            Preconditions.checkState(!currentAsec);
22250
22251            installFlags = INSTALL_INTERNAL;
22252            moveCompleteApp = true;
22253            measurePath = Environment.getDataAppDirectory(volumeUuid);
22254        }
22255
22256        final PackageStats stats = new PackageStats(null, -1);
22257        synchronized (mInstaller) {
22258            for (int userId : installedUserIds) {
22259                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22260                    freezer.close();
22261                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22262                            "Failed to measure package size");
22263                }
22264            }
22265        }
22266
22267        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22268                + stats.dataSize);
22269
22270        final long startFreeBytes = measurePath.getFreeSpace();
22271        final long sizeBytes;
22272        if (moveCompleteApp) {
22273            sizeBytes = stats.codeSize + stats.dataSize;
22274        } else {
22275            sizeBytes = stats.codeSize;
22276        }
22277
22278        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22279            freezer.close();
22280            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22281                    "Not enough free space to move");
22282        }
22283
22284        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22285
22286        final CountDownLatch installedLatch = new CountDownLatch(1);
22287        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22288            @Override
22289            public void onUserActionRequired(Intent intent) throws RemoteException {
22290                throw new IllegalStateException();
22291            }
22292
22293            @Override
22294            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22295                    Bundle extras) throws RemoteException {
22296                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22297                        + PackageManager.installStatusToString(returnCode, msg));
22298
22299                installedLatch.countDown();
22300                freezer.close();
22301
22302                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22303                switch (status) {
22304                    case PackageInstaller.STATUS_SUCCESS:
22305                        mMoveCallbacks.notifyStatusChanged(moveId,
22306                                PackageManager.MOVE_SUCCEEDED);
22307                        break;
22308                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22309                        mMoveCallbacks.notifyStatusChanged(moveId,
22310                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22311                        break;
22312                    default:
22313                        mMoveCallbacks.notifyStatusChanged(moveId,
22314                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22315                        break;
22316                }
22317            }
22318        };
22319
22320        final MoveInfo move;
22321        if (moveCompleteApp) {
22322            // Kick off a thread to report progress estimates
22323            new Thread() {
22324                @Override
22325                public void run() {
22326                    while (true) {
22327                        try {
22328                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22329                                break;
22330                            }
22331                        } catch (InterruptedException ignored) {
22332                        }
22333
22334                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22335                        final int progress = 10 + (int) MathUtils.constrain(
22336                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22337                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22338                    }
22339                }
22340            }.start();
22341
22342            final String dataAppName = codeFile.getName();
22343            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22344                    dataAppName, appId, seinfo, targetSdkVersion);
22345        } else {
22346            move = null;
22347        }
22348
22349        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22350
22351        final Message msg = mHandler.obtainMessage(INIT_COPY);
22352        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22353        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22354                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22355                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22356                PackageManager.INSTALL_REASON_UNKNOWN);
22357        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22358        msg.obj = params;
22359
22360        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22361                System.identityHashCode(msg.obj));
22362        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22363                System.identityHashCode(msg.obj));
22364
22365        mHandler.sendMessage(msg);
22366    }
22367
22368    @Override
22369    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22370        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22371
22372        final int realMoveId = mNextMoveId.getAndIncrement();
22373        final Bundle extras = new Bundle();
22374        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22375        mMoveCallbacks.notifyCreated(realMoveId, extras);
22376
22377        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22378            @Override
22379            public void onCreated(int moveId, Bundle extras) {
22380                // Ignored
22381            }
22382
22383            @Override
22384            public void onStatusChanged(int moveId, int status, long estMillis) {
22385                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22386            }
22387        };
22388
22389        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22390        storage.setPrimaryStorageUuid(volumeUuid, callback);
22391        return realMoveId;
22392    }
22393
22394    @Override
22395    public int getMoveStatus(int moveId) {
22396        mContext.enforceCallingOrSelfPermission(
22397                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22398        return mMoveCallbacks.mLastStatus.get(moveId);
22399    }
22400
22401    @Override
22402    public void registerMoveCallback(IPackageMoveObserver callback) {
22403        mContext.enforceCallingOrSelfPermission(
22404                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22405        mMoveCallbacks.register(callback);
22406    }
22407
22408    @Override
22409    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22410        mContext.enforceCallingOrSelfPermission(
22411                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22412        mMoveCallbacks.unregister(callback);
22413    }
22414
22415    @Override
22416    public boolean setInstallLocation(int loc) {
22417        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22418                null);
22419        if (getInstallLocation() == loc) {
22420            return true;
22421        }
22422        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22423                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22424            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22425                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22426            return true;
22427        }
22428        return false;
22429   }
22430
22431    @Override
22432    public int getInstallLocation() {
22433        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22434                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22435                PackageHelper.APP_INSTALL_AUTO);
22436    }
22437
22438    /** Called by UserManagerService */
22439    void cleanUpUser(UserManagerService userManager, int userHandle) {
22440        synchronized (mPackages) {
22441            mDirtyUsers.remove(userHandle);
22442            mUserNeedsBadging.delete(userHandle);
22443            mSettings.removeUserLPw(userHandle);
22444            mPendingBroadcasts.remove(userHandle);
22445            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22446            removeUnusedPackagesLPw(userManager, userHandle);
22447        }
22448    }
22449
22450    /**
22451     * We're removing userHandle and would like to remove any downloaded packages
22452     * that are no longer in use by any other user.
22453     * @param userHandle the user being removed
22454     */
22455    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22456        final boolean DEBUG_CLEAN_APKS = false;
22457        int [] users = userManager.getUserIds();
22458        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22459        while (psit.hasNext()) {
22460            PackageSetting ps = psit.next();
22461            if (ps.pkg == null) {
22462                continue;
22463            }
22464            final String packageName = ps.pkg.packageName;
22465            // Skip over if system app
22466            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22467                continue;
22468            }
22469            if (DEBUG_CLEAN_APKS) {
22470                Slog.i(TAG, "Checking package " + packageName);
22471            }
22472            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22473            if (keep) {
22474                if (DEBUG_CLEAN_APKS) {
22475                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22476                }
22477            } else {
22478                for (int i = 0; i < users.length; i++) {
22479                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22480                        keep = true;
22481                        if (DEBUG_CLEAN_APKS) {
22482                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22483                                    + users[i]);
22484                        }
22485                        break;
22486                    }
22487                }
22488            }
22489            if (!keep) {
22490                if (DEBUG_CLEAN_APKS) {
22491                    Slog.i(TAG, "  Removing package " + packageName);
22492                }
22493                mHandler.post(new Runnable() {
22494                    public void run() {
22495                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22496                                userHandle, 0);
22497                    } //end run
22498                });
22499            }
22500        }
22501    }
22502
22503    /** Called by UserManagerService */
22504    void createNewUser(int userId, String[] disallowedPackages) {
22505        synchronized (mInstallLock) {
22506            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22507        }
22508        synchronized (mPackages) {
22509            scheduleWritePackageRestrictionsLocked(userId);
22510            scheduleWritePackageListLocked(userId);
22511            applyFactoryDefaultBrowserLPw(userId);
22512            primeDomainVerificationsLPw(userId);
22513        }
22514    }
22515
22516    void onNewUserCreated(final int userId) {
22517        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22518        // If permission review for legacy apps is required, we represent
22519        // dagerous permissions for such apps as always granted runtime
22520        // permissions to keep per user flag state whether review is needed.
22521        // Hence, if a new user is added we have to propagate dangerous
22522        // permission grants for these legacy apps.
22523        if (mPermissionReviewRequired) {
22524            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22525                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22526        }
22527    }
22528
22529    @Override
22530    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22531        mContext.enforceCallingOrSelfPermission(
22532                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22533                "Only package verification agents can read the verifier device identity");
22534
22535        synchronized (mPackages) {
22536            return mSettings.getVerifierDeviceIdentityLPw();
22537        }
22538    }
22539
22540    @Override
22541    public void setPermissionEnforced(String permission, boolean enforced) {
22542        // TODO: Now that we no longer change GID for storage, this should to away.
22543        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22544                "setPermissionEnforced");
22545        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22546            synchronized (mPackages) {
22547                if (mSettings.mReadExternalStorageEnforced == null
22548                        || mSettings.mReadExternalStorageEnforced != enforced) {
22549                    mSettings.mReadExternalStorageEnforced = enforced;
22550                    mSettings.writeLPr();
22551                }
22552            }
22553            // kill any non-foreground processes so we restart them and
22554            // grant/revoke the GID.
22555            final IActivityManager am = ActivityManager.getService();
22556            if (am != null) {
22557                final long token = Binder.clearCallingIdentity();
22558                try {
22559                    am.killProcessesBelowForeground("setPermissionEnforcement");
22560                } catch (RemoteException e) {
22561                } finally {
22562                    Binder.restoreCallingIdentity(token);
22563                }
22564            }
22565        } else {
22566            throw new IllegalArgumentException("No selective enforcement for " + permission);
22567        }
22568    }
22569
22570    @Override
22571    @Deprecated
22572    public boolean isPermissionEnforced(String permission) {
22573        return true;
22574    }
22575
22576    @Override
22577    public boolean isStorageLow() {
22578        final long token = Binder.clearCallingIdentity();
22579        try {
22580            final DeviceStorageMonitorInternal
22581                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22582            if (dsm != null) {
22583                return dsm.isMemoryLow();
22584            } else {
22585                return false;
22586            }
22587        } finally {
22588            Binder.restoreCallingIdentity(token);
22589        }
22590    }
22591
22592    @Override
22593    public IPackageInstaller getPackageInstaller() {
22594        return mInstallerService;
22595    }
22596
22597    private boolean userNeedsBadging(int userId) {
22598        int index = mUserNeedsBadging.indexOfKey(userId);
22599        if (index < 0) {
22600            final UserInfo userInfo;
22601            final long token = Binder.clearCallingIdentity();
22602            try {
22603                userInfo = sUserManager.getUserInfo(userId);
22604            } finally {
22605                Binder.restoreCallingIdentity(token);
22606            }
22607            final boolean b;
22608            if (userInfo != null && userInfo.isManagedProfile()) {
22609                b = true;
22610            } else {
22611                b = false;
22612            }
22613            mUserNeedsBadging.put(userId, b);
22614            return b;
22615        }
22616        return mUserNeedsBadging.valueAt(index);
22617    }
22618
22619    @Override
22620    public KeySet getKeySetByAlias(String packageName, String alias) {
22621        if (packageName == null || alias == null) {
22622            return null;
22623        }
22624        synchronized(mPackages) {
22625            final PackageParser.Package pkg = mPackages.get(packageName);
22626            if (pkg == null) {
22627                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22628                throw new IllegalArgumentException("Unknown package: " + packageName);
22629            }
22630            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22631            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22632        }
22633    }
22634
22635    @Override
22636    public KeySet getSigningKeySet(String packageName) {
22637        if (packageName == null) {
22638            return null;
22639        }
22640        synchronized(mPackages) {
22641            final PackageParser.Package pkg = mPackages.get(packageName);
22642            if (pkg == null) {
22643                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22644                throw new IllegalArgumentException("Unknown package: " + packageName);
22645            }
22646            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22647                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22648                throw new SecurityException("May not access signing KeySet of other apps.");
22649            }
22650            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22651            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22652        }
22653    }
22654
22655    @Override
22656    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22657        if (packageName == null || ks == null) {
22658            return false;
22659        }
22660        synchronized(mPackages) {
22661            final PackageParser.Package pkg = mPackages.get(packageName);
22662            if (pkg == null) {
22663                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22664                throw new IllegalArgumentException("Unknown package: " + packageName);
22665            }
22666            IBinder ksh = ks.getToken();
22667            if (ksh instanceof KeySetHandle) {
22668                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22669                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22670            }
22671            return false;
22672        }
22673    }
22674
22675    @Override
22676    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22677        if (packageName == null || ks == null) {
22678            return false;
22679        }
22680        synchronized(mPackages) {
22681            final PackageParser.Package pkg = mPackages.get(packageName);
22682            if (pkg == null) {
22683                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22684                throw new IllegalArgumentException("Unknown package: " + packageName);
22685            }
22686            IBinder ksh = ks.getToken();
22687            if (ksh instanceof KeySetHandle) {
22688                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22689                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22690            }
22691            return false;
22692        }
22693    }
22694
22695    private void deletePackageIfUnusedLPr(final String packageName) {
22696        PackageSetting ps = mSettings.mPackages.get(packageName);
22697        if (ps == null) {
22698            return;
22699        }
22700        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22701            // TODO Implement atomic delete if package is unused
22702            // It is currently possible that the package will be deleted even if it is installed
22703            // after this method returns.
22704            mHandler.post(new Runnable() {
22705                public void run() {
22706                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22707                            0, PackageManager.DELETE_ALL_USERS);
22708                }
22709            });
22710        }
22711    }
22712
22713    /**
22714     * Check and throw if the given before/after packages would be considered a
22715     * downgrade.
22716     */
22717    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22718            throws PackageManagerException {
22719        if (after.versionCode < before.mVersionCode) {
22720            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22721                    "Update version code " + after.versionCode + " is older than current "
22722                    + before.mVersionCode);
22723        } else if (after.versionCode == before.mVersionCode) {
22724            if (after.baseRevisionCode < before.baseRevisionCode) {
22725                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22726                        "Update base revision code " + after.baseRevisionCode
22727                        + " is older than current " + before.baseRevisionCode);
22728            }
22729
22730            if (!ArrayUtils.isEmpty(after.splitNames)) {
22731                for (int i = 0; i < after.splitNames.length; i++) {
22732                    final String splitName = after.splitNames[i];
22733                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22734                    if (j != -1) {
22735                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22736                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22737                                    "Update split " + splitName + " revision code "
22738                                    + after.splitRevisionCodes[i] + " is older than current "
22739                                    + before.splitRevisionCodes[j]);
22740                        }
22741                    }
22742                }
22743            }
22744        }
22745    }
22746
22747    private static class MoveCallbacks extends Handler {
22748        private static final int MSG_CREATED = 1;
22749        private static final int MSG_STATUS_CHANGED = 2;
22750
22751        private final RemoteCallbackList<IPackageMoveObserver>
22752                mCallbacks = new RemoteCallbackList<>();
22753
22754        private final SparseIntArray mLastStatus = new SparseIntArray();
22755
22756        public MoveCallbacks(Looper looper) {
22757            super(looper);
22758        }
22759
22760        public void register(IPackageMoveObserver callback) {
22761            mCallbacks.register(callback);
22762        }
22763
22764        public void unregister(IPackageMoveObserver callback) {
22765            mCallbacks.unregister(callback);
22766        }
22767
22768        @Override
22769        public void handleMessage(Message msg) {
22770            final SomeArgs args = (SomeArgs) msg.obj;
22771            final int n = mCallbacks.beginBroadcast();
22772            for (int i = 0; i < n; i++) {
22773                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22774                try {
22775                    invokeCallback(callback, msg.what, args);
22776                } catch (RemoteException ignored) {
22777                }
22778            }
22779            mCallbacks.finishBroadcast();
22780            args.recycle();
22781        }
22782
22783        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22784                throws RemoteException {
22785            switch (what) {
22786                case MSG_CREATED: {
22787                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22788                    break;
22789                }
22790                case MSG_STATUS_CHANGED: {
22791                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22792                    break;
22793                }
22794            }
22795        }
22796
22797        private void notifyCreated(int moveId, Bundle extras) {
22798            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22799
22800            final SomeArgs args = SomeArgs.obtain();
22801            args.argi1 = moveId;
22802            args.arg2 = extras;
22803            obtainMessage(MSG_CREATED, args).sendToTarget();
22804        }
22805
22806        private void notifyStatusChanged(int moveId, int status) {
22807            notifyStatusChanged(moveId, status, -1);
22808        }
22809
22810        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22811            Slog.v(TAG, "Move " + moveId + " status " + status);
22812
22813            final SomeArgs args = SomeArgs.obtain();
22814            args.argi1 = moveId;
22815            args.argi2 = status;
22816            args.arg3 = estMillis;
22817            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22818
22819            synchronized (mLastStatus) {
22820                mLastStatus.put(moveId, status);
22821            }
22822        }
22823    }
22824
22825    private final static class OnPermissionChangeListeners extends Handler {
22826        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22827
22828        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22829                new RemoteCallbackList<>();
22830
22831        public OnPermissionChangeListeners(Looper looper) {
22832            super(looper);
22833        }
22834
22835        @Override
22836        public void handleMessage(Message msg) {
22837            switch (msg.what) {
22838                case MSG_ON_PERMISSIONS_CHANGED: {
22839                    final int uid = msg.arg1;
22840                    handleOnPermissionsChanged(uid);
22841                } break;
22842            }
22843        }
22844
22845        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22846            mPermissionListeners.register(listener);
22847
22848        }
22849
22850        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22851            mPermissionListeners.unregister(listener);
22852        }
22853
22854        public void onPermissionsChanged(int uid) {
22855            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22856                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22857            }
22858        }
22859
22860        private void handleOnPermissionsChanged(int uid) {
22861            final int count = mPermissionListeners.beginBroadcast();
22862            try {
22863                for (int i = 0; i < count; i++) {
22864                    IOnPermissionsChangeListener callback = mPermissionListeners
22865                            .getBroadcastItem(i);
22866                    try {
22867                        callback.onPermissionsChanged(uid);
22868                    } catch (RemoteException e) {
22869                        Log.e(TAG, "Permission listener is dead", e);
22870                    }
22871                }
22872            } finally {
22873                mPermissionListeners.finishBroadcast();
22874            }
22875        }
22876    }
22877
22878    private class PackageManagerInternalImpl extends PackageManagerInternal {
22879        @Override
22880        public void setLocationPackagesProvider(PackagesProvider provider) {
22881            synchronized (mPackages) {
22882                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22883            }
22884        }
22885
22886        @Override
22887        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22888            synchronized (mPackages) {
22889                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22890            }
22891        }
22892
22893        @Override
22894        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22895            synchronized (mPackages) {
22896                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22897            }
22898        }
22899
22900        @Override
22901        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22902            synchronized (mPackages) {
22903                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22904            }
22905        }
22906
22907        @Override
22908        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22909            synchronized (mPackages) {
22910                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22911            }
22912        }
22913
22914        @Override
22915        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22916            synchronized (mPackages) {
22917                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22918            }
22919        }
22920
22921        @Override
22922        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22923            synchronized (mPackages) {
22924                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22925                        packageName, userId);
22926            }
22927        }
22928
22929        @Override
22930        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22931            synchronized (mPackages) {
22932                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22933                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22934                        packageName, userId);
22935            }
22936        }
22937
22938        @Override
22939        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22940            synchronized (mPackages) {
22941                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22942                        packageName, userId);
22943            }
22944        }
22945
22946        @Override
22947        public void setKeepUninstalledPackages(final List<String> packageList) {
22948            Preconditions.checkNotNull(packageList);
22949            List<String> removedFromList = null;
22950            synchronized (mPackages) {
22951                if (mKeepUninstalledPackages != null) {
22952                    final int packagesCount = mKeepUninstalledPackages.size();
22953                    for (int i = 0; i < packagesCount; i++) {
22954                        String oldPackage = mKeepUninstalledPackages.get(i);
22955                        if (packageList != null && packageList.contains(oldPackage)) {
22956                            continue;
22957                        }
22958                        if (removedFromList == null) {
22959                            removedFromList = new ArrayList<>();
22960                        }
22961                        removedFromList.add(oldPackage);
22962                    }
22963                }
22964                mKeepUninstalledPackages = new ArrayList<>(packageList);
22965                if (removedFromList != null) {
22966                    final int removedCount = removedFromList.size();
22967                    for (int i = 0; i < removedCount; i++) {
22968                        deletePackageIfUnusedLPr(removedFromList.get(i));
22969                    }
22970                }
22971            }
22972        }
22973
22974        @Override
22975        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22976            synchronized (mPackages) {
22977                // If we do not support permission review, done.
22978                if (!mPermissionReviewRequired) {
22979                    return false;
22980                }
22981
22982                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22983                if (packageSetting == null) {
22984                    return false;
22985                }
22986
22987                // Permission review applies only to apps not supporting the new permission model.
22988                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22989                    return false;
22990                }
22991
22992                // Legacy apps have the permission and get user consent on launch.
22993                PermissionsState permissionsState = packageSetting.getPermissionsState();
22994                return permissionsState.isPermissionReviewRequired(userId);
22995            }
22996        }
22997
22998        @Override
22999        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
23000            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
23001        }
23002
23003        @Override
23004        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23005                int userId) {
23006            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23007        }
23008
23009        @Override
23010        public void setDeviceAndProfileOwnerPackages(
23011                int deviceOwnerUserId, String deviceOwnerPackage,
23012                SparseArray<String> profileOwnerPackages) {
23013            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23014                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23015        }
23016
23017        @Override
23018        public boolean isPackageDataProtected(int userId, String packageName) {
23019            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23020        }
23021
23022        @Override
23023        public boolean isPackageEphemeral(int userId, String packageName) {
23024            synchronized (mPackages) {
23025                final PackageSetting ps = mSettings.mPackages.get(packageName);
23026                return ps != null ? ps.getInstantApp(userId) : false;
23027            }
23028        }
23029
23030        @Override
23031        public boolean wasPackageEverLaunched(String packageName, int userId) {
23032            synchronized (mPackages) {
23033                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23034            }
23035        }
23036
23037        @Override
23038        public void grantRuntimePermission(String packageName, String name, int userId,
23039                boolean overridePolicy) {
23040            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23041                    overridePolicy);
23042        }
23043
23044        @Override
23045        public void revokeRuntimePermission(String packageName, String name, int userId,
23046                boolean overridePolicy) {
23047            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23048                    overridePolicy);
23049        }
23050
23051        @Override
23052        public String getNameForUid(int uid) {
23053            return PackageManagerService.this.getNameForUid(uid);
23054        }
23055
23056        @Override
23057        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23058                Intent origIntent, String resolvedType, String callingPackage, int userId) {
23059            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23060                    responseObj, origIntent, resolvedType, callingPackage, userId);
23061        }
23062
23063        @Override
23064        public void grantEphemeralAccess(int userId, Intent intent,
23065                int targetAppId, int ephemeralAppId) {
23066            synchronized (mPackages) {
23067                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23068                        targetAppId, ephemeralAppId);
23069            }
23070        }
23071
23072        @Override
23073        public void pruneInstantApps() {
23074            synchronized (mPackages) {
23075                mInstantAppRegistry.pruneInstantAppsLPw();
23076            }
23077        }
23078
23079        @Override
23080        public String getSetupWizardPackageName() {
23081            return mSetupWizardPackage;
23082        }
23083
23084        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23085            if (policy != null) {
23086                mExternalSourcesPolicy = policy;
23087            }
23088        }
23089
23090        @Override
23091        public boolean isPackagePersistent(String packageName) {
23092            synchronized (mPackages) {
23093                PackageParser.Package pkg = mPackages.get(packageName);
23094                return pkg != null
23095                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23096                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23097                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23098                        : false;
23099            }
23100        }
23101
23102        @Override
23103        public List<PackageInfo> getOverlayPackages(int userId) {
23104            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23105            synchronized (mPackages) {
23106                for (PackageParser.Package p : mPackages.values()) {
23107                    if (p.mOverlayTarget != null) {
23108                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23109                        if (pkg != null) {
23110                            overlayPackages.add(pkg);
23111                        }
23112                    }
23113                }
23114            }
23115            return overlayPackages;
23116        }
23117
23118        @Override
23119        public List<String> getTargetPackageNames(int userId) {
23120            List<String> targetPackages = new ArrayList<>();
23121            synchronized (mPackages) {
23122                for (PackageParser.Package p : mPackages.values()) {
23123                    if (p.mOverlayTarget == null) {
23124                        targetPackages.add(p.packageName);
23125                    }
23126                }
23127            }
23128            return targetPackages;
23129        }
23130
23131        @Override
23132        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23133                @Nullable List<String> overlayPackageNames) {
23134            synchronized (mPackages) {
23135                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23136                    Slog.e(TAG, "failed to find package " + targetPackageName);
23137                    return false;
23138                }
23139
23140                ArrayList<String> paths = null;
23141                if (overlayPackageNames != null) {
23142                    final int N = overlayPackageNames.size();
23143                    paths = new ArrayList<String>(N);
23144                    for (int i = 0; i < N; i++) {
23145                        final String packageName = overlayPackageNames.get(i);
23146                        final PackageParser.Package pkg = mPackages.get(packageName);
23147                        if (pkg == null) {
23148                            Slog.e(TAG, "failed to find package " + packageName);
23149                            return false;
23150                        }
23151                        paths.add(pkg.baseCodePath);
23152                    }
23153                }
23154
23155                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23156                    mEnabledOverlayPaths.get(userId);
23157                if (userSpecificOverlays == null) {
23158                    userSpecificOverlays = new ArrayMap<String, ArrayList<String>>();
23159                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23160                }
23161
23162                if (paths != null && paths.size() > 0) {
23163                    userSpecificOverlays.put(targetPackageName, paths);
23164                } else {
23165                    userSpecificOverlays.remove(targetPackageName);
23166                }
23167                return true;
23168            }
23169        }
23170
23171        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23172                int flags, int userId) {
23173            return resolveIntentInternal(
23174                    intent, resolvedType, flags, userId, true /*includeInstantApp*/);
23175        }
23176    }
23177
23178    @Override
23179    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23180        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23181        synchronized (mPackages) {
23182            final long identity = Binder.clearCallingIdentity();
23183            try {
23184                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23185                        packageNames, userId);
23186            } finally {
23187                Binder.restoreCallingIdentity(identity);
23188            }
23189        }
23190    }
23191
23192    @Override
23193    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23194        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23195        synchronized (mPackages) {
23196            final long identity = Binder.clearCallingIdentity();
23197            try {
23198                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23199                        packageNames, userId);
23200            } finally {
23201                Binder.restoreCallingIdentity(identity);
23202            }
23203        }
23204    }
23205
23206    private static void enforceSystemOrPhoneCaller(String tag) {
23207        int callingUid = Binder.getCallingUid();
23208        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23209            throw new SecurityException(
23210                    "Cannot call " + tag + " from UID " + callingUid);
23211        }
23212    }
23213
23214    boolean isHistoricalPackageUsageAvailable() {
23215        return mPackageUsage.isHistoricalPackageUsageAvailable();
23216    }
23217
23218    /**
23219     * Return a <b>copy</b> of the collection of packages known to the package manager.
23220     * @return A copy of the values of mPackages.
23221     */
23222    Collection<PackageParser.Package> getPackages() {
23223        synchronized (mPackages) {
23224            return new ArrayList<>(mPackages.values());
23225        }
23226    }
23227
23228    /**
23229     * Logs process start information (including base APK hash) to the security log.
23230     * @hide
23231     */
23232    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23233            String apkFile, int pid) {
23234        if (!SecurityLog.isLoggingEnabled()) {
23235            return;
23236        }
23237        Bundle data = new Bundle();
23238        data.putLong("startTimestamp", System.currentTimeMillis());
23239        data.putString("processName", processName);
23240        data.putInt("uid", uid);
23241        data.putString("seinfo", seinfo);
23242        data.putString("apkFile", apkFile);
23243        data.putInt("pid", pid);
23244        Message msg = mProcessLoggingHandler.obtainMessage(
23245                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23246        msg.setData(data);
23247        mProcessLoggingHandler.sendMessage(msg);
23248    }
23249
23250    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23251        return mCompilerStats.getPackageStats(pkgName);
23252    }
23253
23254    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23255        return getOrCreateCompilerPackageStats(pkg.packageName);
23256    }
23257
23258    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23259        return mCompilerStats.getOrCreatePackageStats(pkgName);
23260    }
23261
23262    public void deleteCompilerPackageStats(String pkgName) {
23263        mCompilerStats.deletePackageStats(pkgName);
23264    }
23265
23266    @Override
23267    public int getInstallReason(String packageName, int userId) {
23268        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23269                true /* requireFullPermission */, false /* checkShell */,
23270                "get install reason");
23271        synchronized (mPackages) {
23272            final PackageSetting ps = mSettings.mPackages.get(packageName);
23273            if (ps != null) {
23274                return ps.getInstallReason(userId);
23275            }
23276        }
23277        return PackageManager.INSTALL_REASON_UNKNOWN;
23278    }
23279
23280    @Override
23281    public boolean canRequestPackageInstalls(String packageName, int userId) {
23282        int callingUid = Binder.getCallingUid();
23283        int uid = getPackageUid(packageName, 0, userId);
23284        if (callingUid != uid && callingUid != Process.ROOT_UID
23285                && callingUid != Process.SYSTEM_UID) {
23286            throw new SecurityException(
23287                    "Caller uid " + callingUid + " does not own package " + packageName);
23288        }
23289        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23290        if (info == null) {
23291            return false;
23292        }
23293        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23294            throw new UnsupportedOperationException(
23295                    "Operation only supported on apps targeting Android O or higher");
23296        }
23297        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23298        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23299        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23300            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23301        }
23302        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23303            return false;
23304        }
23305        if (mExternalSourcesPolicy != null) {
23306            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23307            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23308                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23309            }
23310        }
23311        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23312    }
23313}
23314