PackageManagerService.java revision 2f2053b939fdd1aee80d7bba531707d56f498c07
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                result.add(ephemeralInstaller);
6321            }
6322            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6323        }
6324        if (sortResult) {
6325            Collections.sort(result, mResolvePrioritySorter);
6326        }
6327        return applyPostResolutionFilter(result, instantAppPkgName);
6328    }
6329
6330    private static class CrossProfileDomainInfo {
6331        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6332        ResolveInfo resolveInfo;
6333        /* Best domain verification status of the activities found in the other profile */
6334        int bestDomainVerificationStatus;
6335    }
6336
6337    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6338            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6339        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6340                sourceUserId)) {
6341            return null;
6342        }
6343        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6344                resolvedType, flags, parentUserId);
6345
6346        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6347            return null;
6348        }
6349        CrossProfileDomainInfo result = null;
6350        int size = resultTargetUser.size();
6351        for (int i = 0; i < size; i++) {
6352            ResolveInfo riTargetUser = resultTargetUser.get(i);
6353            // Intent filter verification is only for filters that specify a host. So don't return
6354            // those that handle all web uris.
6355            if (riTargetUser.handleAllWebDataURI) {
6356                continue;
6357            }
6358            String packageName = riTargetUser.activityInfo.packageName;
6359            PackageSetting ps = mSettings.mPackages.get(packageName);
6360            if (ps == null) {
6361                continue;
6362            }
6363            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6364            int status = (int)(verificationState >> 32);
6365            if (result == null) {
6366                result = new CrossProfileDomainInfo();
6367                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6368                        sourceUserId, parentUserId);
6369                result.bestDomainVerificationStatus = status;
6370            } else {
6371                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6372                        result.bestDomainVerificationStatus);
6373            }
6374        }
6375        // Don't consider matches with status NEVER across profiles.
6376        if (result != null && result.bestDomainVerificationStatus
6377                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6378            return null;
6379        }
6380        return result;
6381    }
6382
6383    /**
6384     * Verification statuses are ordered from the worse to the best, except for
6385     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6386     */
6387    private int bestDomainVerificationStatus(int status1, int status2) {
6388        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6389            return status2;
6390        }
6391        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6392            return status1;
6393        }
6394        return (int) MathUtils.max(status1, status2);
6395    }
6396
6397    private boolean isUserEnabled(int userId) {
6398        long callingId = Binder.clearCallingIdentity();
6399        try {
6400            UserInfo userInfo = sUserManager.getUserInfo(userId);
6401            return userInfo != null && userInfo.isEnabled();
6402        } finally {
6403            Binder.restoreCallingIdentity(callingId);
6404        }
6405    }
6406
6407    /**
6408     * Filter out activities with systemUserOnly flag set, when current user is not System.
6409     *
6410     * @return filtered list
6411     */
6412    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6413        if (userId == UserHandle.USER_SYSTEM) {
6414            return resolveInfos;
6415        }
6416        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6417            ResolveInfo info = resolveInfos.get(i);
6418            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6419                resolveInfos.remove(i);
6420            }
6421        }
6422        return resolveInfos;
6423    }
6424
6425    /**
6426     * Filters out ephemeral activities.
6427     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6428     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6429     *
6430     * @param resolveInfos The pre-filtered list of resolved activities
6431     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6432     *          is performed.
6433     * @return A filtered list of resolved activities.
6434     */
6435    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6436            String ephemeralPkgName) {
6437        // TODO: When adding on-demand split support for non-instant apps, remove this check
6438        // and always apply post filtering
6439        if (ephemeralPkgName == null) {
6440            return resolveInfos;
6441        }
6442        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6443            final ResolveInfo info = resolveInfos.get(i);
6444            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6445            // allow activities that are defined in the provided package
6446            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6447                if (info.activityInfo.splitName != null
6448                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6449                                info.activityInfo.splitName)) {
6450                    // requested activity is defined in a split that hasn't been installed yet.
6451                    // add the installer to the resolve list
6452                    if (DEBUG_EPHEMERAL) {
6453                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6454                    }
6455                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6456                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6457                            info.activityInfo.packageName, info.activityInfo.splitName,
6458                            info.activityInfo.applicationInfo.versionCode);
6459                    // make sure this resolver is the default
6460                    installerInfo.isDefault = true;
6461                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6462                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6463                    // add a non-generic filter
6464                    installerInfo.filter = new IntentFilter();
6465                    // load resources from the correct package
6466                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6467                    resolveInfos.set(i, installerInfo);
6468                }
6469                continue;
6470            }
6471            // allow activities that have been explicitly exposed to ephemeral apps
6472            if (!isEphemeralApp
6473                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6474                continue;
6475            }
6476            resolveInfos.remove(i);
6477        }
6478        return resolveInfos;
6479    }
6480
6481    /**
6482     * @param resolveInfos list of resolve infos in descending priority order
6483     * @return if the list contains a resolve info with non-negative priority
6484     */
6485    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6486        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6487    }
6488
6489    private static boolean hasWebURI(Intent intent) {
6490        if (intent.getData() == null) {
6491            return false;
6492        }
6493        final String scheme = intent.getScheme();
6494        if (TextUtils.isEmpty(scheme)) {
6495            return false;
6496        }
6497        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6498    }
6499
6500    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6501            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6502            int userId) {
6503        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6504
6505        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6506            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6507                    candidates.size());
6508        }
6509
6510        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6511        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6512        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6513        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6514        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6515        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6516
6517        synchronized (mPackages) {
6518            final int count = candidates.size();
6519            // First, try to use linked apps. Partition the candidates into four lists:
6520            // one for the final results, one for the "do not use ever", one for "undefined status"
6521            // and finally one for "browser app type".
6522            for (int n=0; n<count; n++) {
6523                ResolveInfo info = candidates.get(n);
6524                String packageName = info.activityInfo.packageName;
6525                PackageSetting ps = mSettings.mPackages.get(packageName);
6526                if (ps != null) {
6527                    // Add to the special match all list (Browser use case)
6528                    if (info.handleAllWebDataURI) {
6529                        matchAllList.add(info);
6530                        continue;
6531                    }
6532                    // Try to get the status from User settings first
6533                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6534                    int status = (int)(packedStatus >> 32);
6535                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6536                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6537                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6538                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6539                                    + " : linkgen=" + linkGeneration);
6540                        }
6541                        // Use link-enabled generation as preferredOrder, i.e.
6542                        // prefer newly-enabled over earlier-enabled.
6543                        info.preferredOrder = linkGeneration;
6544                        alwaysList.add(info);
6545                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6546                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6547                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6548                        }
6549                        neverList.add(info);
6550                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6551                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6552                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6553                        }
6554                        alwaysAskList.add(info);
6555                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6556                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6557                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6558                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6559                        }
6560                        undefinedList.add(info);
6561                    }
6562                }
6563            }
6564
6565            // We'll want to include browser possibilities in a few cases
6566            boolean includeBrowser = false;
6567
6568            // First try to add the "always" resolution(s) for the current user, if any
6569            if (alwaysList.size() > 0) {
6570                result.addAll(alwaysList);
6571            } else {
6572                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6573                result.addAll(undefinedList);
6574                // Maybe add one for the other profile.
6575                if (xpDomainInfo != null && (
6576                        xpDomainInfo.bestDomainVerificationStatus
6577                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6578                    result.add(xpDomainInfo.resolveInfo);
6579                }
6580                includeBrowser = true;
6581            }
6582
6583            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6584            // If there were 'always' entries their preferred order has been set, so we also
6585            // back that off to make the alternatives equivalent
6586            if (alwaysAskList.size() > 0) {
6587                for (ResolveInfo i : result) {
6588                    i.preferredOrder = 0;
6589                }
6590                result.addAll(alwaysAskList);
6591                includeBrowser = true;
6592            }
6593
6594            if (includeBrowser) {
6595                // Also add browsers (all of them or only the default one)
6596                if (DEBUG_DOMAIN_VERIFICATION) {
6597                    Slog.v(TAG, "   ...including browsers in candidate set");
6598                }
6599                if ((matchFlags & MATCH_ALL) != 0) {
6600                    result.addAll(matchAllList);
6601                } else {
6602                    // Browser/generic handling case.  If there's a default browser, go straight
6603                    // to that (but only if there is no other higher-priority match).
6604                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6605                    int maxMatchPrio = 0;
6606                    ResolveInfo defaultBrowserMatch = null;
6607                    final int numCandidates = matchAllList.size();
6608                    for (int n = 0; n < numCandidates; n++) {
6609                        ResolveInfo info = matchAllList.get(n);
6610                        // track the highest overall match priority...
6611                        if (info.priority > maxMatchPrio) {
6612                            maxMatchPrio = info.priority;
6613                        }
6614                        // ...and the highest-priority default browser match
6615                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6616                            if (defaultBrowserMatch == null
6617                                    || (defaultBrowserMatch.priority < info.priority)) {
6618                                if (debug) {
6619                                    Slog.v(TAG, "Considering default browser match " + info);
6620                                }
6621                                defaultBrowserMatch = info;
6622                            }
6623                        }
6624                    }
6625                    if (defaultBrowserMatch != null
6626                            && defaultBrowserMatch.priority >= maxMatchPrio
6627                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6628                    {
6629                        if (debug) {
6630                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6631                        }
6632                        result.add(defaultBrowserMatch);
6633                    } else {
6634                        result.addAll(matchAllList);
6635                    }
6636                }
6637
6638                // If there is nothing selected, add all candidates and remove the ones that the user
6639                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6640                if (result.size() == 0) {
6641                    result.addAll(candidates);
6642                    result.removeAll(neverList);
6643                }
6644            }
6645        }
6646        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6647            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6648                    result.size());
6649            for (ResolveInfo info : result) {
6650                Slog.v(TAG, "  + " + info.activityInfo);
6651            }
6652        }
6653        return result;
6654    }
6655
6656    // Returns a packed value as a long:
6657    //
6658    // high 'int'-sized word: link status: undefined/ask/never/always.
6659    // low 'int'-sized word: relative priority among 'always' results.
6660    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6661        long result = ps.getDomainVerificationStatusForUser(userId);
6662        // if none available, get the master status
6663        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6664            if (ps.getIntentFilterVerificationInfo() != null) {
6665                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6666            }
6667        }
6668        return result;
6669    }
6670
6671    private ResolveInfo querySkipCurrentProfileIntents(
6672            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6673            int flags, int sourceUserId) {
6674        if (matchingFilters != null) {
6675            int size = matchingFilters.size();
6676            for (int i = 0; i < size; i ++) {
6677                CrossProfileIntentFilter filter = matchingFilters.get(i);
6678                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6679                    // Checking if there are activities in the target user that can handle the
6680                    // intent.
6681                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6682                            resolvedType, flags, sourceUserId);
6683                    if (resolveInfo != null) {
6684                        return resolveInfo;
6685                    }
6686                }
6687            }
6688        }
6689        return null;
6690    }
6691
6692    // Return matching ResolveInfo in target user if any.
6693    private ResolveInfo queryCrossProfileIntents(
6694            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6695            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6696        if (matchingFilters != null) {
6697            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6698            // match the same intent. For performance reasons, it is better not to
6699            // run queryIntent twice for the same userId
6700            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6701            int size = matchingFilters.size();
6702            for (int i = 0; i < size; i++) {
6703                CrossProfileIntentFilter filter = matchingFilters.get(i);
6704                int targetUserId = filter.getTargetUserId();
6705                boolean skipCurrentProfile =
6706                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6707                boolean skipCurrentProfileIfNoMatchFound =
6708                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6709                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6710                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6711                    // Checking if there are activities in the target user that can handle the
6712                    // intent.
6713                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6714                            resolvedType, flags, sourceUserId);
6715                    if (resolveInfo != null) return resolveInfo;
6716                    alreadyTriedUserIds.put(targetUserId, true);
6717                }
6718            }
6719        }
6720        return null;
6721    }
6722
6723    /**
6724     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6725     * will forward the intent to the filter's target user.
6726     * Otherwise, returns null.
6727     */
6728    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6729            String resolvedType, int flags, int sourceUserId) {
6730        int targetUserId = filter.getTargetUserId();
6731        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6732                resolvedType, flags, targetUserId);
6733        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6734            // If all the matches in the target profile are suspended, return null.
6735            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6736                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6737                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6738                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6739                            targetUserId);
6740                }
6741            }
6742        }
6743        return null;
6744    }
6745
6746    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6747            int sourceUserId, int targetUserId) {
6748        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6749        long ident = Binder.clearCallingIdentity();
6750        boolean targetIsProfile;
6751        try {
6752            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6753        } finally {
6754            Binder.restoreCallingIdentity(ident);
6755        }
6756        String className;
6757        if (targetIsProfile) {
6758            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6759        } else {
6760            className = FORWARD_INTENT_TO_PARENT;
6761        }
6762        ComponentName forwardingActivityComponentName = new ComponentName(
6763                mAndroidApplication.packageName, className);
6764        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6765                sourceUserId);
6766        if (!targetIsProfile) {
6767            forwardingActivityInfo.showUserIcon = targetUserId;
6768            forwardingResolveInfo.noResourceId = true;
6769        }
6770        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6771        forwardingResolveInfo.priority = 0;
6772        forwardingResolveInfo.preferredOrder = 0;
6773        forwardingResolveInfo.match = 0;
6774        forwardingResolveInfo.isDefault = true;
6775        forwardingResolveInfo.filter = filter;
6776        forwardingResolveInfo.targetUserId = targetUserId;
6777        return forwardingResolveInfo;
6778    }
6779
6780    @Override
6781    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6782            Intent[] specifics, String[] specificTypes, Intent intent,
6783            String resolvedType, int flags, int userId) {
6784        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6785                specificTypes, intent, resolvedType, flags, userId));
6786    }
6787
6788    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6789            Intent[] specifics, String[] specificTypes, Intent intent,
6790            String resolvedType, int flags, int userId) {
6791        if (!sUserManager.exists(userId)) return Collections.emptyList();
6792        flags = updateFlagsForResolve(flags, userId, intent, false);
6793        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6794                false /* requireFullPermission */, false /* checkShell */,
6795                "query intent activity options");
6796        final String resultsAction = intent.getAction();
6797
6798        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6799                | PackageManager.GET_RESOLVED_FILTER, userId);
6800
6801        if (DEBUG_INTENT_MATCHING) {
6802            Log.v(TAG, "Query " + intent + ": " + results);
6803        }
6804
6805        int specificsPos = 0;
6806        int N;
6807
6808        // todo: note that the algorithm used here is O(N^2).  This
6809        // isn't a problem in our current environment, but if we start running
6810        // into situations where we have more than 5 or 10 matches then this
6811        // should probably be changed to something smarter...
6812
6813        // First we go through and resolve each of the specific items
6814        // that were supplied, taking care of removing any corresponding
6815        // duplicate items in the generic resolve list.
6816        if (specifics != null) {
6817            for (int i=0; i<specifics.length; i++) {
6818                final Intent sintent = specifics[i];
6819                if (sintent == null) {
6820                    continue;
6821                }
6822
6823                if (DEBUG_INTENT_MATCHING) {
6824                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6825                }
6826
6827                String action = sintent.getAction();
6828                if (resultsAction != null && resultsAction.equals(action)) {
6829                    // If this action was explicitly requested, then don't
6830                    // remove things that have it.
6831                    action = null;
6832                }
6833
6834                ResolveInfo ri = null;
6835                ActivityInfo ai = null;
6836
6837                ComponentName comp = sintent.getComponent();
6838                if (comp == null) {
6839                    ri = resolveIntent(
6840                        sintent,
6841                        specificTypes != null ? specificTypes[i] : null,
6842                            flags, userId);
6843                    if (ri == null) {
6844                        continue;
6845                    }
6846                    if (ri == mResolveInfo) {
6847                        // ACK!  Must do something better with this.
6848                    }
6849                    ai = ri.activityInfo;
6850                    comp = new ComponentName(ai.applicationInfo.packageName,
6851                            ai.name);
6852                } else {
6853                    ai = getActivityInfo(comp, flags, userId);
6854                    if (ai == null) {
6855                        continue;
6856                    }
6857                }
6858
6859                // Look for any generic query activities that are duplicates
6860                // of this specific one, and remove them from the results.
6861                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6862                N = results.size();
6863                int j;
6864                for (j=specificsPos; j<N; j++) {
6865                    ResolveInfo sri = results.get(j);
6866                    if ((sri.activityInfo.name.equals(comp.getClassName())
6867                            && sri.activityInfo.applicationInfo.packageName.equals(
6868                                    comp.getPackageName()))
6869                        || (action != null && sri.filter.matchAction(action))) {
6870                        results.remove(j);
6871                        if (DEBUG_INTENT_MATCHING) Log.v(
6872                            TAG, "Removing duplicate item from " + j
6873                            + " due to specific " + specificsPos);
6874                        if (ri == null) {
6875                            ri = sri;
6876                        }
6877                        j--;
6878                        N--;
6879                    }
6880                }
6881
6882                // Add this specific item to its proper place.
6883                if (ri == null) {
6884                    ri = new ResolveInfo();
6885                    ri.activityInfo = ai;
6886                }
6887                results.add(specificsPos, ri);
6888                ri.specificIndex = i;
6889                specificsPos++;
6890            }
6891        }
6892
6893        // Now we go through the remaining generic results and remove any
6894        // duplicate actions that are found here.
6895        N = results.size();
6896        for (int i=specificsPos; i<N-1; i++) {
6897            final ResolveInfo rii = results.get(i);
6898            if (rii.filter == null) {
6899                continue;
6900            }
6901
6902            // Iterate over all of the actions of this result's intent
6903            // filter...  typically this should be just one.
6904            final Iterator<String> it = rii.filter.actionsIterator();
6905            if (it == null) {
6906                continue;
6907            }
6908            while (it.hasNext()) {
6909                final String action = it.next();
6910                if (resultsAction != null && resultsAction.equals(action)) {
6911                    // If this action was explicitly requested, then don't
6912                    // remove things that have it.
6913                    continue;
6914                }
6915                for (int j=i+1; j<N; j++) {
6916                    final ResolveInfo rij = results.get(j);
6917                    if (rij.filter != null && rij.filter.hasAction(action)) {
6918                        results.remove(j);
6919                        if (DEBUG_INTENT_MATCHING) Log.v(
6920                            TAG, "Removing duplicate item from " + j
6921                            + " due to action " + action + " at " + i);
6922                        j--;
6923                        N--;
6924                    }
6925                }
6926            }
6927
6928            // If the caller didn't request filter information, drop it now
6929            // so we don't have to marshall/unmarshall it.
6930            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6931                rii.filter = null;
6932            }
6933        }
6934
6935        // Filter out the caller activity if so requested.
6936        if (caller != null) {
6937            N = results.size();
6938            for (int i=0; i<N; i++) {
6939                ActivityInfo ainfo = results.get(i).activityInfo;
6940                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6941                        && caller.getClassName().equals(ainfo.name)) {
6942                    results.remove(i);
6943                    break;
6944                }
6945            }
6946        }
6947
6948        // If the caller didn't request filter information,
6949        // drop them now so we don't have to
6950        // marshall/unmarshall it.
6951        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6952            N = results.size();
6953            for (int i=0; i<N; i++) {
6954                results.get(i).filter = null;
6955            }
6956        }
6957
6958        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6959        return results;
6960    }
6961
6962    @Override
6963    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6964            String resolvedType, int flags, int userId) {
6965        return new ParceledListSlice<>(
6966                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6967    }
6968
6969    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6970            String resolvedType, int flags, int userId) {
6971        if (!sUserManager.exists(userId)) return Collections.emptyList();
6972        flags = updateFlagsForResolve(flags, userId, intent, false);
6973        ComponentName comp = intent.getComponent();
6974        if (comp == null) {
6975            if (intent.getSelector() != null) {
6976                intent = intent.getSelector();
6977                comp = intent.getComponent();
6978            }
6979        }
6980        if (comp != null) {
6981            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6982            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6983            if (ai != null) {
6984                ResolveInfo ri = new ResolveInfo();
6985                ri.activityInfo = ai;
6986                list.add(ri);
6987            }
6988            return list;
6989        }
6990
6991        // reader
6992        synchronized (mPackages) {
6993            String pkgName = intent.getPackage();
6994            if (pkgName == null) {
6995                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6996            }
6997            final PackageParser.Package pkg = mPackages.get(pkgName);
6998            if (pkg != null) {
6999                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7000                        userId);
7001            }
7002            return Collections.emptyList();
7003        }
7004    }
7005
7006    @Override
7007    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7008        if (!sUserManager.exists(userId)) return null;
7009        flags = updateFlagsForResolve(flags, userId, intent, false);
7010        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
7011        if (query != null) {
7012            if (query.size() >= 1) {
7013                // If there is more than one service with the same priority,
7014                // just arbitrarily pick the first one.
7015                return query.get(0);
7016            }
7017        }
7018        return null;
7019    }
7020
7021    @Override
7022    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7023            String resolvedType, int flags, int userId) {
7024        return new ParceledListSlice<>(
7025                queryIntentServicesInternal(intent, resolvedType, flags, userId));
7026    }
7027
7028    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7029            String resolvedType, int flags, int userId) {
7030        if (!sUserManager.exists(userId)) return Collections.emptyList();
7031        flags = updateFlagsForResolve(flags, userId, intent, false);
7032        ComponentName comp = intent.getComponent();
7033        if (comp == null) {
7034            if (intent.getSelector() != null) {
7035                intent = intent.getSelector();
7036                comp = intent.getComponent();
7037            }
7038        }
7039        if (comp != null) {
7040            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7041            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7042            if (si != null) {
7043                final ResolveInfo ri = new ResolveInfo();
7044                ri.serviceInfo = si;
7045                list.add(ri);
7046            }
7047            return list;
7048        }
7049
7050        // reader
7051        synchronized (mPackages) {
7052            String pkgName = intent.getPackage();
7053            if (pkgName == null) {
7054                return mServices.queryIntent(intent, resolvedType, flags, userId);
7055            }
7056            final PackageParser.Package pkg = mPackages.get(pkgName);
7057            if (pkg != null) {
7058                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7059                        userId);
7060            }
7061            return Collections.emptyList();
7062        }
7063    }
7064
7065    @Override
7066    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7067            String resolvedType, int flags, int userId) {
7068        return new ParceledListSlice<>(
7069                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7070    }
7071
7072    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7073            Intent intent, String resolvedType, int flags, int userId) {
7074        if (!sUserManager.exists(userId)) return Collections.emptyList();
7075        flags = updateFlagsForResolve(flags, userId, intent, false);
7076        ComponentName comp = intent.getComponent();
7077        if (comp == null) {
7078            if (intent.getSelector() != null) {
7079                intent = intent.getSelector();
7080                comp = intent.getComponent();
7081            }
7082        }
7083        if (comp != null) {
7084            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7085            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7086            if (pi != null) {
7087                final ResolveInfo ri = new ResolveInfo();
7088                ri.providerInfo = pi;
7089                list.add(ri);
7090            }
7091            return list;
7092        }
7093
7094        // reader
7095        synchronized (mPackages) {
7096            String pkgName = intent.getPackage();
7097            if (pkgName == null) {
7098                return mProviders.queryIntent(intent, resolvedType, flags, userId);
7099            }
7100            final PackageParser.Package pkg = mPackages.get(pkgName);
7101            if (pkg != null) {
7102                return mProviders.queryIntentForPackage(
7103                        intent, resolvedType, flags, pkg.providers, userId);
7104            }
7105            return Collections.emptyList();
7106        }
7107    }
7108
7109    @Override
7110    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7111        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7112        flags = updateFlagsForPackage(flags, userId, null);
7113        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7114        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7115                true /* requireFullPermission */, false /* checkShell */,
7116                "get installed packages");
7117
7118        // writer
7119        synchronized (mPackages) {
7120            ArrayList<PackageInfo> list;
7121            if (listUninstalled) {
7122                list = new ArrayList<>(mSettings.mPackages.size());
7123                for (PackageSetting ps : mSettings.mPackages.values()) {
7124                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7125                        continue;
7126                    }
7127                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7128                    if (pi != null) {
7129                        list.add(pi);
7130                    }
7131                }
7132            } else {
7133                list = new ArrayList<>(mPackages.size());
7134                for (PackageParser.Package p : mPackages.values()) {
7135                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7136                            Binder.getCallingUid(), userId)) {
7137                        continue;
7138                    }
7139                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7140                            p.mExtras, flags, userId);
7141                    if (pi != null) {
7142                        list.add(pi);
7143                    }
7144                }
7145            }
7146
7147            return new ParceledListSlice<>(list);
7148        }
7149    }
7150
7151    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7152            String[] permissions, boolean[] tmp, int flags, int userId) {
7153        int numMatch = 0;
7154        final PermissionsState permissionsState = ps.getPermissionsState();
7155        for (int i=0; i<permissions.length; i++) {
7156            final String permission = permissions[i];
7157            if (permissionsState.hasPermission(permission, userId)) {
7158                tmp[i] = true;
7159                numMatch++;
7160            } else {
7161                tmp[i] = false;
7162            }
7163        }
7164        if (numMatch == 0) {
7165            return;
7166        }
7167        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7168
7169        // The above might return null in cases of uninstalled apps or install-state
7170        // skew across users/profiles.
7171        if (pi != null) {
7172            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7173                if (numMatch == permissions.length) {
7174                    pi.requestedPermissions = permissions;
7175                } else {
7176                    pi.requestedPermissions = new String[numMatch];
7177                    numMatch = 0;
7178                    for (int i=0; i<permissions.length; i++) {
7179                        if (tmp[i]) {
7180                            pi.requestedPermissions[numMatch] = permissions[i];
7181                            numMatch++;
7182                        }
7183                    }
7184                }
7185            }
7186            list.add(pi);
7187        }
7188    }
7189
7190    @Override
7191    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7192            String[] permissions, int flags, int userId) {
7193        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7194        flags = updateFlagsForPackage(flags, userId, permissions);
7195        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7196                true /* requireFullPermission */, false /* checkShell */,
7197                "get packages holding permissions");
7198        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7199
7200        // writer
7201        synchronized (mPackages) {
7202            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7203            boolean[] tmpBools = new boolean[permissions.length];
7204            if (listUninstalled) {
7205                for (PackageSetting ps : mSettings.mPackages.values()) {
7206                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7207                            userId);
7208                }
7209            } else {
7210                for (PackageParser.Package pkg : mPackages.values()) {
7211                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7212                    if (ps != null) {
7213                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7214                                userId);
7215                    }
7216                }
7217            }
7218
7219            return new ParceledListSlice<PackageInfo>(list);
7220        }
7221    }
7222
7223    @Override
7224    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7225        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7226        flags = updateFlagsForApplication(flags, userId, null);
7227        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7228
7229        // writer
7230        synchronized (mPackages) {
7231            ArrayList<ApplicationInfo> list;
7232            if (listUninstalled) {
7233                list = new ArrayList<>(mSettings.mPackages.size());
7234                for (PackageSetting ps : mSettings.mPackages.values()) {
7235                    ApplicationInfo ai;
7236                    int effectiveFlags = flags;
7237                    if (ps.isSystem()) {
7238                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7239                    }
7240                    if (ps.pkg != null) {
7241                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7242                            continue;
7243                        }
7244                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7245                                ps.readUserState(userId), userId);
7246                        if (ai != null) {
7247                            rebaseEnabledOverlays(ai, userId);
7248                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7249                        }
7250                    } else {
7251                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7252                        // and already converts to externally visible package name
7253                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7254                                Binder.getCallingUid(), effectiveFlags, userId);
7255                    }
7256                    if (ai != null) {
7257                        list.add(ai);
7258                    }
7259                }
7260            } else {
7261                list = new ArrayList<>(mPackages.size());
7262                for (PackageParser.Package p : mPackages.values()) {
7263                    if (p.mExtras != null) {
7264                        PackageSetting ps = (PackageSetting) p.mExtras;
7265                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7266                            continue;
7267                        }
7268                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7269                                ps.readUserState(userId), userId);
7270                        if (ai != null) {
7271                            rebaseEnabledOverlays(ai, userId);
7272                            ai.packageName = resolveExternalPackageNameLPr(p);
7273                            list.add(ai);
7274                        }
7275                    }
7276                }
7277            }
7278
7279            return new ParceledListSlice<>(list);
7280        }
7281    }
7282
7283    @Override
7284    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7285        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7286            return null;
7287        }
7288
7289        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7290                "getEphemeralApplications");
7291        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7292                true /* requireFullPermission */, false /* checkShell */,
7293                "getEphemeralApplications");
7294        synchronized (mPackages) {
7295            List<InstantAppInfo> instantApps = mInstantAppRegistry
7296                    .getInstantAppsLPr(userId);
7297            if (instantApps != null) {
7298                return new ParceledListSlice<>(instantApps);
7299            }
7300        }
7301        return null;
7302    }
7303
7304    @Override
7305    public boolean isInstantApp(String packageName, int userId) {
7306        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7307                true /* requireFullPermission */, false /* checkShell */,
7308                "isInstantApp");
7309        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7310            return false;
7311        }
7312
7313        if (!isCallerSameApp(packageName)) {
7314            return false;
7315        }
7316        synchronized (mPackages) {
7317            final PackageSetting ps = mSettings.mPackages.get(packageName);
7318            if (ps != null) {
7319                return ps.getInstantApp(userId);
7320            }
7321        }
7322        return false;
7323    }
7324
7325    @Override
7326    public byte[] getInstantAppCookie(String packageName, int userId) {
7327        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7328            return null;
7329        }
7330
7331        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7332                true /* requireFullPermission */, false /* checkShell */,
7333                "getInstantAppCookie");
7334        if (!isCallerSameApp(packageName)) {
7335            return null;
7336        }
7337        synchronized (mPackages) {
7338            return mInstantAppRegistry.getInstantAppCookieLPw(
7339                    packageName, userId);
7340        }
7341    }
7342
7343    @Override
7344    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7345        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7346            return true;
7347        }
7348
7349        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7350                true /* requireFullPermission */, true /* checkShell */,
7351                "setInstantAppCookie");
7352        if (!isCallerSameApp(packageName)) {
7353            return false;
7354        }
7355        synchronized (mPackages) {
7356            return mInstantAppRegistry.setInstantAppCookieLPw(
7357                    packageName, cookie, userId);
7358        }
7359    }
7360
7361    @Override
7362    public Bitmap getInstantAppIcon(String packageName, int userId) {
7363        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7364            return null;
7365        }
7366
7367        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7368                "getInstantAppIcon");
7369
7370        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7371                true /* requireFullPermission */, false /* checkShell */,
7372                "getInstantAppIcon");
7373
7374        synchronized (mPackages) {
7375            return mInstantAppRegistry.getInstantAppIconLPw(
7376                    packageName, userId);
7377        }
7378    }
7379
7380    private boolean isCallerSameApp(String packageName) {
7381        PackageParser.Package pkg = mPackages.get(packageName);
7382        return pkg != null
7383                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7384    }
7385
7386    @Override
7387    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7388        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7389    }
7390
7391    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7392        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7393
7394        // reader
7395        synchronized (mPackages) {
7396            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7397            final int userId = UserHandle.getCallingUserId();
7398            while (i.hasNext()) {
7399                final PackageParser.Package p = i.next();
7400                if (p.applicationInfo == null) continue;
7401
7402                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7403                        && !p.applicationInfo.isDirectBootAware();
7404                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7405                        && p.applicationInfo.isDirectBootAware();
7406
7407                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7408                        && (!mSafeMode || isSystemApp(p))
7409                        && (matchesUnaware || matchesAware)) {
7410                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7411                    if (ps != null) {
7412                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7413                                ps.readUserState(userId), userId);
7414                        if (ai != null) {
7415                            rebaseEnabledOverlays(ai, userId);
7416                            finalList.add(ai);
7417                        }
7418                    }
7419                }
7420            }
7421        }
7422
7423        return finalList;
7424    }
7425
7426    @Override
7427    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7428        if (!sUserManager.exists(userId)) return null;
7429        flags = updateFlagsForComponent(flags, userId, name);
7430        // reader
7431        synchronized (mPackages) {
7432            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7433            PackageSetting ps = provider != null
7434                    ? mSettings.mPackages.get(provider.owner.packageName)
7435                    : null;
7436            return ps != null
7437                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7438                    ? PackageParser.generateProviderInfo(provider, flags,
7439                            ps.readUserState(userId), userId)
7440                    : null;
7441        }
7442    }
7443
7444    /**
7445     * @deprecated
7446     */
7447    @Deprecated
7448    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7449        // reader
7450        synchronized (mPackages) {
7451            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7452                    .entrySet().iterator();
7453            final int userId = UserHandle.getCallingUserId();
7454            while (i.hasNext()) {
7455                Map.Entry<String, PackageParser.Provider> entry = i.next();
7456                PackageParser.Provider p = entry.getValue();
7457                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7458
7459                if (ps != null && p.syncable
7460                        && (!mSafeMode || (p.info.applicationInfo.flags
7461                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7462                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7463                            ps.readUserState(userId), userId);
7464                    if (info != null) {
7465                        outNames.add(entry.getKey());
7466                        outInfo.add(info);
7467                    }
7468                }
7469            }
7470        }
7471    }
7472
7473    @Override
7474    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7475            int uid, int flags, String metaDataKey) {
7476        final int userId = processName != null ? UserHandle.getUserId(uid)
7477                : UserHandle.getCallingUserId();
7478        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7479        flags = updateFlagsForComponent(flags, userId, processName);
7480
7481        ArrayList<ProviderInfo> finalList = null;
7482        // reader
7483        synchronized (mPackages) {
7484            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7485            while (i.hasNext()) {
7486                final PackageParser.Provider p = i.next();
7487                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7488                if (ps != null && p.info.authority != null
7489                        && (processName == null
7490                                || (p.info.processName.equals(processName)
7491                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7492                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7493
7494                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7495                    // parameter.
7496                    if (metaDataKey != null
7497                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7498                        continue;
7499                    }
7500
7501                    if (finalList == null) {
7502                        finalList = new ArrayList<ProviderInfo>(3);
7503                    }
7504                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7505                            ps.readUserState(userId), userId);
7506                    if (info != null) {
7507                        finalList.add(info);
7508                    }
7509                }
7510            }
7511        }
7512
7513        if (finalList != null) {
7514            Collections.sort(finalList, mProviderInitOrderSorter);
7515            return new ParceledListSlice<ProviderInfo>(finalList);
7516        }
7517
7518        return ParceledListSlice.emptyList();
7519    }
7520
7521    @Override
7522    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7523        // reader
7524        synchronized (mPackages) {
7525            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7526            return PackageParser.generateInstrumentationInfo(i, flags);
7527        }
7528    }
7529
7530    @Override
7531    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7532            String targetPackage, int flags) {
7533        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7534    }
7535
7536    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7537            int flags) {
7538        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7539
7540        // reader
7541        synchronized (mPackages) {
7542            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7543            while (i.hasNext()) {
7544                final PackageParser.Instrumentation p = i.next();
7545                if (targetPackage == null
7546                        || targetPackage.equals(p.info.targetPackage)) {
7547                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7548                            flags);
7549                    if (ii != null) {
7550                        finalList.add(ii);
7551                    }
7552                }
7553            }
7554        }
7555
7556        return finalList;
7557    }
7558
7559    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7560        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7561        try {
7562            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7563        } finally {
7564            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7565        }
7566    }
7567
7568    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7569        final File[] files = dir.listFiles();
7570        if (ArrayUtils.isEmpty(files)) {
7571            Log.d(TAG, "No files in app dir " + dir);
7572            return;
7573        }
7574
7575        if (DEBUG_PACKAGE_SCANNING) {
7576            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7577                    + " flags=0x" + Integer.toHexString(parseFlags));
7578        }
7579        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7580                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7581
7582        // Submit files for parsing in parallel
7583        int fileCount = 0;
7584        for (File file : files) {
7585            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7586                    && !PackageInstallerService.isStageName(file.getName());
7587            if (!isPackage) {
7588                // Ignore entries which are not packages
7589                continue;
7590            }
7591            parallelPackageParser.submit(file, parseFlags);
7592            fileCount++;
7593        }
7594
7595        // Process results one by one
7596        for (; fileCount > 0; fileCount--) {
7597            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7598            Throwable throwable = parseResult.throwable;
7599            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7600
7601            if (throwable == null) {
7602                // Static shared libraries have synthetic package names
7603                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7604                    renameStaticSharedLibraryPackage(parseResult.pkg);
7605                }
7606                try {
7607                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7608                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7609                                currentTime, null);
7610                    }
7611                } catch (PackageManagerException e) {
7612                    errorCode = e.error;
7613                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7614                }
7615            } else if (throwable instanceof PackageParser.PackageParserException) {
7616                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7617                        throwable;
7618                errorCode = e.error;
7619                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7620            } else {
7621                throw new IllegalStateException("Unexpected exception occurred while parsing "
7622                        + parseResult.scanFile, throwable);
7623            }
7624
7625            // Delete invalid userdata apps
7626            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7627                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7628                logCriticalInfo(Log.WARN,
7629                        "Deleting invalid package at " + parseResult.scanFile);
7630                removeCodePathLI(parseResult.scanFile);
7631            }
7632        }
7633        parallelPackageParser.close();
7634    }
7635
7636    private static File getSettingsProblemFile() {
7637        File dataDir = Environment.getDataDirectory();
7638        File systemDir = new File(dataDir, "system");
7639        File fname = new File(systemDir, "uiderrors.txt");
7640        return fname;
7641    }
7642
7643    static void reportSettingsProblem(int priority, String msg) {
7644        logCriticalInfo(priority, msg);
7645    }
7646
7647    static void logCriticalInfo(int priority, String msg) {
7648        Slog.println(priority, TAG, msg);
7649        EventLogTags.writePmCriticalInfo(msg);
7650        try {
7651            File fname = getSettingsProblemFile();
7652            FileOutputStream out = new FileOutputStream(fname, true);
7653            PrintWriter pw = new FastPrintWriter(out);
7654            SimpleDateFormat formatter = new SimpleDateFormat();
7655            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7656            pw.println(dateString + ": " + msg);
7657            pw.close();
7658            FileUtils.setPermissions(
7659                    fname.toString(),
7660                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7661                    -1, -1);
7662        } catch (java.io.IOException e) {
7663        }
7664    }
7665
7666    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7667        if (srcFile.isDirectory()) {
7668            final File baseFile = new File(pkg.baseCodePath);
7669            long maxModifiedTime = baseFile.lastModified();
7670            if (pkg.splitCodePaths != null) {
7671                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7672                    final File splitFile = new File(pkg.splitCodePaths[i]);
7673                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7674                }
7675            }
7676            return maxModifiedTime;
7677        }
7678        return srcFile.lastModified();
7679    }
7680
7681    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7682            final int policyFlags) throws PackageManagerException {
7683        // When upgrading from pre-N MR1, verify the package time stamp using the package
7684        // directory and not the APK file.
7685        final long lastModifiedTime = mIsPreNMR1Upgrade
7686                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7687        if (ps != null
7688                && ps.codePath.equals(srcFile)
7689                && ps.timeStamp == lastModifiedTime
7690                && !isCompatSignatureUpdateNeeded(pkg)
7691                && !isRecoverSignatureUpdateNeeded(pkg)) {
7692            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7693            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7694            ArraySet<PublicKey> signingKs;
7695            synchronized (mPackages) {
7696                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7697            }
7698            if (ps.signatures.mSignatures != null
7699                    && ps.signatures.mSignatures.length != 0
7700                    && signingKs != null) {
7701                // Optimization: reuse the existing cached certificates
7702                // if the package appears to be unchanged.
7703                pkg.mSignatures = ps.signatures.mSignatures;
7704                pkg.mSigningKeys = signingKs;
7705                return;
7706            }
7707
7708            Slog.w(TAG, "PackageSetting for " + ps.name
7709                    + " is missing signatures.  Collecting certs again to recover them.");
7710        } else {
7711            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7712        }
7713
7714        try {
7715            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7716            PackageParser.collectCertificates(pkg, policyFlags);
7717        } catch (PackageParserException e) {
7718            throw PackageManagerException.from(e);
7719        } finally {
7720            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7721        }
7722    }
7723
7724    /**
7725     *  Traces a package scan.
7726     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7727     */
7728    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7729            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7730        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7731        try {
7732            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7733        } finally {
7734            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7735        }
7736    }
7737
7738    /**
7739     *  Scans a package and returns the newly parsed package.
7740     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7741     */
7742    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7743            long currentTime, UserHandle user) throws PackageManagerException {
7744        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7745        PackageParser pp = new PackageParser();
7746        pp.setSeparateProcesses(mSeparateProcesses);
7747        pp.setOnlyCoreApps(mOnlyCore);
7748        pp.setDisplayMetrics(mMetrics);
7749
7750        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7751            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7752        }
7753
7754        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7755        final PackageParser.Package pkg;
7756        try {
7757            pkg = pp.parsePackage(scanFile, parseFlags);
7758        } catch (PackageParserException e) {
7759            throw PackageManagerException.from(e);
7760        } finally {
7761            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7762        }
7763
7764        // Static shared libraries have synthetic package names
7765        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7766            renameStaticSharedLibraryPackage(pkg);
7767        }
7768
7769        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7770    }
7771
7772    /**
7773     *  Scans a package and returns the newly parsed package.
7774     *  @throws PackageManagerException on a parse error.
7775     */
7776    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7777            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7778            throws PackageManagerException {
7779        // If the package has children and this is the first dive in the function
7780        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7781        // packages (parent and children) would be successfully scanned before the
7782        // actual scan since scanning mutates internal state and we want to atomically
7783        // install the package and its children.
7784        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7785            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7786                scanFlags |= SCAN_CHECK_ONLY;
7787            }
7788        } else {
7789            scanFlags &= ~SCAN_CHECK_ONLY;
7790        }
7791
7792        // Scan the parent
7793        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7794                scanFlags, currentTime, user);
7795
7796        // Scan the children
7797        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7798        for (int i = 0; i < childCount; i++) {
7799            PackageParser.Package childPackage = pkg.childPackages.get(i);
7800            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7801                    currentTime, user);
7802        }
7803
7804
7805        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7806            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7807        }
7808
7809        return scannedPkg;
7810    }
7811
7812    /**
7813     *  Scans a package and returns the newly parsed package.
7814     *  @throws PackageManagerException on a parse error.
7815     */
7816    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7817            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7818            throws PackageManagerException {
7819        PackageSetting ps = null;
7820        PackageSetting updatedPkg;
7821        // reader
7822        synchronized (mPackages) {
7823            // Look to see if we already know about this package.
7824            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7825            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7826                // This package has been renamed to its original name.  Let's
7827                // use that.
7828                ps = mSettings.getPackageLPr(oldName);
7829            }
7830            // If there was no original package, see one for the real package name.
7831            if (ps == null) {
7832                ps = mSettings.getPackageLPr(pkg.packageName);
7833            }
7834            // Check to see if this package could be hiding/updating a system
7835            // package.  Must look for it either under the original or real
7836            // package name depending on our state.
7837            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7838            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7839
7840            // If this is a package we don't know about on the system partition, we
7841            // may need to remove disabled child packages on the system partition
7842            // or may need to not add child packages if the parent apk is updated
7843            // on the data partition and no longer defines this child package.
7844            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7845                // If this is a parent package for an updated system app and this system
7846                // app got an OTA update which no longer defines some of the child packages
7847                // we have to prune them from the disabled system packages.
7848                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7849                if (disabledPs != null) {
7850                    final int scannedChildCount = (pkg.childPackages != null)
7851                            ? pkg.childPackages.size() : 0;
7852                    final int disabledChildCount = disabledPs.childPackageNames != null
7853                            ? disabledPs.childPackageNames.size() : 0;
7854                    for (int i = 0; i < disabledChildCount; i++) {
7855                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7856                        boolean disabledPackageAvailable = false;
7857                        for (int j = 0; j < scannedChildCount; j++) {
7858                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7859                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7860                                disabledPackageAvailable = true;
7861                                break;
7862                            }
7863                         }
7864                         if (!disabledPackageAvailable) {
7865                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7866                         }
7867                    }
7868                }
7869            }
7870        }
7871
7872        boolean updatedPkgBetter = false;
7873        // First check if this is a system package that may involve an update
7874        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7875            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7876            // it needs to drop FLAG_PRIVILEGED.
7877            if (locationIsPrivileged(scanFile)) {
7878                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7879            } else {
7880                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7881            }
7882
7883            if (ps != null && !ps.codePath.equals(scanFile)) {
7884                // The path has changed from what was last scanned...  check the
7885                // version of the new path against what we have stored to determine
7886                // what to do.
7887                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7888                if (pkg.mVersionCode <= ps.versionCode) {
7889                    // The system package has been updated and the code path does not match
7890                    // Ignore entry. Skip it.
7891                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7892                            + " ignored: updated version " + ps.versionCode
7893                            + " better than this " + pkg.mVersionCode);
7894                    if (!updatedPkg.codePath.equals(scanFile)) {
7895                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7896                                + ps.name + " changing from " + updatedPkg.codePathString
7897                                + " to " + scanFile);
7898                        updatedPkg.codePath = scanFile;
7899                        updatedPkg.codePathString = scanFile.toString();
7900                        updatedPkg.resourcePath = scanFile;
7901                        updatedPkg.resourcePathString = scanFile.toString();
7902                    }
7903                    updatedPkg.pkg = pkg;
7904                    updatedPkg.versionCode = pkg.mVersionCode;
7905
7906                    // Update the disabled system child packages to point to the package too.
7907                    final int childCount = updatedPkg.childPackageNames != null
7908                            ? updatedPkg.childPackageNames.size() : 0;
7909                    for (int i = 0; i < childCount; i++) {
7910                        String childPackageName = updatedPkg.childPackageNames.get(i);
7911                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7912                                childPackageName);
7913                        if (updatedChildPkg != null) {
7914                            updatedChildPkg.pkg = pkg;
7915                            updatedChildPkg.versionCode = pkg.mVersionCode;
7916                        }
7917                    }
7918
7919                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7920                            + scanFile + " ignored: updated version " + ps.versionCode
7921                            + " better than this " + pkg.mVersionCode);
7922                } else {
7923                    // The current app on the system partition is better than
7924                    // what we have updated to on the data partition; switch
7925                    // back to the system partition version.
7926                    // At this point, its safely assumed that package installation for
7927                    // apps in system partition will go through. If not there won't be a working
7928                    // version of the app
7929                    // writer
7930                    synchronized (mPackages) {
7931                        // Just remove the loaded entries from package lists.
7932                        mPackages.remove(ps.name);
7933                    }
7934
7935                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7936                            + " reverting from " + ps.codePathString
7937                            + ": new version " + pkg.mVersionCode
7938                            + " better than installed " + ps.versionCode);
7939
7940                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7941                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7942                    synchronized (mInstallLock) {
7943                        args.cleanUpResourcesLI();
7944                    }
7945                    synchronized (mPackages) {
7946                        mSettings.enableSystemPackageLPw(ps.name);
7947                    }
7948                    updatedPkgBetter = true;
7949                }
7950            }
7951        }
7952
7953        if (updatedPkg != null) {
7954            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7955            // initially
7956            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7957
7958            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7959            // flag set initially
7960            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7961                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7962            }
7963        }
7964
7965        // Verify certificates against what was last scanned
7966        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7967
7968        /*
7969         * A new system app appeared, but we already had a non-system one of the
7970         * same name installed earlier.
7971         */
7972        boolean shouldHideSystemApp = false;
7973        if (updatedPkg == null && ps != null
7974                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7975            /*
7976             * Check to make sure the signatures match first. If they don't,
7977             * wipe the installed application and its data.
7978             */
7979            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7980                    != PackageManager.SIGNATURE_MATCH) {
7981                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7982                        + " signatures don't match existing userdata copy; removing");
7983                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7984                        "scanPackageInternalLI")) {
7985                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7986                }
7987                ps = null;
7988            } else {
7989                /*
7990                 * If the newly-added system app is an older version than the
7991                 * already installed version, hide it. It will be scanned later
7992                 * and re-added like an update.
7993                 */
7994                if (pkg.mVersionCode <= ps.versionCode) {
7995                    shouldHideSystemApp = true;
7996                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7997                            + " but new version " + pkg.mVersionCode + " better than installed "
7998                            + ps.versionCode + "; hiding system");
7999                } else {
8000                    /*
8001                     * The newly found system app is a newer version that the
8002                     * one previously installed. Simply remove the
8003                     * already-installed application and replace it with our own
8004                     * while keeping the application data.
8005                     */
8006                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8007                            + " reverting from " + ps.codePathString + ": new version "
8008                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8009                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8010                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8011                    synchronized (mInstallLock) {
8012                        args.cleanUpResourcesLI();
8013                    }
8014                }
8015            }
8016        }
8017
8018        // The apk is forward locked (not public) if its code and resources
8019        // are kept in different files. (except for app in either system or
8020        // vendor path).
8021        // TODO grab this value from PackageSettings
8022        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8023            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8024                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8025            }
8026        }
8027
8028        // TODO: extend to support forward-locked splits
8029        String resourcePath = null;
8030        String baseResourcePath = null;
8031        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8032            if (ps != null && ps.resourcePathString != null) {
8033                resourcePath = ps.resourcePathString;
8034                baseResourcePath = ps.resourcePathString;
8035            } else {
8036                // Should not happen at all. Just log an error.
8037                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8038            }
8039        } else {
8040            resourcePath = pkg.codePath;
8041            baseResourcePath = pkg.baseCodePath;
8042        }
8043
8044        // Set application objects path explicitly.
8045        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8046        pkg.setApplicationInfoCodePath(pkg.codePath);
8047        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8048        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8049        pkg.setApplicationInfoResourcePath(resourcePath);
8050        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8051        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8052
8053        final int userId = ((user == null) ? 0 : user.getIdentifier());
8054        if (ps != null && ps.getInstantApp(userId)) {
8055            scanFlags |= SCAN_AS_INSTANT_APP;
8056        }
8057
8058        // Note that we invoke the following method only if we are about to unpack an application
8059        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8060                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8061
8062        /*
8063         * If the system app should be overridden by a previously installed
8064         * data, hide the system app now and let the /data/app scan pick it up
8065         * again.
8066         */
8067        if (shouldHideSystemApp) {
8068            synchronized (mPackages) {
8069                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8070            }
8071        }
8072
8073        return scannedPkg;
8074    }
8075
8076    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8077        // Derive the new package synthetic package name
8078        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8079                + pkg.staticSharedLibVersion);
8080    }
8081
8082    private static String fixProcessName(String defProcessName,
8083            String processName) {
8084        if (processName == null) {
8085            return defProcessName;
8086        }
8087        return processName;
8088    }
8089
8090    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8091            throws PackageManagerException {
8092        if (pkgSetting.signatures.mSignatures != null) {
8093            // Already existing package. Make sure signatures match
8094            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8095                    == PackageManager.SIGNATURE_MATCH;
8096            if (!match) {
8097                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8098                        == PackageManager.SIGNATURE_MATCH;
8099            }
8100            if (!match) {
8101                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8102                        == PackageManager.SIGNATURE_MATCH;
8103            }
8104            if (!match) {
8105                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8106                        + pkg.packageName + " signatures do not match the "
8107                        + "previously installed version; ignoring!");
8108            }
8109        }
8110
8111        // Check for shared user signatures
8112        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8113            // Already existing package. Make sure signatures match
8114            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8115                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8116            if (!match) {
8117                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8118                        == PackageManager.SIGNATURE_MATCH;
8119            }
8120            if (!match) {
8121                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8122                        == PackageManager.SIGNATURE_MATCH;
8123            }
8124            if (!match) {
8125                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8126                        "Package " + pkg.packageName
8127                        + " has no signatures that match those in shared user "
8128                        + pkgSetting.sharedUser.name + "; ignoring!");
8129            }
8130        }
8131    }
8132
8133    /**
8134     * Enforces that only the system UID or root's UID can call a method exposed
8135     * via Binder.
8136     *
8137     * @param message used as message if SecurityException is thrown
8138     * @throws SecurityException if the caller is not system or root
8139     */
8140    private static final void enforceSystemOrRoot(String message) {
8141        final int uid = Binder.getCallingUid();
8142        if (uid != Process.SYSTEM_UID && uid != 0) {
8143            throw new SecurityException(message);
8144        }
8145    }
8146
8147    @Override
8148    public void performFstrimIfNeeded() {
8149        enforceSystemOrRoot("Only the system can request fstrim");
8150
8151        // Before everything else, see whether we need to fstrim.
8152        try {
8153            IStorageManager sm = PackageHelper.getStorageManager();
8154            if (sm != null) {
8155                boolean doTrim = false;
8156                final long interval = android.provider.Settings.Global.getLong(
8157                        mContext.getContentResolver(),
8158                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8159                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8160                if (interval > 0) {
8161                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8162                    if (timeSinceLast > interval) {
8163                        doTrim = true;
8164                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8165                                + "; running immediately");
8166                    }
8167                }
8168                if (doTrim) {
8169                    final boolean dexOptDialogShown;
8170                    synchronized (mPackages) {
8171                        dexOptDialogShown = mDexOptDialogShown;
8172                    }
8173                    if (!isFirstBoot() && dexOptDialogShown) {
8174                        try {
8175                            ActivityManager.getService().showBootMessage(
8176                                    mContext.getResources().getString(
8177                                            R.string.android_upgrading_fstrim), true);
8178                        } catch (RemoteException e) {
8179                        }
8180                    }
8181                    sm.runMaintenance();
8182                }
8183            } else {
8184                Slog.e(TAG, "storageManager service unavailable!");
8185            }
8186        } catch (RemoteException e) {
8187            // Can't happen; StorageManagerService is local
8188        }
8189    }
8190
8191    @Override
8192    public void updatePackagesIfNeeded() {
8193        enforceSystemOrRoot("Only the system can request package update");
8194
8195        // We need to re-extract after an OTA.
8196        boolean causeUpgrade = isUpgrade();
8197
8198        // First boot or factory reset.
8199        // Note: we also handle devices that are upgrading to N right now as if it is their
8200        //       first boot, as they do not have profile data.
8201        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8202
8203        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8204        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8205
8206        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8207            return;
8208        }
8209
8210        List<PackageParser.Package> pkgs;
8211        synchronized (mPackages) {
8212            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8213        }
8214
8215        final long startTime = System.nanoTime();
8216        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8217                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8218
8219        final int elapsedTimeSeconds =
8220                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8221
8222        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8223        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8224        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8225        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8226        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8227    }
8228
8229    /**
8230     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8231     * containing statistics about the invocation. The array consists of three elements,
8232     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8233     * and {@code numberOfPackagesFailed}.
8234     */
8235    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8236            String compilerFilter) {
8237
8238        int numberOfPackagesVisited = 0;
8239        int numberOfPackagesOptimized = 0;
8240        int numberOfPackagesSkipped = 0;
8241        int numberOfPackagesFailed = 0;
8242        final int numberOfPackagesToDexopt = pkgs.size();
8243
8244        for (PackageParser.Package pkg : pkgs) {
8245            numberOfPackagesVisited++;
8246
8247            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8248                if (DEBUG_DEXOPT) {
8249                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8250                }
8251                numberOfPackagesSkipped++;
8252                continue;
8253            }
8254
8255            if (DEBUG_DEXOPT) {
8256                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8257                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8258            }
8259
8260            if (showDialog) {
8261                try {
8262                    ActivityManager.getService().showBootMessage(
8263                            mContext.getResources().getString(R.string.android_upgrading_apk,
8264                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8265                } catch (RemoteException e) {
8266                }
8267                synchronized (mPackages) {
8268                    mDexOptDialogShown = true;
8269                }
8270            }
8271
8272            // If the OTA updates a system app which was previously preopted to a non-preopted state
8273            // the app might end up being verified at runtime. That's because by default the apps
8274            // are verify-profile but for preopted apps there's no profile.
8275            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8276            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8277            // filter (by default interpret-only).
8278            // Note that at this stage unused apps are already filtered.
8279            if (isSystemApp(pkg) &&
8280                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8281                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8282                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8283            }
8284
8285            // checkProfiles is false to avoid merging profiles during boot which
8286            // might interfere with background compilation (b/28612421).
8287            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8288            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8289            // trade-off worth doing to save boot time work.
8290            int dexOptStatus = performDexOptTraced(pkg.packageName,
8291                    false /* checkProfiles */,
8292                    compilerFilter,
8293                    false /* force */);
8294            switch (dexOptStatus) {
8295                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8296                    numberOfPackagesOptimized++;
8297                    break;
8298                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8299                    numberOfPackagesSkipped++;
8300                    break;
8301                case PackageDexOptimizer.DEX_OPT_FAILED:
8302                    numberOfPackagesFailed++;
8303                    break;
8304                default:
8305                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8306                    break;
8307            }
8308        }
8309
8310        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8311                numberOfPackagesFailed };
8312    }
8313
8314    @Override
8315    public void notifyPackageUse(String packageName, int reason) {
8316        synchronized (mPackages) {
8317            PackageParser.Package p = mPackages.get(packageName);
8318            if (p == null) {
8319                return;
8320            }
8321            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8322        }
8323    }
8324
8325    @Override
8326    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8327        int userId = UserHandle.getCallingUserId();
8328        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8329        if (ai == null) {
8330            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8331                + loadingPackageName + ", user=" + userId);
8332            return;
8333        }
8334        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8335    }
8336
8337    // TODO: this is not used nor needed. Delete it.
8338    @Override
8339    public boolean performDexOptIfNeeded(String packageName) {
8340        int dexOptStatus = performDexOptTraced(packageName,
8341                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8342        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8343    }
8344
8345    @Override
8346    public boolean performDexOpt(String packageName,
8347            boolean checkProfiles, int compileReason, boolean force) {
8348        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8349                getCompilerFilterForReason(compileReason), force);
8350        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8351    }
8352
8353    @Override
8354    public boolean performDexOptMode(String packageName,
8355            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8356        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8357                targetCompilerFilter, force);
8358        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8359    }
8360
8361    private int performDexOptTraced(String packageName,
8362                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8363        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8364        try {
8365            return performDexOptInternal(packageName, checkProfiles,
8366                    targetCompilerFilter, force);
8367        } finally {
8368            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8369        }
8370    }
8371
8372    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8373    // if the package can now be considered up to date for the given filter.
8374    private int performDexOptInternal(String packageName,
8375                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8376        PackageParser.Package p;
8377        synchronized (mPackages) {
8378            p = mPackages.get(packageName);
8379            if (p == null) {
8380                // Package could not be found. Report failure.
8381                return PackageDexOptimizer.DEX_OPT_FAILED;
8382            }
8383            mPackageUsage.maybeWriteAsync(mPackages);
8384            mCompilerStats.maybeWriteAsync();
8385        }
8386        long callingId = Binder.clearCallingIdentity();
8387        try {
8388            synchronized (mInstallLock) {
8389                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8390                        targetCompilerFilter, force);
8391            }
8392        } finally {
8393            Binder.restoreCallingIdentity(callingId);
8394        }
8395    }
8396
8397    public ArraySet<String> getOptimizablePackages() {
8398        ArraySet<String> pkgs = new ArraySet<String>();
8399        synchronized (mPackages) {
8400            for (PackageParser.Package p : mPackages.values()) {
8401                if (PackageDexOptimizer.canOptimizePackage(p)) {
8402                    pkgs.add(p.packageName);
8403                }
8404            }
8405        }
8406        return pkgs;
8407    }
8408
8409    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8410            boolean checkProfiles, String targetCompilerFilter,
8411            boolean force) {
8412        // Select the dex optimizer based on the force parameter.
8413        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8414        //       allocate an object here.
8415        PackageDexOptimizer pdo = force
8416                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8417                : mPackageDexOptimizer;
8418
8419        // Optimize all dependencies first. Note: we ignore the return value and march on
8420        // on errors.
8421        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8422        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8423        if (!deps.isEmpty()) {
8424            for (PackageParser.Package depPackage : deps) {
8425                // TODO: Analyze and investigate if we (should) profile libraries.
8426                // Currently this will do a full compilation of the library by default.
8427                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8428                        false /* checkProfiles */,
8429                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8430                        getOrCreateCompilerPackageStats(depPackage));
8431            }
8432        }
8433        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8434                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
8435    }
8436
8437    // Performs dexopt on the used secondary dex files belonging to the given package.
8438    // Returns true if all dex files were process successfully (which could mean either dexopt or
8439    // skip). Returns false if any of the files caused errors.
8440    @Override
8441    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8442            boolean force) {
8443        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8444    }
8445
8446    /**
8447     * Reconcile the information we have about the secondary dex files belonging to
8448     * {@code packagName} and the actual dex files. For all dex files that were
8449     * deleted, update the internal records and delete the generated oat files.
8450     */
8451    @Override
8452    public void reconcileSecondaryDexFiles(String packageName) {
8453        mDexManager.reconcileSecondaryDexFiles(packageName);
8454    }
8455
8456    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8457    // a reference there.
8458    /*package*/ DexManager getDexManager() {
8459        return mDexManager;
8460    }
8461
8462    /**
8463     * Execute the background dexopt job immediately.
8464     */
8465    @Override
8466    public boolean runBackgroundDexoptJob() {
8467        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8468    }
8469
8470    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8471        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8472                || p.usesStaticLibraries != null) {
8473            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8474            Set<String> collectedNames = new HashSet<>();
8475            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8476
8477            retValue.remove(p);
8478
8479            return retValue;
8480        } else {
8481            return Collections.emptyList();
8482        }
8483    }
8484
8485    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8486            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8487        if (!collectedNames.contains(p.packageName)) {
8488            collectedNames.add(p.packageName);
8489            collected.add(p);
8490
8491            if (p.usesLibraries != null) {
8492                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8493                        null, collected, collectedNames);
8494            }
8495            if (p.usesOptionalLibraries != null) {
8496                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8497                        null, collected, collectedNames);
8498            }
8499            if (p.usesStaticLibraries != null) {
8500                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8501                        p.usesStaticLibrariesVersions, collected, collectedNames);
8502            }
8503        }
8504    }
8505
8506    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8507            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8508        final int libNameCount = libs.size();
8509        for (int i = 0; i < libNameCount; i++) {
8510            String libName = libs.get(i);
8511            int version = (versions != null && versions.length == libNameCount)
8512                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8513            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8514            if (libPkg != null) {
8515                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8516            }
8517        }
8518    }
8519
8520    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8521        synchronized (mPackages) {
8522            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8523            if (libEntry != null) {
8524                return mPackages.get(libEntry.apk);
8525            }
8526            return null;
8527        }
8528    }
8529
8530    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8531        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8532        if (versionedLib == null) {
8533            return null;
8534        }
8535        return versionedLib.get(version);
8536    }
8537
8538    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8539        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8540                pkg.staticSharedLibName);
8541        if (versionedLib == null) {
8542            return null;
8543        }
8544        int previousLibVersion = -1;
8545        final int versionCount = versionedLib.size();
8546        for (int i = 0; i < versionCount; i++) {
8547            final int libVersion = versionedLib.keyAt(i);
8548            if (libVersion < pkg.staticSharedLibVersion) {
8549                previousLibVersion = Math.max(previousLibVersion, libVersion);
8550            }
8551        }
8552        if (previousLibVersion >= 0) {
8553            return versionedLib.get(previousLibVersion);
8554        }
8555        return null;
8556    }
8557
8558    public void shutdown() {
8559        mPackageUsage.writeNow(mPackages);
8560        mCompilerStats.writeNow();
8561    }
8562
8563    @Override
8564    public void dumpProfiles(String packageName) {
8565        PackageParser.Package pkg;
8566        synchronized (mPackages) {
8567            pkg = mPackages.get(packageName);
8568            if (pkg == null) {
8569                throw new IllegalArgumentException("Unknown package: " + packageName);
8570            }
8571        }
8572        /* Only the shell, root, or the app user should be able to dump profiles. */
8573        int callingUid = Binder.getCallingUid();
8574        if (callingUid != Process.SHELL_UID &&
8575            callingUid != Process.ROOT_UID &&
8576            callingUid != pkg.applicationInfo.uid) {
8577            throw new SecurityException("dumpProfiles");
8578        }
8579
8580        synchronized (mInstallLock) {
8581            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8582            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8583            try {
8584                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8585                String codePaths = TextUtils.join(";", allCodePaths);
8586                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8587            } catch (InstallerException e) {
8588                Slog.w(TAG, "Failed to dump profiles", e);
8589            }
8590            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8591        }
8592    }
8593
8594    @Override
8595    public void forceDexOpt(String packageName) {
8596        enforceSystemOrRoot("forceDexOpt");
8597
8598        PackageParser.Package pkg;
8599        synchronized (mPackages) {
8600            pkg = mPackages.get(packageName);
8601            if (pkg == null) {
8602                throw new IllegalArgumentException("Unknown package: " + packageName);
8603            }
8604        }
8605
8606        synchronized (mInstallLock) {
8607            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8608
8609            // Whoever is calling forceDexOpt wants a fully compiled package.
8610            // Don't use profiles since that may cause compilation to be skipped.
8611            final int res = performDexOptInternalWithDependenciesLI(pkg,
8612                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8613                    true /* force */);
8614
8615            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8616            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8617                throw new IllegalStateException("Failed to dexopt: " + res);
8618            }
8619        }
8620    }
8621
8622    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8623        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8624            Slog.w(TAG, "Unable to update from " + oldPkg.name
8625                    + " to " + newPkg.packageName
8626                    + ": old package not in system partition");
8627            return false;
8628        } else if (mPackages.get(oldPkg.name) != null) {
8629            Slog.w(TAG, "Unable to update from " + oldPkg.name
8630                    + " to " + newPkg.packageName
8631                    + ": old package still exists");
8632            return false;
8633        }
8634        return true;
8635    }
8636
8637    void removeCodePathLI(File codePath) {
8638        if (codePath.isDirectory()) {
8639            try {
8640                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8641            } catch (InstallerException e) {
8642                Slog.w(TAG, "Failed to remove code path", e);
8643            }
8644        } else {
8645            codePath.delete();
8646        }
8647    }
8648
8649    private int[] resolveUserIds(int userId) {
8650        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8651    }
8652
8653    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8654        if (pkg == null) {
8655            Slog.wtf(TAG, "Package was null!", new Throwable());
8656            return;
8657        }
8658        clearAppDataLeafLIF(pkg, userId, flags);
8659        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8660        for (int i = 0; i < childCount; i++) {
8661            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8662        }
8663    }
8664
8665    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8666        final PackageSetting ps;
8667        synchronized (mPackages) {
8668            ps = mSettings.mPackages.get(pkg.packageName);
8669        }
8670        for (int realUserId : resolveUserIds(userId)) {
8671            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8672            try {
8673                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8674                        ceDataInode);
8675            } catch (InstallerException e) {
8676                Slog.w(TAG, String.valueOf(e));
8677            }
8678        }
8679    }
8680
8681    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8682        if (pkg == null) {
8683            Slog.wtf(TAG, "Package was null!", new Throwable());
8684            return;
8685        }
8686        destroyAppDataLeafLIF(pkg, userId, flags);
8687        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8688        for (int i = 0; i < childCount; i++) {
8689            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8690        }
8691    }
8692
8693    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8694        final PackageSetting ps;
8695        synchronized (mPackages) {
8696            ps = mSettings.mPackages.get(pkg.packageName);
8697        }
8698        for (int realUserId : resolveUserIds(userId)) {
8699            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8700            try {
8701                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8702                        ceDataInode);
8703            } catch (InstallerException e) {
8704                Slog.w(TAG, String.valueOf(e));
8705            }
8706        }
8707    }
8708
8709    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8710        if (pkg == null) {
8711            Slog.wtf(TAG, "Package was null!", new Throwable());
8712            return;
8713        }
8714        destroyAppProfilesLeafLIF(pkg);
8715        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8716        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8717        for (int i = 0; i < childCount; i++) {
8718            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8719            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8720                    true /* removeBaseMarker */);
8721        }
8722    }
8723
8724    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8725            boolean removeBaseMarker) {
8726        if (pkg.isForwardLocked()) {
8727            return;
8728        }
8729
8730        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8731            try {
8732                path = PackageManagerServiceUtils.realpath(new File(path));
8733            } catch (IOException e) {
8734                // TODO: Should we return early here ?
8735                Slog.w(TAG, "Failed to get canonical path", e);
8736                continue;
8737            }
8738
8739            final String useMarker = path.replace('/', '@');
8740            for (int realUserId : resolveUserIds(userId)) {
8741                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8742                if (removeBaseMarker) {
8743                    File foreignUseMark = new File(profileDir, useMarker);
8744                    if (foreignUseMark.exists()) {
8745                        if (!foreignUseMark.delete()) {
8746                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8747                                    + pkg.packageName);
8748                        }
8749                    }
8750                }
8751
8752                File[] markers = profileDir.listFiles();
8753                if (markers != null) {
8754                    final String searchString = "@" + pkg.packageName + "@";
8755                    // We also delete all markers that contain the package name we're
8756                    // uninstalling. These are associated with secondary dex-files belonging
8757                    // to the package. Reconstructing the path of these dex files is messy
8758                    // in general.
8759                    for (File marker : markers) {
8760                        if (marker.getName().indexOf(searchString) > 0) {
8761                            if (!marker.delete()) {
8762                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8763                                    + pkg.packageName);
8764                            }
8765                        }
8766                    }
8767                }
8768            }
8769        }
8770    }
8771
8772    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8773        try {
8774            mInstaller.destroyAppProfiles(pkg.packageName);
8775        } catch (InstallerException e) {
8776            Slog.w(TAG, String.valueOf(e));
8777        }
8778    }
8779
8780    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8781        if (pkg == null) {
8782            Slog.wtf(TAG, "Package was null!", new Throwable());
8783            return;
8784        }
8785        clearAppProfilesLeafLIF(pkg);
8786        // We don't remove the base foreign use marker when clearing profiles because
8787        // we will rename it when the app is updated. Unlike the actual profile contents,
8788        // the foreign use marker is good across installs.
8789        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8790        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8791        for (int i = 0; i < childCount; i++) {
8792            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8793        }
8794    }
8795
8796    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8797        try {
8798            mInstaller.clearAppProfiles(pkg.packageName);
8799        } catch (InstallerException e) {
8800            Slog.w(TAG, String.valueOf(e));
8801        }
8802    }
8803
8804    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8805            long lastUpdateTime) {
8806        // Set parent install/update time
8807        PackageSetting ps = (PackageSetting) pkg.mExtras;
8808        if (ps != null) {
8809            ps.firstInstallTime = firstInstallTime;
8810            ps.lastUpdateTime = lastUpdateTime;
8811        }
8812        // Set children install/update time
8813        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8814        for (int i = 0; i < childCount; i++) {
8815            PackageParser.Package childPkg = pkg.childPackages.get(i);
8816            ps = (PackageSetting) childPkg.mExtras;
8817            if (ps != null) {
8818                ps.firstInstallTime = firstInstallTime;
8819                ps.lastUpdateTime = lastUpdateTime;
8820            }
8821        }
8822    }
8823
8824    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8825            PackageParser.Package changingLib) {
8826        if (file.path != null) {
8827            usesLibraryFiles.add(file.path);
8828            return;
8829        }
8830        PackageParser.Package p = mPackages.get(file.apk);
8831        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8832            // If we are doing this while in the middle of updating a library apk,
8833            // then we need to make sure to use that new apk for determining the
8834            // dependencies here.  (We haven't yet finished committing the new apk
8835            // to the package manager state.)
8836            if (p == null || p.packageName.equals(changingLib.packageName)) {
8837                p = changingLib;
8838            }
8839        }
8840        if (p != null) {
8841            usesLibraryFiles.addAll(p.getAllCodePaths());
8842        }
8843    }
8844
8845    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8846            PackageParser.Package changingLib) throws PackageManagerException {
8847        if (pkg == null) {
8848            return;
8849        }
8850        ArraySet<String> usesLibraryFiles = null;
8851        if (pkg.usesLibraries != null) {
8852            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8853                    null, null, pkg.packageName, changingLib, true, null);
8854        }
8855        if (pkg.usesStaticLibraries != null) {
8856            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8857                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8858                    pkg.packageName, changingLib, true, usesLibraryFiles);
8859        }
8860        if (pkg.usesOptionalLibraries != null) {
8861            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8862                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8863        }
8864        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8865            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8866        } else {
8867            pkg.usesLibraryFiles = null;
8868        }
8869    }
8870
8871    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8872            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8873            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8874            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8875            throws PackageManagerException {
8876        final int libCount = requestedLibraries.size();
8877        for (int i = 0; i < libCount; i++) {
8878            final String libName = requestedLibraries.get(i);
8879            final int libVersion = requiredVersions != null ? requiredVersions[i]
8880                    : SharedLibraryInfo.VERSION_UNDEFINED;
8881            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8882            if (libEntry == null) {
8883                if (required) {
8884                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8885                            "Package " + packageName + " requires unavailable shared library "
8886                                    + libName + "; failing!");
8887                } else {
8888                    Slog.w(TAG, "Package " + packageName
8889                            + " desires unavailable shared library "
8890                            + libName + "; ignoring!");
8891                }
8892            } else {
8893                if (requiredVersions != null && requiredCertDigests != null) {
8894                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8895                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8896                            "Package " + packageName + " requires unavailable static shared"
8897                                    + " library " + libName + " version "
8898                                    + libEntry.info.getVersion() + "; failing!");
8899                    }
8900
8901                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8902                    if (libPkg == null) {
8903                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8904                                "Package " + packageName + " requires unavailable static shared"
8905                                        + " library; failing!");
8906                    }
8907
8908                    String expectedCertDigest = requiredCertDigests[i];
8909                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8910                                libPkg.mSignatures[0]);
8911                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8912                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8913                                "Package " + packageName + " requires differently signed" +
8914                                        " static shared library; failing!");
8915                    }
8916                }
8917
8918                if (outUsedLibraries == null) {
8919                    outUsedLibraries = new ArraySet<>();
8920                }
8921                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8922            }
8923        }
8924        return outUsedLibraries;
8925    }
8926
8927    private static boolean hasString(List<String> list, List<String> which) {
8928        if (list == null) {
8929            return false;
8930        }
8931        for (int i=list.size()-1; i>=0; i--) {
8932            for (int j=which.size()-1; j>=0; j--) {
8933                if (which.get(j).equals(list.get(i))) {
8934                    return true;
8935                }
8936            }
8937        }
8938        return false;
8939    }
8940
8941    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8942            PackageParser.Package changingPkg) {
8943        ArrayList<PackageParser.Package> res = null;
8944        for (PackageParser.Package pkg : mPackages.values()) {
8945            if (changingPkg != null
8946                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8947                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8948                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8949                            changingPkg.staticSharedLibName)) {
8950                return null;
8951            }
8952            if (res == null) {
8953                res = new ArrayList<>();
8954            }
8955            res.add(pkg);
8956            try {
8957                updateSharedLibrariesLPr(pkg, changingPkg);
8958            } catch (PackageManagerException e) {
8959                // If a system app update or an app and a required lib missing we
8960                // delete the package and for updated system apps keep the data as
8961                // it is better for the user to reinstall than to be in an limbo
8962                // state. Also libs disappearing under an app should never happen
8963                // - just in case.
8964                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8965                    final int flags = pkg.isUpdatedSystemApp()
8966                            ? PackageManager.DELETE_KEEP_DATA : 0;
8967                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8968                            flags , null, true, null);
8969                }
8970                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8971            }
8972        }
8973        return res;
8974    }
8975
8976    /**
8977     * Derive the value of the {@code cpuAbiOverride} based on the provided
8978     * value and an optional stored value from the package settings.
8979     */
8980    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8981        String cpuAbiOverride = null;
8982
8983        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8984            cpuAbiOverride = null;
8985        } else if (abiOverride != null) {
8986            cpuAbiOverride = abiOverride;
8987        } else if (settings != null) {
8988            cpuAbiOverride = settings.cpuAbiOverrideString;
8989        }
8990
8991        return cpuAbiOverride;
8992    }
8993
8994    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8995            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8996                    throws PackageManagerException {
8997        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8998        // If the package has children and this is the first dive in the function
8999        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9000        // whether all packages (parent and children) would be successfully scanned
9001        // before the actual scan since scanning mutates internal state and we want
9002        // to atomically install the package and its children.
9003        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9004            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9005                scanFlags |= SCAN_CHECK_ONLY;
9006            }
9007        } else {
9008            scanFlags &= ~SCAN_CHECK_ONLY;
9009        }
9010
9011        final PackageParser.Package scannedPkg;
9012        try {
9013            // Scan the parent
9014            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9015            // Scan the children
9016            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9017            for (int i = 0; i < childCount; i++) {
9018                PackageParser.Package childPkg = pkg.childPackages.get(i);
9019                scanPackageLI(childPkg, policyFlags,
9020                        scanFlags, currentTime, user);
9021            }
9022        } finally {
9023            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9024        }
9025
9026        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9027            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9028        }
9029
9030        return scannedPkg;
9031    }
9032
9033    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9034            int scanFlags, long currentTime, @Nullable UserHandle user)
9035                    throws PackageManagerException {
9036        boolean success = false;
9037        try {
9038            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9039                    currentTime, user);
9040            success = true;
9041            return res;
9042        } finally {
9043            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9044                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9045                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9046                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9047                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9048            }
9049        }
9050    }
9051
9052    /**
9053     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9054     */
9055    private static boolean apkHasCode(String fileName) {
9056        StrictJarFile jarFile = null;
9057        try {
9058            jarFile = new StrictJarFile(fileName,
9059                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9060            return jarFile.findEntry("classes.dex") != null;
9061        } catch (IOException ignore) {
9062        } finally {
9063            try {
9064                if (jarFile != null) {
9065                    jarFile.close();
9066                }
9067            } catch (IOException ignore) {}
9068        }
9069        return false;
9070    }
9071
9072    /**
9073     * Enforces code policy for the package. This ensures that if an APK has
9074     * declared hasCode="true" in its manifest that the APK actually contains
9075     * code.
9076     *
9077     * @throws PackageManagerException If bytecode could not be found when it should exist
9078     */
9079    private static void assertCodePolicy(PackageParser.Package pkg)
9080            throws PackageManagerException {
9081        final boolean shouldHaveCode =
9082                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9083        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9084            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9085                    "Package " + pkg.baseCodePath + " code is missing");
9086        }
9087
9088        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9089            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9090                final boolean splitShouldHaveCode =
9091                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9092                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9093                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9094                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9095                }
9096            }
9097        }
9098    }
9099
9100    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9101            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9102                    throws PackageManagerException {
9103        if (DEBUG_PACKAGE_SCANNING) {
9104            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9105                Log.d(TAG, "Scanning package " + pkg.packageName);
9106        }
9107
9108        applyPolicy(pkg, policyFlags);
9109
9110        assertPackageIsValid(pkg, policyFlags, scanFlags);
9111
9112        // Initialize package source and resource directories
9113        final File scanFile = new File(pkg.codePath);
9114        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9115        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9116
9117        SharedUserSetting suid = null;
9118        PackageSetting pkgSetting = null;
9119
9120        // Getting the package setting may have a side-effect, so if we
9121        // are only checking if scan would succeed, stash a copy of the
9122        // old setting to restore at the end.
9123        PackageSetting nonMutatedPs = null;
9124
9125        // We keep references to the derived CPU Abis from settings in oder to reuse
9126        // them in the case where we're not upgrading or booting for the first time.
9127        String primaryCpuAbiFromSettings = null;
9128        String secondaryCpuAbiFromSettings = null;
9129
9130        // writer
9131        synchronized (mPackages) {
9132            if (pkg.mSharedUserId != null) {
9133                // SIDE EFFECTS; may potentially allocate a new shared user
9134                suid = mSettings.getSharedUserLPw(
9135                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9136                if (DEBUG_PACKAGE_SCANNING) {
9137                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9138                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9139                                + "): packages=" + suid.packages);
9140                }
9141            }
9142
9143            // Check if we are renaming from an original package name.
9144            PackageSetting origPackage = null;
9145            String realName = null;
9146            if (pkg.mOriginalPackages != null) {
9147                // This package may need to be renamed to a previously
9148                // installed name.  Let's check on that...
9149                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9150                if (pkg.mOriginalPackages.contains(renamed)) {
9151                    // This package had originally been installed as the
9152                    // original name, and we have already taken care of
9153                    // transitioning to the new one.  Just update the new
9154                    // one to continue using the old name.
9155                    realName = pkg.mRealPackage;
9156                    if (!pkg.packageName.equals(renamed)) {
9157                        // Callers into this function may have already taken
9158                        // care of renaming the package; only do it here if
9159                        // it is not already done.
9160                        pkg.setPackageName(renamed);
9161                    }
9162                } else {
9163                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9164                        if ((origPackage = mSettings.getPackageLPr(
9165                                pkg.mOriginalPackages.get(i))) != null) {
9166                            // We do have the package already installed under its
9167                            // original name...  should we use it?
9168                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9169                                // New package is not compatible with original.
9170                                origPackage = null;
9171                                continue;
9172                            } else if (origPackage.sharedUser != null) {
9173                                // Make sure uid is compatible between packages.
9174                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9175                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9176                                            + " to " + pkg.packageName + ": old uid "
9177                                            + origPackage.sharedUser.name
9178                                            + " differs from " + pkg.mSharedUserId);
9179                                    origPackage = null;
9180                                    continue;
9181                                }
9182                                // TODO: Add case when shared user id is added [b/28144775]
9183                            } else {
9184                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9185                                        + pkg.packageName + " to old name " + origPackage.name);
9186                            }
9187                            break;
9188                        }
9189                    }
9190                }
9191            }
9192
9193            if (mTransferedPackages.contains(pkg.packageName)) {
9194                Slog.w(TAG, "Package " + pkg.packageName
9195                        + " was transferred to another, but its .apk remains");
9196            }
9197
9198            // See comments in nonMutatedPs declaration
9199            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9200                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9201                if (foundPs != null) {
9202                    nonMutatedPs = new PackageSetting(foundPs);
9203                }
9204            }
9205
9206            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9207                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9208                if (foundPs != null) {
9209                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9210                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9211                }
9212            }
9213
9214            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9215            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9216                PackageManagerService.reportSettingsProblem(Log.WARN,
9217                        "Package " + pkg.packageName + " shared user changed from "
9218                                + (pkgSetting.sharedUser != null
9219                                        ? pkgSetting.sharedUser.name : "<nothing>")
9220                                + " to "
9221                                + (suid != null ? suid.name : "<nothing>")
9222                                + "; replacing with new");
9223                pkgSetting = null;
9224            }
9225            final PackageSetting oldPkgSetting =
9226                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9227            final PackageSetting disabledPkgSetting =
9228                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9229
9230            String[] usesStaticLibraries = null;
9231            if (pkg.usesStaticLibraries != null) {
9232                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9233                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9234            }
9235
9236            if (pkgSetting == null) {
9237                final String parentPackageName = (pkg.parentPackage != null)
9238                        ? pkg.parentPackage.packageName : null;
9239                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9240                // REMOVE SharedUserSetting from method; update in a separate call
9241                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9242                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9243                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9244                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9245                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9246                        true /*allowInstall*/, instantApp, parentPackageName,
9247                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9248                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9249                // SIDE EFFECTS; updates system state; move elsewhere
9250                if (origPackage != null) {
9251                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9252                }
9253                mSettings.addUserToSettingLPw(pkgSetting);
9254            } else {
9255                // REMOVE SharedUserSetting from method; update in a separate call.
9256                //
9257                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9258                // secondaryCpuAbi are not known at this point so we always update them
9259                // to null here, only to reset them at a later point.
9260                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9261                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9262                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9263                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9264                        UserManagerService.getInstance(), usesStaticLibraries,
9265                        pkg.usesStaticLibrariesVersions);
9266            }
9267            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9268            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9269
9270            // SIDE EFFECTS; modifies system state; move elsewhere
9271            if (pkgSetting.origPackage != null) {
9272                // If we are first transitioning from an original package,
9273                // fix up the new package's name now.  We need to do this after
9274                // looking up the package under its new name, so getPackageLP
9275                // can take care of fiddling things correctly.
9276                pkg.setPackageName(origPackage.name);
9277
9278                // File a report about this.
9279                String msg = "New package " + pkgSetting.realName
9280                        + " renamed to replace old package " + pkgSetting.name;
9281                reportSettingsProblem(Log.WARN, msg);
9282
9283                // Make a note of it.
9284                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9285                    mTransferedPackages.add(origPackage.name);
9286                }
9287
9288                // No longer need to retain this.
9289                pkgSetting.origPackage = null;
9290            }
9291
9292            // SIDE EFFECTS; modifies system state; move elsewhere
9293            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9294                // Make a note of it.
9295                mTransferedPackages.add(pkg.packageName);
9296            }
9297
9298            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9299                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9300            }
9301
9302            if ((scanFlags & SCAN_BOOTING) == 0
9303                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9304                // Check all shared libraries and map to their actual file path.
9305                // We only do this here for apps not on a system dir, because those
9306                // are the only ones that can fail an install due to this.  We
9307                // will take care of the system apps by updating all of their
9308                // library paths after the scan is done. Also during the initial
9309                // scan don't update any libs as we do this wholesale after all
9310                // apps are scanned to avoid dependency based scanning.
9311                updateSharedLibrariesLPr(pkg, null);
9312            }
9313
9314            if (mFoundPolicyFile) {
9315                SELinuxMMAC.assignSeInfoValue(pkg);
9316            }
9317            pkg.applicationInfo.uid = pkgSetting.appId;
9318            pkg.mExtras = pkgSetting;
9319
9320
9321            // Static shared libs have same package with different versions where
9322            // we internally use a synthetic package name to allow multiple versions
9323            // of the same package, therefore we need to compare signatures against
9324            // the package setting for the latest library version.
9325            PackageSetting signatureCheckPs = pkgSetting;
9326            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9327                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9328                if (libraryEntry != null) {
9329                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9330                }
9331            }
9332
9333            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9334                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9335                    // We just determined the app is signed correctly, so bring
9336                    // over the latest parsed certs.
9337                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9338                } else {
9339                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9340                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9341                                "Package " + pkg.packageName + " upgrade keys do not match the "
9342                                + "previously installed version");
9343                    } else {
9344                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9345                        String msg = "System package " + pkg.packageName
9346                                + " signature changed; retaining data.";
9347                        reportSettingsProblem(Log.WARN, msg);
9348                    }
9349                }
9350            } else {
9351                try {
9352                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9353                    verifySignaturesLP(signatureCheckPs, pkg);
9354                    // We just determined the app is signed correctly, so bring
9355                    // over the latest parsed certs.
9356                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9357                } catch (PackageManagerException e) {
9358                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9359                        throw e;
9360                    }
9361                    // The signature has changed, but this package is in the system
9362                    // image...  let's recover!
9363                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9364                    // However...  if this package is part of a shared user, but it
9365                    // doesn't match the signature of the shared user, let's fail.
9366                    // What this means is that you can't change the signatures
9367                    // associated with an overall shared user, which doesn't seem all
9368                    // that unreasonable.
9369                    if (signatureCheckPs.sharedUser != null) {
9370                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9371                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9372                            throw new PackageManagerException(
9373                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9374                                    "Signature mismatch for shared user: "
9375                                            + pkgSetting.sharedUser);
9376                        }
9377                    }
9378                    // File a report about this.
9379                    String msg = "System package " + pkg.packageName
9380                            + " signature changed; retaining data.";
9381                    reportSettingsProblem(Log.WARN, msg);
9382                }
9383            }
9384
9385            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9386                // This package wants to adopt ownership of permissions from
9387                // another package.
9388                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9389                    final String origName = pkg.mAdoptPermissions.get(i);
9390                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9391                    if (orig != null) {
9392                        if (verifyPackageUpdateLPr(orig, pkg)) {
9393                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9394                                    + pkg.packageName);
9395                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9396                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9397                        }
9398                    }
9399                }
9400            }
9401        }
9402
9403        pkg.applicationInfo.processName = fixProcessName(
9404                pkg.applicationInfo.packageName,
9405                pkg.applicationInfo.processName);
9406
9407        if (pkg != mPlatformPackage) {
9408            // Get all of our default paths setup
9409            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9410        }
9411
9412        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9413
9414        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9415            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9416                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9417                derivePackageAbi(
9418                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9419                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9420
9421                // Some system apps still use directory structure for native libraries
9422                // in which case we might end up not detecting abi solely based on apk
9423                // structure. Try to detect abi based on directory structure.
9424                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9425                        pkg.applicationInfo.primaryCpuAbi == null) {
9426                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9427                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9428                }
9429            } else {
9430                // This is not a first boot or an upgrade, don't bother deriving the
9431                // ABI during the scan. Instead, trust the value that was stored in the
9432                // package setting.
9433                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9434                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9435
9436                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9437
9438                if (DEBUG_ABI_SELECTION) {
9439                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9440                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9441                        pkg.applicationInfo.secondaryCpuAbi);
9442                }
9443            }
9444        } else {
9445            if ((scanFlags & SCAN_MOVE) != 0) {
9446                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9447                // but we already have this packages package info in the PackageSetting. We just
9448                // use that and derive the native library path based on the new codepath.
9449                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9450                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9451            }
9452
9453            // Set native library paths again. For moves, the path will be updated based on the
9454            // ABIs we've determined above. For non-moves, the path will be updated based on the
9455            // ABIs we determined during compilation, but the path will depend on the final
9456            // package path (after the rename away from the stage path).
9457            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9458        }
9459
9460        // This is a special case for the "system" package, where the ABI is
9461        // dictated by the zygote configuration (and init.rc). We should keep track
9462        // of this ABI so that we can deal with "normal" applications that run under
9463        // the same UID correctly.
9464        if (mPlatformPackage == pkg) {
9465            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9466                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9467        }
9468
9469        // If there's a mismatch between the abi-override in the package setting
9470        // and the abiOverride specified for the install. Warn about this because we
9471        // would've already compiled the app without taking the package setting into
9472        // account.
9473        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9474            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9475                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9476                        " for package " + pkg.packageName);
9477            }
9478        }
9479
9480        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9481        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9482        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9483
9484        // Copy the derived override back to the parsed package, so that we can
9485        // update the package settings accordingly.
9486        pkg.cpuAbiOverride = cpuAbiOverride;
9487
9488        if (DEBUG_ABI_SELECTION) {
9489            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9490                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9491                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9492        }
9493
9494        // Push the derived path down into PackageSettings so we know what to
9495        // clean up at uninstall time.
9496        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9497
9498        if (DEBUG_ABI_SELECTION) {
9499            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9500                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9501                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9502        }
9503
9504        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9505        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9506            // We don't do this here during boot because we can do it all
9507            // at once after scanning all existing packages.
9508            //
9509            // We also do this *before* we perform dexopt on this package, so that
9510            // we can avoid redundant dexopts, and also to make sure we've got the
9511            // code and package path correct.
9512            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9513        }
9514
9515        if (mFactoryTest && pkg.requestedPermissions.contains(
9516                android.Manifest.permission.FACTORY_TEST)) {
9517            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9518        }
9519
9520        if (isSystemApp(pkg)) {
9521            pkgSetting.isOrphaned = true;
9522        }
9523
9524        // Take care of first install / last update times.
9525        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9526        if (currentTime != 0) {
9527            if (pkgSetting.firstInstallTime == 0) {
9528                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9529            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9530                pkgSetting.lastUpdateTime = currentTime;
9531            }
9532        } else if (pkgSetting.firstInstallTime == 0) {
9533            // We need *something*.  Take time time stamp of the file.
9534            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9535        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9536            if (scanFileTime != pkgSetting.timeStamp) {
9537                // A package on the system image has changed; consider this
9538                // to be an update.
9539                pkgSetting.lastUpdateTime = scanFileTime;
9540            }
9541        }
9542        pkgSetting.setTimeStamp(scanFileTime);
9543
9544        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9545            if (nonMutatedPs != null) {
9546                synchronized (mPackages) {
9547                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9548                }
9549            }
9550        } else {
9551            final int userId = user == null ? 0 : user.getIdentifier();
9552            // Modify state for the given package setting
9553            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9554                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9555            if (pkgSetting.getInstantApp(userId)) {
9556                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9557            }
9558        }
9559        return pkg;
9560    }
9561
9562    /**
9563     * Applies policy to the parsed package based upon the given policy flags.
9564     * Ensures the package is in a good state.
9565     * <p>
9566     * Implementation detail: This method must NOT have any side effect. It would
9567     * ideally be static, but, it requires locks to read system state.
9568     */
9569    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9570        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9571            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9572            if (pkg.applicationInfo.isDirectBootAware()) {
9573                // we're direct boot aware; set for all components
9574                for (PackageParser.Service s : pkg.services) {
9575                    s.info.encryptionAware = s.info.directBootAware = true;
9576                }
9577                for (PackageParser.Provider p : pkg.providers) {
9578                    p.info.encryptionAware = p.info.directBootAware = true;
9579                }
9580                for (PackageParser.Activity a : pkg.activities) {
9581                    a.info.encryptionAware = a.info.directBootAware = true;
9582                }
9583                for (PackageParser.Activity r : pkg.receivers) {
9584                    r.info.encryptionAware = r.info.directBootAware = true;
9585                }
9586            }
9587        } else {
9588            // Only allow system apps to be flagged as core apps.
9589            pkg.coreApp = false;
9590            // clear flags not applicable to regular apps
9591            pkg.applicationInfo.privateFlags &=
9592                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9593            pkg.applicationInfo.privateFlags &=
9594                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9595        }
9596        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9597
9598        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9599            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9600        }
9601
9602        if (!isSystemApp(pkg)) {
9603            // Only system apps can use these features.
9604            pkg.mOriginalPackages = null;
9605            pkg.mRealPackage = null;
9606            pkg.mAdoptPermissions = null;
9607        }
9608    }
9609
9610    /**
9611     * Asserts the parsed package is valid according to the given policy. If the
9612     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
9613     * <p>
9614     * Implementation detail: This method must NOT have any side effects. It would
9615     * ideally be static, but, it requires locks to read system state.
9616     *
9617     * @throws PackageManagerException If the package fails any of the validation checks
9618     */
9619    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9620            throws PackageManagerException {
9621        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9622            assertCodePolicy(pkg);
9623        }
9624
9625        if (pkg.applicationInfo.getCodePath() == null ||
9626                pkg.applicationInfo.getResourcePath() == null) {
9627            // Bail out. The resource and code paths haven't been set.
9628            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9629                    "Code and resource paths haven't been set correctly");
9630        }
9631
9632        // Make sure we're not adding any bogus keyset info
9633        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9634        ksms.assertScannedPackageValid(pkg);
9635
9636        synchronized (mPackages) {
9637            // The special "android" package can only be defined once
9638            if (pkg.packageName.equals("android")) {
9639                if (mAndroidApplication != null) {
9640                    Slog.w(TAG, "*************************************************");
9641                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9642                    Slog.w(TAG, " codePath=" + pkg.codePath);
9643                    Slog.w(TAG, "*************************************************");
9644                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9645                            "Core android package being redefined.  Skipping.");
9646                }
9647            }
9648
9649            // A package name must be unique; don't allow duplicates
9650            if (mPackages.containsKey(pkg.packageName)) {
9651                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9652                        "Application package " + pkg.packageName
9653                        + " already installed.  Skipping duplicate.");
9654            }
9655
9656            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9657                // Static libs have a synthetic package name containing the version
9658                // but we still want the base name to be unique.
9659                if (mPackages.containsKey(pkg.manifestPackageName)) {
9660                    throw new PackageManagerException(
9661                            "Duplicate static shared lib provider package");
9662                }
9663
9664                // Static shared libraries should have at least O target SDK
9665                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9666                    throw new PackageManagerException(
9667                            "Packages declaring static-shared libs must target O SDK or higher");
9668                }
9669
9670                // Package declaring static a shared lib cannot be instant apps
9671                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9672                    throw new PackageManagerException(
9673                            "Packages declaring static-shared libs cannot be instant apps");
9674                }
9675
9676                // Package declaring static a shared lib cannot be renamed since the package
9677                // name is synthetic and apps can't code around package manager internals.
9678                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9679                    throw new PackageManagerException(
9680                            "Packages declaring static-shared libs cannot be renamed");
9681                }
9682
9683                // Package declaring static a shared lib cannot declare child packages
9684                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9685                    throw new PackageManagerException(
9686                            "Packages declaring static-shared libs cannot have child packages");
9687                }
9688
9689                // Package declaring static a shared lib cannot declare dynamic libs
9690                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9691                    throw new PackageManagerException(
9692                            "Packages declaring static-shared libs cannot declare dynamic libs");
9693                }
9694
9695                // Package declaring static a shared lib cannot declare shared users
9696                if (pkg.mSharedUserId != null) {
9697                    throw new PackageManagerException(
9698                            "Packages declaring static-shared libs cannot declare shared users");
9699                }
9700
9701                // Static shared libs cannot declare activities
9702                if (!pkg.activities.isEmpty()) {
9703                    throw new PackageManagerException(
9704                            "Static shared libs cannot declare activities");
9705                }
9706
9707                // Static shared libs cannot declare services
9708                if (!pkg.services.isEmpty()) {
9709                    throw new PackageManagerException(
9710                            "Static shared libs cannot declare services");
9711                }
9712
9713                // Static shared libs cannot declare providers
9714                if (!pkg.providers.isEmpty()) {
9715                    throw new PackageManagerException(
9716                            "Static shared libs cannot declare content providers");
9717                }
9718
9719                // Static shared libs cannot declare receivers
9720                if (!pkg.receivers.isEmpty()) {
9721                    throw new PackageManagerException(
9722                            "Static shared libs cannot declare broadcast receivers");
9723                }
9724
9725                // Static shared libs cannot declare permission groups
9726                if (!pkg.permissionGroups.isEmpty()) {
9727                    throw new PackageManagerException(
9728                            "Static shared libs cannot declare permission groups");
9729                }
9730
9731                // Static shared libs cannot declare permissions
9732                if (!pkg.permissions.isEmpty()) {
9733                    throw new PackageManagerException(
9734                            "Static shared libs cannot declare permissions");
9735                }
9736
9737                // Static shared libs cannot declare protected broadcasts
9738                if (pkg.protectedBroadcasts != null) {
9739                    throw new PackageManagerException(
9740                            "Static shared libs cannot declare protected broadcasts");
9741                }
9742
9743                // Static shared libs cannot be overlay targets
9744                if (pkg.mOverlayTarget != null) {
9745                    throw new PackageManagerException(
9746                            "Static shared libs cannot be overlay targets");
9747                }
9748
9749                // The version codes must be ordered as lib versions
9750                int minVersionCode = Integer.MIN_VALUE;
9751                int maxVersionCode = Integer.MAX_VALUE;
9752
9753                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9754                        pkg.staticSharedLibName);
9755                if (versionedLib != null) {
9756                    final int versionCount = versionedLib.size();
9757                    for (int i = 0; i < versionCount; i++) {
9758                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9759                        // TODO: We will change version code to long, so in the new API it is long
9760                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9761                                .getVersionCode();
9762                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9763                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9764                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9765                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9766                        } else {
9767                            minVersionCode = maxVersionCode = libVersionCode;
9768                            break;
9769                        }
9770                    }
9771                }
9772                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9773                    throw new PackageManagerException("Static shared"
9774                            + " lib version codes must be ordered as lib versions");
9775                }
9776            }
9777
9778            // Only privileged apps and updated privileged apps can add child packages.
9779            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9780                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9781                    throw new PackageManagerException("Only privileged apps can add child "
9782                            + "packages. Ignoring package " + pkg.packageName);
9783                }
9784                final int childCount = pkg.childPackages.size();
9785                for (int i = 0; i < childCount; i++) {
9786                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9787                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9788                            childPkg.packageName)) {
9789                        throw new PackageManagerException("Can't override child of "
9790                                + "another disabled app. Ignoring package " + pkg.packageName);
9791                    }
9792                }
9793            }
9794
9795            // If we're only installing presumed-existing packages, require that the
9796            // scanned APK is both already known and at the path previously established
9797            // for it.  Previously unknown packages we pick up normally, but if we have an
9798            // a priori expectation about this package's install presence, enforce it.
9799            // With a singular exception for new system packages. When an OTA contains
9800            // a new system package, we allow the codepath to change from a system location
9801            // to the user-installed location. If we don't allow this change, any newer,
9802            // user-installed version of the application will be ignored.
9803            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9804                if (mExpectingBetter.containsKey(pkg.packageName)) {
9805                    logCriticalInfo(Log.WARN,
9806                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9807                } else {
9808                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9809                    if (known != null) {
9810                        if (DEBUG_PACKAGE_SCANNING) {
9811                            Log.d(TAG, "Examining " + pkg.codePath
9812                                    + " and requiring known paths " + known.codePathString
9813                                    + " & " + known.resourcePathString);
9814                        }
9815                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9816                                || !pkg.applicationInfo.getResourcePath().equals(
9817                                        known.resourcePathString)) {
9818                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9819                                    "Application package " + pkg.packageName
9820                                    + " found at " + pkg.applicationInfo.getCodePath()
9821                                    + " but expected at " + known.codePathString
9822                                    + "; ignoring.");
9823                        }
9824                    }
9825                }
9826            }
9827
9828            // Verify that this new package doesn't have any content providers
9829            // that conflict with existing packages.  Only do this if the
9830            // package isn't already installed, since we don't want to break
9831            // things that are installed.
9832            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9833                final int N = pkg.providers.size();
9834                int i;
9835                for (i=0; i<N; i++) {
9836                    PackageParser.Provider p = pkg.providers.get(i);
9837                    if (p.info.authority != null) {
9838                        String names[] = p.info.authority.split(";");
9839                        for (int j = 0; j < names.length; j++) {
9840                            if (mProvidersByAuthority.containsKey(names[j])) {
9841                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9842                                final String otherPackageName =
9843                                        ((other != null && other.getComponentName() != null) ?
9844                                                other.getComponentName().getPackageName() : "?");
9845                                throw new PackageManagerException(
9846                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9847                                        "Can't install because provider name " + names[j]
9848                                                + " (in package " + pkg.applicationInfo.packageName
9849                                                + ") is already used by " + otherPackageName);
9850                            }
9851                        }
9852                    }
9853                }
9854            }
9855        }
9856    }
9857
9858    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9859            int type, String declaringPackageName, int declaringVersionCode) {
9860        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9861        if (versionedLib == null) {
9862            versionedLib = new SparseArray<>();
9863            mSharedLibraries.put(name, versionedLib);
9864            if (type == SharedLibraryInfo.TYPE_STATIC) {
9865                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9866            }
9867        } else if (versionedLib.indexOfKey(version) >= 0) {
9868            return false;
9869        }
9870        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9871                version, type, declaringPackageName, declaringVersionCode);
9872        versionedLib.put(version, libEntry);
9873        return true;
9874    }
9875
9876    private boolean removeSharedLibraryLPw(String name, int version) {
9877        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9878        if (versionedLib == null) {
9879            return false;
9880        }
9881        final int libIdx = versionedLib.indexOfKey(version);
9882        if (libIdx < 0) {
9883            return false;
9884        }
9885        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9886        versionedLib.remove(version);
9887        if (versionedLib.size() <= 0) {
9888            mSharedLibraries.remove(name);
9889            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9890                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9891                        .getPackageName());
9892            }
9893        }
9894        return true;
9895    }
9896
9897    /**
9898     * Adds a scanned package to the system. When this method is finished, the package will
9899     * be available for query, resolution, etc...
9900     */
9901    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9902            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9903        final String pkgName = pkg.packageName;
9904        if (mCustomResolverComponentName != null &&
9905                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9906            setUpCustomResolverActivity(pkg);
9907        }
9908
9909        if (pkg.packageName.equals("android")) {
9910            synchronized (mPackages) {
9911                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9912                    // Set up information for our fall-back user intent resolution activity.
9913                    mPlatformPackage = pkg;
9914                    pkg.mVersionCode = mSdkVersion;
9915                    mAndroidApplication = pkg.applicationInfo;
9916                    if (!mResolverReplaced) {
9917                        mResolveActivity.applicationInfo = mAndroidApplication;
9918                        mResolveActivity.name = ResolverActivity.class.getName();
9919                        mResolveActivity.packageName = mAndroidApplication.packageName;
9920                        mResolveActivity.processName = "system:ui";
9921                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9922                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9923                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9924                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9925                        mResolveActivity.exported = true;
9926                        mResolveActivity.enabled = true;
9927                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9928                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9929                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9930                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9931                                | ActivityInfo.CONFIG_ORIENTATION
9932                                | ActivityInfo.CONFIG_KEYBOARD
9933                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9934                        mResolveInfo.activityInfo = mResolveActivity;
9935                        mResolveInfo.priority = 0;
9936                        mResolveInfo.preferredOrder = 0;
9937                        mResolveInfo.match = 0;
9938                        mResolveComponentName = new ComponentName(
9939                                mAndroidApplication.packageName, mResolveActivity.name);
9940                    }
9941                }
9942            }
9943        }
9944
9945        ArrayList<PackageParser.Package> clientLibPkgs = null;
9946        // writer
9947        synchronized (mPackages) {
9948            boolean hasStaticSharedLibs = false;
9949
9950            // Any app can add new static shared libraries
9951            if (pkg.staticSharedLibName != null) {
9952                // Static shared libs don't allow renaming as they have synthetic package
9953                // names to allow install of multiple versions, so use name from manifest.
9954                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9955                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9956                        pkg.manifestPackageName, pkg.mVersionCode)) {
9957                    hasStaticSharedLibs = true;
9958                } else {
9959                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9960                                + pkg.staticSharedLibName + " already exists; skipping");
9961                }
9962                // Static shared libs cannot be updated once installed since they
9963                // use synthetic package name which includes the version code, so
9964                // not need to update other packages's shared lib dependencies.
9965            }
9966
9967            if (!hasStaticSharedLibs
9968                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9969                // Only system apps can add new dynamic shared libraries.
9970                if (pkg.libraryNames != null) {
9971                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9972                        String name = pkg.libraryNames.get(i);
9973                        boolean allowed = false;
9974                        if (pkg.isUpdatedSystemApp()) {
9975                            // New library entries can only be added through the
9976                            // system image.  This is important to get rid of a lot
9977                            // of nasty edge cases: for example if we allowed a non-
9978                            // system update of the app to add a library, then uninstalling
9979                            // the update would make the library go away, and assumptions
9980                            // we made such as through app install filtering would now
9981                            // have allowed apps on the device which aren't compatible
9982                            // with it.  Better to just have the restriction here, be
9983                            // conservative, and create many fewer cases that can negatively
9984                            // impact the user experience.
9985                            final PackageSetting sysPs = mSettings
9986                                    .getDisabledSystemPkgLPr(pkg.packageName);
9987                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9988                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9989                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9990                                        allowed = true;
9991                                        break;
9992                                    }
9993                                }
9994                            }
9995                        } else {
9996                            allowed = true;
9997                        }
9998                        if (allowed) {
9999                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10000                                    SharedLibraryInfo.VERSION_UNDEFINED,
10001                                    SharedLibraryInfo.TYPE_DYNAMIC,
10002                                    pkg.packageName, pkg.mVersionCode)) {
10003                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10004                                        + name + " already exists; skipping");
10005                            }
10006                        } else {
10007                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10008                                    + name + " that is not declared on system image; skipping");
10009                        }
10010                    }
10011
10012                    if ((scanFlags & SCAN_BOOTING) == 0) {
10013                        // If we are not booting, we need to update any applications
10014                        // that are clients of our shared library.  If we are booting,
10015                        // this will all be done once the scan is complete.
10016                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10017                    }
10018                }
10019            }
10020        }
10021
10022        if ((scanFlags & SCAN_BOOTING) != 0) {
10023            // No apps can run during boot scan, so they don't need to be frozen
10024        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10025            // Caller asked to not kill app, so it's probably not frozen
10026        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10027            // Caller asked us to ignore frozen check for some reason; they
10028            // probably didn't know the package name
10029        } else {
10030            // We're doing major surgery on this package, so it better be frozen
10031            // right now to keep it from launching
10032            checkPackageFrozen(pkgName);
10033        }
10034
10035        // Also need to kill any apps that are dependent on the library.
10036        if (clientLibPkgs != null) {
10037            for (int i=0; i<clientLibPkgs.size(); i++) {
10038                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10039                killApplication(clientPkg.applicationInfo.packageName,
10040                        clientPkg.applicationInfo.uid, "update lib");
10041            }
10042        }
10043
10044        // writer
10045        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10046
10047        synchronized (mPackages) {
10048            // We don't expect installation to fail beyond this point
10049
10050            if (pkgSetting.pkg != null) {
10051                // Note that |user| might be null during the initial boot scan. If a codePath
10052                // for an app has changed during a boot scan, it's due to an app update that's
10053                // part of the system partition and marker changes must be applied to all users.
10054                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
10055                final int[] userIds = resolveUserIds(userId);
10056                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
10057            }
10058
10059            // Add the new setting to mSettings
10060            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10061            // Add the new setting to mPackages
10062            mPackages.put(pkg.applicationInfo.packageName, pkg);
10063            // Make sure we don't accidentally delete its data.
10064            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10065            while (iter.hasNext()) {
10066                PackageCleanItem item = iter.next();
10067                if (pkgName.equals(item.packageName)) {
10068                    iter.remove();
10069                }
10070            }
10071
10072            // Add the package's KeySets to the global KeySetManagerService
10073            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10074            ksms.addScannedPackageLPw(pkg);
10075
10076            int N = pkg.providers.size();
10077            StringBuilder r = null;
10078            int i;
10079            for (i=0; i<N; i++) {
10080                PackageParser.Provider p = pkg.providers.get(i);
10081                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10082                        p.info.processName);
10083                mProviders.addProvider(p);
10084                p.syncable = p.info.isSyncable;
10085                if (p.info.authority != null) {
10086                    String names[] = p.info.authority.split(";");
10087                    p.info.authority = null;
10088                    for (int j = 0; j < names.length; j++) {
10089                        if (j == 1 && p.syncable) {
10090                            // We only want the first authority for a provider to possibly be
10091                            // syncable, so if we already added this provider using a different
10092                            // authority clear the syncable flag. We copy the provider before
10093                            // changing it because the mProviders object contains a reference
10094                            // to a provider that we don't want to change.
10095                            // Only do this for the second authority since the resulting provider
10096                            // object can be the same for all future authorities for this provider.
10097                            p = new PackageParser.Provider(p);
10098                            p.syncable = false;
10099                        }
10100                        if (!mProvidersByAuthority.containsKey(names[j])) {
10101                            mProvidersByAuthority.put(names[j], p);
10102                            if (p.info.authority == null) {
10103                                p.info.authority = names[j];
10104                            } else {
10105                                p.info.authority = p.info.authority + ";" + names[j];
10106                            }
10107                            if (DEBUG_PACKAGE_SCANNING) {
10108                                if (chatty)
10109                                    Log.d(TAG, "Registered content provider: " + names[j]
10110                                            + ", className = " + p.info.name + ", isSyncable = "
10111                                            + p.info.isSyncable);
10112                            }
10113                        } else {
10114                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10115                            Slog.w(TAG, "Skipping provider name " + names[j] +
10116                                    " (in package " + pkg.applicationInfo.packageName +
10117                                    "): name already used by "
10118                                    + ((other != null && other.getComponentName() != null)
10119                                            ? other.getComponentName().getPackageName() : "?"));
10120                        }
10121                    }
10122                }
10123                if (chatty) {
10124                    if (r == null) {
10125                        r = new StringBuilder(256);
10126                    } else {
10127                        r.append(' ');
10128                    }
10129                    r.append(p.info.name);
10130                }
10131            }
10132            if (r != null) {
10133                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10134            }
10135
10136            N = pkg.services.size();
10137            r = null;
10138            for (i=0; i<N; i++) {
10139                PackageParser.Service s = pkg.services.get(i);
10140                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10141                        s.info.processName);
10142                mServices.addService(s);
10143                if (chatty) {
10144                    if (r == null) {
10145                        r = new StringBuilder(256);
10146                    } else {
10147                        r.append(' ');
10148                    }
10149                    r.append(s.info.name);
10150                }
10151            }
10152            if (r != null) {
10153                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10154            }
10155
10156            N = pkg.receivers.size();
10157            r = null;
10158            for (i=0; i<N; i++) {
10159                PackageParser.Activity a = pkg.receivers.get(i);
10160                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10161                        a.info.processName);
10162                mReceivers.addActivity(a, "receiver");
10163                if (chatty) {
10164                    if (r == null) {
10165                        r = new StringBuilder(256);
10166                    } else {
10167                        r.append(' ');
10168                    }
10169                    r.append(a.info.name);
10170                }
10171            }
10172            if (r != null) {
10173                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10174            }
10175
10176            N = pkg.activities.size();
10177            r = null;
10178            for (i=0; i<N; i++) {
10179                PackageParser.Activity a = pkg.activities.get(i);
10180                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10181                        a.info.processName);
10182                mActivities.addActivity(a, "activity");
10183                if (chatty) {
10184                    if (r == null) {
10185                        r = new StringBuilder(256);
10186                    } else {
10187                        r.append(' ');
10188                    }
10189                    r.append(a.info.name);
10190                }
10191            }
10192            if (r != null) {
10193                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10194            }
10195
10196            N = pkg.permissionGroups.size();
10197            r = null;
10198            for (i=0; i<N; i++) {
10199                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10200                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10201                final String curPackageName = cur == null ? null : cur.info.packageName;
10202                // Dont allow ephemeral apps to define new permission groups.
10203                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10204                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10205                            + pg.info.packageName
10206                            + " ignored: instant apps cannot define new permission groups.");
10207                    continue;
10208                }
10209                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10210                if (cur == null || isPackageUpdate) {
10211                    mPermissionGroups.put(pg.info.name, pg);
10212                    if (chatty) {
10213                        if (r == null) {
10214                            r = new StringBuilder(256);
10215                        } else {
10216                            r.append(' ');
10217                        }
10218                        if (isPackageUpdate) {
10219                            r.append("UPD:");
10220                        }
10221                        r.append(pg.info.name);
10222                    }
10223                } else {
10224                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10225                            + pg.info.packageName + " ignored: original from "
10226                            + cur.info.packageName);
10227                    if (chatty) {
10228                        if (r == null) {
10229                            r = new StringBuilder(256);
10230                        } else {
10231                            r.append(' ');
10232                        }
10233                        r.append("DUP:");
10234                        r.append(pg.info.name);
10235                    }
10236                }
10237            }
10238            if (r != null) {
10239                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10240            }
10241
10242            N = pkg.permissions.size();
10243            r = null;
10244            for (i=0; i<N; i++) {
10245                PackageParser.Permission p = pkg.permissions.get(i);
10246
10247                // Dont allow ephemeral apps to define new permissions.
10248                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10249                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10250                            + p.info.packageName
10251                            + " ignored: instant apps cannot define new permissions.");
10252                    continue;
10253                }
10254
10255                // Assume by default that we did not install this permission into the system.
10256                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10257
10258                // Now that permission groups have a special meaning, we ignore permission
10259                // groups for legacy apps to prevent unexpected behavior. In particular,
10260                // permissions for one app being granted to someone just becase they happen
10261                // to be in a group defined by another app (before this had no implications).
10262                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10263                    p.group = mPermissionGroups.get(p.info.group);
10264                    // Warn for a permission in an unknown group.
10265                    if (p.info.group != null && p.group == null) {
10266                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10267                                + p.info.packageName + " in an unknown group " + p.info.group);
10268                    }
10269                }
10270
10271                ArrayMap<String, BasePermission> permissionMap =
10272                        p.tree ? mSettings.mPermissionTrees
10273                                : mSettings.mPermissions;
10274                BasePermission bp = permissionMap.get(p.info.name);
10275
10276                // Allow system apps to redefine non-system permissions
10277                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10278                    final boolean currentOwnerIsSystem = (bp.perm != null
10279                            && isSystemApp(bp.perm.owner));
10280                    if (isSystemApp(p.owner)) {
10281                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10282                            // It's a built-in permission and no owner, take ownership now
10283                            bp.packageSetting = pkgSetting;
10284                            bp.perm = p;
10285                            bp.uid = pkg.applicationInfo.uid;
10286                            bp.sourcePackage = p.info.packageName;
10287                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10288                        } else if (!currentOwnerIsSystem) {
10289                            String msg = "New decl " + p.owner + " of permission  "
10290                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10291                            reportSettingsProblem(Log.WARN, msg);
10292                            bp = null;
10293                        }
10294                    }
10295                }
10296
10297                if (bp == null) {
10298                    bp = new BasePermission(p.info.name, p.info.packageName,
10299                            BasePermission.TYPE_NORMAL);
10300                    permissionMap.put(p.info.name, bp);
10301                }
10302
10303                if (bp.perm == null) {
10304                    if (bp.sourcePackage == null
10305                            || bp.sourcePackage.equals(p.info.packageName)) {
10306                        BasePermission tree = findPermissionTreeLP(p.info.name);
10307                        if (tree == null
10308                                || tree.sourcePackage.equals(p.info.packageName)) {
10309                            bp.packageSetting = pkgSetting;
10310                            bp.perm = p;
10311                            bp.uid = pkg.applicationInfo.uid;
10312                            bp.sourcePackage = p.info.packageName;
10313                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10314                            if (chatty) {
10315                                if (r == null) {
10316                                    r = new StringBuilder(256);
10317                                } else {
10318                                    r.append(' ');
10319                                }
10320                                r.append(p.info.name);
10321                            }
10322                        } else {
10323                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10324                                    + p.info.packageName + " ignored: base tree "
10325                                    + tree.name + " is from package "
10326                                    + tree.sourcePackage);
10327                        }
10328                    } else {
10329                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10330                                + p.info.packageName + " ignored: original from "
10331                                + bp.sourcePackage);
10332                    }
10333                } else if (chatty) {
10334                    if (r == null) {
10335                        r = new StringBuilder(256);
10336                    } else {
10337                        r.append(' ');
10338                    }
10339                    r.append("DUP:");
10340                    r.append(p.info.name);
10341                }
10342                if (bp.perm == p) {
10343                    bp.protectionLevel = p.info.protectionLevel;
10344                }
10345            }
10346
10347            if (r != null) {
10348                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10349            }
10350
10351            N = pkg.instrumentation.size();
10352            r = null;
10353            for (i=0; i<N; i++) {
10354                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10355                a.info.packageName = pkg.applicationInfo.packageName;
10356                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10357                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10358                a.info.splitNames = pkg.splitNames;
10359                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10360                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10361                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10362                a.info.dataDir = pkg.applicationInfo.dataDir;
10363                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10364                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10365                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10366                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10367                mInstrumentation.put(a.getComponentName(), a);
10368                if (chatty) {
10369                    if (r == null) {
10370                        r = new StringBuilder(256);
10371                    } else {
10372                        r.append(' ');
10373                    }
10374                    r.append(a.info.name);
10375                }
10376            }
10377            if (r != null) {
10378                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10379            }
10380
10381            if (pkg.protectedBroadcasts != null) {
10382                N = pkg.protectedBroadcasts.size();
10383                for (i=0; i<N; i++) {
10384                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10385                }
10386            }
10387        }
10388
10389        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10390    }
10391
10392    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
10393            PackageParser.Package update, int[] userIds) {
10394        if (existing.applicationInfo == null || update.applicationInfo == null) {
10395            // This isn't due to an app installation.
10396            return;
10397        }
10398
10399        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
10400        final File newCodePath = new File(update.applicationInfo.getCodePath());
10401
10402        // The codePath hasn't changed, so there's nothing for us to do.
10403        if (Objects.equals(oldCodePath, newCodePath)) {
10404            return;
10405        }
10406
10407        File canonicalNewCodePath;
10408        try {
10409            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
10410        } catch (IOException e) {
10411            Slog.w(TAG, "Failed to get canonical path.", e);
10412            return;
10413        }
10414
10415        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
10416        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
10417        // that the last component of the path (i.e, the name) doesn't need canonicalization
10418        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
10419        // but may change in the future. Hopefully this function won't exist at that point.
10420        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
10421                oldCodePath.getName());
10422
10423        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
10424        // with "@".
10425        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
10426        if (!oldMarkerPrefix.endsWith("@")) {
10427            oldMarkerPrefix += "@";
10428        }
10429        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
10430        if (!newMarkerPrefix.endsWith("@")) {
10431            newMarkerPrefix += "@";
10432        }
10433
10434        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
10435        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
10436        for (String updatedPath : updatedPaths) {
10437            String updatedPathName = new File(updatedPath).getName();
10438            markerSuffixes.add(updatedPathName.replace('/', '@'));
10439        }
10440
10441        for (int userId : userIds) {
10442            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
10443
10444            for (String markerSuffix : markerSuffixes) {
10445                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
10446                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
10447                if (oldForeignUseMark.exists()) {
10448                    try {
10449                        Os.rename(oldForeignUseMark.getAbsolutePath(),
10450                                newForeignUseMark.getAbsolutePath());
10451                    } catch (ErrnoException e) {
10452                        Slog.w(TAG, "Failed to rename foreign use marker", e);
10453                        oldForeignUseMark.delete();
10454                    }
10455                }
10456            }
10457        }
10458    }
10459
10460    /**
10461     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10462     * is derived purely on the basis of the contents of {@code scanFile} and
10463     * {@code cpuAbiOverride}.
10464     *
10465     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10466     */
10467    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10468                                 String cpuAbiOverride, boolean extractLibs,
10469                                 File appLib32InstallDir)
10470            throws PackageManagerException {
10471        // Give ourselves some initial paths; we'll come back for another
10472        // pass once we've determined ABI below.
10473        setNativeLibraryPaths(pkg, appLib32InstallDir);
10474
10475        // We would never need to extract libs for forward-locked and external packages,
10476        // since the container service will do it for us. We shouldn't attempt to
10477        // extract libs from system app when it was not updated.
10478        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10479                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10480            extractLibs = false;
10481        }
10482
10483        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10484        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10485
10486        NativeLibraryHelper.Handle handle = null;
10487        try {
10488            handle = NativeLibraryHelper.Handle.create(pkg);
10489            // TODO(multiArch): This can be null for apps that didn't go through the
10490            // usual installation process. We can calculate it again, like we
10491            // do during install time.
10492            //
10493            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10494            // unnecessary.
10495            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10496
10497            // Null out the abis so that they can be recalculated.
10498            pkg.applicationInfo.primaryCpuAbi = null;
10499            pkg.applicationInfo.secondaryCpuAbi = null;
10500            if (isMultiArch(pkg.applicationInfo)) {
10501                // Warn if we've set an abiOverride for multi-lib packages..
10502                // By definition, we need to copy both 32 and 64 bit libraries for
10503                // such packages.
10504                if (pkg.cpuAbiOverride != null
10505                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10506                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10507                }
10508
10509                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10510                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10511                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10512                    if (extractLibs) {
10513                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10514                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10515                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10516                                useIsaSpecificSubdirs);
10517                    } else {
10518                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10519                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10520                    }
10521                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10522                }
10523
10524                maybeThrowExceptionForMultiArchCopy(
10525                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10526
10527                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10528                    if (extractLibs) {
10529                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10530                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10531                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10532                                useIsaSpecificSubdirs);
10533                    } else {
10534                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10535                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10536                    }
10537                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10538                }
10539
10540                maybeThrowExceptionForMultiArchCopy(
10541                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10542
10543                if (abi64 >= 0) {
10544                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10545                }
10546
10547                if (abi32 >= 0) {
10548                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10549                    if (abi64 >= 0) {
10550                        if (pkg.use32bitAbi) {
10551                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10552                            pkg.applicationInfo.primaryCpuAbi = abi;
10553                        } else {
10554                            pkg.applicationInfo.secondaryCpuAbi = abi;
10555                        }
10556                    } else {
10557                        pkg.applicationInfo.primaryCpuAbi = abi;
10558                    }
10559                }
10560
10561            } else {
10562                String[] abiList = (cpuAbiOverride != null) ?
10563                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10564
10565                // Enable gross and lame hacks for apps that are built with old
10566                // SDK tools. We must scan their APKs for renderscript bitcode and
10567                // not launch them if it's present. Don't bother checking on devices
10568                // that don't have 64 bit support.
10569                boolean needsRenderScriptOverride = false;
10570                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10571                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10572                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10573                    needsRenderScriptOverride = true;
10574                }
10575
10576                final int copyRet;
10577                if (extractLibs) {
10578                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10579                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10580                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10581                } else {
10582                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10583                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10584                }
10585                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10586
10587                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10588                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10589                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10590                }
10591
10592                if (copyRet >= 0) {
10593                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10594                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10595                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10596                } else if (needsRenderScriptOverride) {
10597                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10598                }
10599            }
10600        } catch (IOException ioe) {
10601            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10602        } finally {
10603            IoUtils.closeQuietly(handle);
10604        }
10605
10606        // Now that we've calculated the ABIs and determined if it's an internal app,
10607        // we will go ahead and populate the nativeLibraryPath.
10608        setNativeLibraryPaths(pkg, appLib32InstallDir);
10609    }
10610
10611    /**
10612     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10613     * i.e, so that all packages can be run inside a single process if required.
10614     *
10615     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10616     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10617     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10618     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10619     * updating a package that belongs to a shared user.
10620     *
10621     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10622     * adds unnecessary complexity.
10623     */
10624    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10625            PackageParser.Package scannedPackage) {
10626        String requiredInstructionSet = null;
10627        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10628            requiredInstructionSet = VMRuntime.getInstructionSet(
10629                     scannedPackage.applicationInfo.primaryCpuAbi);
10630        }
10631
10632        PackageSetting requirer = null;
10633        for (PackageSetting ps : packagesForUser) {
10634            // If packagesForUser contains scannedPackage, we skip it. This will happen
10635            // when scannedPackage is an update of an existing package. Without this check,
10636            // we will never be able to change the ABI of any package belonging to a shared
10637            // user, even if it's compatible with other packages.
10638            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10639                if (ps.primaryCpuAbiString == null) {
10640                    continue;
10641                }
10642
10643                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10644                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10645                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10646                    // this but there's not much we can do.
10647                    String errorMessage = "Instruction set mismatch, "
10648                            + ((requirer == null) ? "[caller]" : requirer)
10649                            + " requires " + requiredInstructionSet + " whereas " + ps
10650                            + " requires " + instructionSet;
10651                    Slog.w(TAG, errorMessage);
10652                }
10653
10654                if (requiredInstructionSet == null) {
10655                    requiredInstructionSet = instructionSet;
10656                    requirer = ps;
10657                }
10658            }
10659        }
10660
10661        if (requiredInstructionSet != null) {
10662            String adjustedAbi;
10663            if (requirer != null) {
10664                // requirer != null implies that either scannedPackage was null or that scannedPackage
10665                // did not require an ABI, in which case we have to adjust scannedPackage to match
10666                // the ABI of the set (which is the same as requirer's ABI)
10667                adjustedAbi = requirer.primaryCpuAbiString;
10668                if (scannedPackage != null) {
10669                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10670                }
10671            } else {
10672                // requirer == null implies that we're updating all ABIs in the set to
10673                // match scannedPackage.
10674                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10675            }
10676
10677            for (PackageSetting ps : packagesForUser) {
10678                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10679                    if (ps.primaryCpuAbiString != null) {
10680                        continue;
10681                    }
10682
10683                    ps.primaryCpuAbiString = adjustedAbi;
10684                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10685                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10686                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10687                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10688                                + " (requirer="
10689                                + (requirer == null ? "null" : requirer.pkg.packageName)
10690                                + ", scannedPackage="
10691                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10692                                + ")");
10693                        try {
10694                            mInstaller.rmdex(ps.codePathString,
10695                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10696                        } catch (InstallerException ignored) {
10697                        }
10698                    }
10699                }
10700            }
10701        }
10702    }
10703
10704    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10705        synchronized (mPackages) {
10706            mResolverReplaced = true;
10707            // Set up information for custom user intent resolution activity.
10708            mResolveActivity.applicationInfo = pkg.applicationInfo;
10709            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10710            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10711            mResolveActivity.processName = pkg.applicationInfo.packageName;
10712            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10713            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10714                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10715            mResolveActivity.theme = 0;
10716            mResolveActivity.exported = true;
10717            mResolveActivity.enabled = true;
10718            mResolveInfo.activityInfo = mResolveActivity;
10719            mResolveInfo.priority = 0;
10720            mResolveInfo.preferredOrder = 0;
10721            mResolveInfo.match = 0;
10722            mResolveComponentName = mCustomResolverComponentName;
10723            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10724                    mResolveComponentName);
10725        }
10726    }
10727
10728    private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) {
10729        if (installerComponent == null) {
10730            if (DEBUG_EPHEMERAL) {
10731                Slog.d(TAG, "Clear ephemeral installer activity");
10732            }
10733            mInstantAppInstallerActivity.applicationInfo = null;
10734            return;
10735        }
10736
10737        if (DEBUG_EPHEMERAL) {
10738            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10739        }
10740        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10741        // Set up information for ephemeral installer activity
10742        mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo;
10743        mInstantAppInstallerActivity.name = installerComponent.getClassName();
10744        mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName;
10745        mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName;
10746        mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10747        mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10748                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10749        mInstantAppInstallerActivity.theme = 0;
10750        mInstantAppInstallerActivity.exported = true;
10751        mInstantAppInstallerActivity.enabled = true;
10752        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10753        mInstantAppInstallerInfo.priority = 0;
10754        mInstantAppInstallerInfo.preferredOrder = 1;
10755        mInstantAppInstallerInfo.isDefault = true;
10756        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10757                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10758    }
10759
10760    private static String calculateBundledApkRoot(final String codePathString) {
10761        final File codePath = new File(codePathString);
10762        final File codeRoot;
10763        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10764            codeRoot = Environment.getRootDirectory();
10765        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10766            codeRoot = Environment.getOemDirectory();
10767        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10768            codeRoot = Environment.getVendorDirectory();
10769        } else {
10770            // Unrecognized code path; take its top real segment as the apk root:
10771            // e.g. /something/app/blah.apk => /something
10772            try {
10773                File f = codePath.getCanonicalFile();
10774                File parent = f.getParentFile();    // non-null because codePath is a file
10775                File tmp;
10776                while ((tmp = parent.getParentFile()) != null) {
10777                    f = parent;
10778                    parent = tmp;
10779                }
10780                codeRoot = f;
10781                Slog.w(TAG, "Unrecognized code path "
10782                        + codePath + " - using " + codeRoot);
10783            } catch (IOException e) {
10784                // Can't canonicalize the code path -- shenanigans?
10785                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10786                return Environment.getRootDirectory().getPath();
10787            }
10788        }
10789        return codeRoot.getPath();
10790    }
10791
10792    /**
10793     * Derive and set the location of native libraries for the given package,
10794     * which varies depending on where and how the package was installed.
10795     */
10796    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10797        final ApplicationInfo info = pkg.applicationInfo;
10798        final String codePath = pkg.codePath;
10799        final File codeFile = new File(codePath);
10800        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10801        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10802
10803        info.nativeLibraryRootDir = null;
10804        info.nativeLibraryRootRequiresIsa = false;
10805        info.nativeLibraryDir = null;
10806        info.secondaryNativeLibraryDir = null;
10807
10808        if (isApkFile(codeFile)) {
10809            // Monolithic install
10810            if (bundledApp) {
10811                // If "/system/lib64/apkname" exists, assume that is the per-package
10812                // native library directory to use; otherwise use "/system/lib/apkname".
10813                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10814                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10815                        getPrimaryInstructionSet(info));
10816
10817                // This is a bundled system app so choose the path based on the ABI.
10818                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10819                // is just the default path.
10820                final String apkName = deriveCodePathName(codePath);
10821                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10822                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10823                        apkName).getAbsolutePath();
10824
10825                if (info.secondaryCpuAbi != null) {
10826                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10827                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10828                            secondaryLibDir, apkName).getAbsolutePath();
10829                }
10830            } else if (asecApp) {
10831                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10832                        .getAbsolutePath();
10833            } else {
10834                final String apkName = deriveCodePathName(codePath);
10835                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10836                        .getAbsolutePath();
10837            }
10838
10839            info.nativeLibraryRootRequiresIsa = false;
10840            info.nativeLibraryDir = info.nativeLibraryRootDir;
10841        } else {
10842            // Cluster install
10843            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10844            info.nativeLibraryRootRequiresIsa = true;
10845
10846            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10847                    getPrimaryInstructionSet(info)).getAbsolutePath();
10848
10849            if (info.secondaryCpuAbi != null) {
10850                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10851                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10852            }
10853        }
10854    }
10855
10856    /**
10857     * Calculate the abis and roots for a bundled app. These can uniquely
10858     * be determined from the contents of the system partition, i.e whether
10859     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10860     * of this information, and instead assume that the system was built
10861     * sensibly.
10862     */
10863    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10864                                           PackageSetting pkgSetting) {
10865        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10866
10867        // If "/system/lib64/apkname" exists, assume that is the per-package
10868        // native library directory to use; otherwise use "/system/lib/apkname".
10869        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10870        setBundledAppAbi(pkg, apkRoot, apkName);
10871        // pkgSetting might be null during rescan following uninstall of updates
10872        // to a bundled app, so accommodate that possibility.  The settings in
10873        // that case will be established later from the parsed package.
10874        //
10875        // If the settings aren't null, sync them up with what we've just derived.
10876        // note that apkRoot isn't stored in the package settings.
10877        if (pkgSetting != null) {
10878            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10879            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10880        }
10881    }
10882
10883    /**
10884     * Deduces the ABI of a bundled app and sets the relevant fields on the
10885     * parsed pkg object.
10886     *
10887     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10888     *        under which system libraries are installed.
10889     * @param apkName the name of the installed package.
10890     */
10891    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10892        final File codeFile = new File(pkg.codePath);
10893
10894        final boolean has64BitLibs;
10895        final boolean has32BitLibs;
10896        if (isApkFile(codeFile)) {
10897            // Monolithic install
10898            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10899            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10900        } else {
10901            // Cluster install
10902            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10903            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10904                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10905                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10906                has64BitLibs = (new File(rootDir, isa)).exists();
10907            } else {
10908                has64BitLibs = false;
10909            }
10910            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10911                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10912                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10913                has32BitLibs = (new File(rootDir, isa)).exists();
10914            } else {
10915                has32BitLibs = false;
10916            }
10917        }
10918
10919        if (has64BitLibs && !has32BitLibs) {
10920            // The package has 64 bit libs, but not 32 bit libs. Its primary
10921            // ABI should be 64 bit. We can safely assume here that the bundled
10922            // native libraries correspond to the most preferred ABI in the list.
10923
10924            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10925            pkg.applicationInfo.secondaryCpuAbi = null;
10926        } else if (has32BitLibs && !has64BitLibs) {
10927            // The package has 32 bit libs but not 64 bit libs. Its primary
10928            // ABI should be 32 bit.
10929
10930            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10931            pkg.applicationInfo.secondaryCpuAbi = null;
10932        } else if (has32BitLibs && has64BitLibs) {
10933            // The application has both 64 and 32 bit bundled libraries. We check
10934            // here that the app declares multiArch support, and warn if it doesn't.
10935            //
10936            // We will be lenient here and record both ABIs. The primary will be the
10937            // ABI that's higher on the list, i.e, a device that's configured to prefer
10938            // 64 bit apps will see a 64 bit primary ABI,
10939
10940            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10941                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10942            }
10943
10944            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10945                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10946                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10947            } else {
10948                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10949                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10950            }
10951        } else {
10952            pkg.applicationInfo.primaryCpuAbi = null;
10953            pkg.applicationInfo.secondaryCpuAbi = null;
10954        }
10955    }
10956
10957    private void killApplication(String pkgName, int appId, String reason) {
10958        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10959    }
10960
10961    private void killApplication(String pkgName, int appId, int userId, String reason) {
10962        // Request the ActivityManager to kill the process(only for existing packages)
10963        // so that we do not end up in a confused state while the user is still using the older
10964        // version of the application while the new one gets installed.
10965        final long token = Binder.clearCallingIdentity();
10966        try {
10967            IActivityManager am = ActivityManager.getService();
10968            if (am != null) {
10969                try {
10970                    am.killApplication(pkgName, appId, userId, reason);
10971                } catch (RemoteException e) {
10972                }
10973            }
10974        } finally {
10975            Binder.restoreCallingIdentity(token);
10976        }
10977    }
10978
10979    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10980        // Remove the parent package setting
10981        PackageSetting ps = (PackageSetting) pkg.mExtras;
10982        if (ps != null) {
10983            removePackageLI(ps, chatty);
10984        }
10985        // Remove the child package setting
10986        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10987        for (int i = 0; i < childCount; i++) {
10988            PackageParser.Package childPkg = pkg.childPackages.get(i);
10989            ps = (PackageSetting) childPkg.mExtras;
10990            if (ps != null) {
10991                removePackageLI(ps, chatty);
10992            }
10993        }
10994    }
10995
10996    void removePackageLI(PackageSetting ps, boolean chatty) {
10997        if (DEBUG_INSTALL) {
10998            if (chatty)
10999                Log.d(TAG, "Removing package " + ps.name);
11000        }
11001
11002        // writer
11003        synchronized (mPackages) {
11004            mPackages.remove(ps.name);
11005            final PackageParser.Package pkg = ps.pkg;
11006            if (pkg != null) {
11007                cleanPackageDataStructuresLILPw(pkg, chatty);
11008            }
11009        }
11010    }
11011
11012    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11013        if (DEBUG_INSTALL) {
11014            if (chatty)
11015                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11016        }
11017
11018        // writer
11019        synchronized (mPackages) {
11020            // Remove the parent package
11021            mPackages.remove(pkg.applicationInfo.packageName);
11022            cleanPackageDataStructuresLILPw(pkg, chatty);
11023
11024            // Remove the child packages
11025            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11026            for (int i = 0; i < childCount; i++) {
11027                PackageParser.Package childPkg = pkg.childPackages.get(i);
11028                mPackages.remove(childPkg.applicationInfo.packageName);
11029                cleanPackageDataStructuresLILPw(childPkg, chatty);
11030            }
11031        }
11032    }
11033
11034    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11035        int N = pkg.providers.size();
11036        StringBuilder r = null;
11037        int i;
11038        for (i=0; i<N; i++) {
11039            PackageParser.Provider p = pkg.providers.get(i);
11040            mProviders.removeProvider(p);
11041            if (p.info.authority == null) {
11042
11043                /* There was another ContentProvider with this authority when
11044                 * this app was installed so this authority is null,
11045                 * Ignore it as we don't have to unregister the provider.
11046                 */
11047                continue;
11048            }
11049            String names[] = p.info.authority.split(";");
11050            for (int j = 0; j < names.length; j++) {
11051                if (mProvidersByAuthority.get(names[j]) == p) {
11052                    mProvidersByAuthority.remove(names[j]);
11053                    if (DEBUG_REMOVE) {
11054                        if (chatty)
11055                            Log.d(TAG, "Unregistered content provider: " + names[j]
11056                                    + ", className = " + p.info.name + ", isSyncable = "
11057                                    + p.info.isSyncable);
11058                    }
11059                }
11060            }
11061            if (DEBUG_REMOVE && chatty) {
11062                if (r == null) {
11063                    r = new StringBuilder(256);
11064                } else {
11065                    r.append(' ');
11066                }
11067                r.append(p.info.name);
11068            }
11069        }
11070        if (r != null) {
11071            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11072        }
11073
11074        N = pkg.services.size();
11075        r = null;
11076        for (i=0; i<N; i++) {
11077            PackageParser.Service s = pkg.services.get(i);
11078            mServices.removeService(s);
11079            if (chatty) {
11080                if (r == null) {
11081                    r = new StringBuilder(256);
11082                } else {
11083                    r.append(' ');
11084                }
11085                r.append(s.info.name);
11086            }
11087        }
11088        if (r != null) {
11089            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11090        }
11091
11092        N = pkg.receivers.size();
11093        r = null;
11094        for (i=0; i<N; i++) {
11095            PackageParser.Activity a = pkg.receivers.get(i);
11096            mReceivers.removeActivity(a, "receiver");
11097            if (DEBUG_REMOVE && chatty) {
11098                if (r == null) {
11099                    r = new StringBuilder(256);
11100                } else {
11101                    r.append(' ');
11102                }
11103                r.append(a.info.name);
11104            }
11105        }
11106        if (r != null) {
11107            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11108        }
11109
11110        N = pkg.activities.size();
11111        r = null;
11112        for (i=0; i<N; i++) {
11113            PackageParser.Activity a = pkg.activities.get(i);
11114            mActivities.removeActivity(a, "activity");
11115            if (DEBUG_REMOVE && chatty) {
11116                if (r == null) {
11117                    r = new StringBuilder(256);
11118                } else {
11119                    r.append(' ');
11120                }
11121                r.append(a.info.name);
11122            }
11123        }
11124        if (r != null) {
11125            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11126        }
11127
11128        N = pkg.permissions.size();
11129        r = null;
11130        for (i=0; i<N; i++) {
11131            PackageParser.Permission p = pkg.permissions.get(i);
11132            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11133            if (bp == null) {
11134                bp = mSettings.mPermissionTrees.get(p.info.name);
11135            }
11136            if (bp != null && bp.perm == p) {
11137                bp.perm = null;
11138                if (DEBUG_REMOVE && chatty) {
11139                    if (r == null) {
11140                        r = new StringBuilder(256);
11141                    } else {
11142                        r.append(' ');
11143                    }
11144                    r.append(p.info.name);
11145                }
11146            }
11147            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11148                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11149                if (appOpPkgs != null) {
11150                    appOpPkgs.remove(pkg.packageName);
11151                }
11152            }
11153        }
11154        if (r != null) {
11155            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11156        }
11157
11158        N = pkg.requestedPermissions.size();
11159        r = null;
11160        for (i=0; i<N; i++) {
11161            String perm = pkg.requestedPermissions.get(i);
11162            BasePermission bp = mSettings.mPermissions.get(perm);
11163            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11164                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11165                if (appOpPkgs != null) {
11166                    appOpPkgs.remove(pkg.packageName);
11167                    if (appOpPkgs.isEmpty()) {
11168                        mAppOpPermissionPackages.remove(perm);
11169                    }
11170                }
11171            }
11172        }
11173        if (r != null) {
11174            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11175        }
11176
11177        N = pkg.instrumentation.size();
11178        r = null;
11179        for (i=0; i<N; i++) {
11180            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11181            mInstrumentation.remove(a.getComponentName());
11182            if (DEBUG_REMOVE && chatty) {
11183                if (r == null) {
11184                    r = new StringBuilder(256);
11185                } else {
11186                    r.append(' ');
11187                }
11188                r.append(a.info.name);
11189            }
11190        }
11191        if (r != null) {
11192            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11193        }
11194
11195        r = null;
11196        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11197            // Only system apps can hold shared libraries.
11198            if (pkg.libraryNames != null) {
11199                for (i = 0; i < pkg.libraryNames.size(); i++) {
11200                    String name = pkg.libraryNames.get(i);
11201                    if (removeSharedLibraryLPw(name, 0)) {
11202                        if (DEBUG_REMOVE && chatty) {
11203                            if (r == null) {
11204                                r = new StringBuilder(256);
11205                            } else {
11206                                r.append(' ');
11207                            }
11208                            r.append(name);
11209                        }
11210                    }
11211                }
11212            }
11213        }
11214
11215        r = null;
11216
11217        // Any package can hold static shared libraries.
11218        if (pkg.staticSharedLibName != null) {
11219            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11220                if (DEBUG_REMOVE && chatty) {
11221                    if (r == null) {
11222                        r = new StringBuilder(256);
11223                    } else {
11224                        r.append(' ');
11225                    }
11226                    r.append(pkg.staticSharedLibName);
11227                }
11228            }
11229        }
11230
11231        if (r != null) {
11232            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11233        }
11234    }
11235
11236    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11237        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11238            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11239                return true;
11240            }
11241        }
11242        return false;
11243    }
11244
11245    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11246    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11247    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11248
11249    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11250        // Update the parent permissions
11251        updatePermissionsLPw(pkg.packageName, pkg, flags);
11252        // Update the child permissions
11253        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11254        for (int i = 0; i < childCount; i++) {
11255            PackageParser.Package childPkg = pkg.childPackages.get(i);
11256            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11257        }
11258    }
11259
11260    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11261            int flags) {
11262        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11263        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11264    }
11265
11266    private void updatePermissionsLPw(String changingPkg,
11267            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11268        // Make sure there are no dangling permission trees.
11269        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11270        while (it.hasNext()) {
11271            final BasePermission bp = it.next();
11272            if (bp.packageSetting == null) {
11273                // We may not yet have parsed the package, so just see if
11274                // we still know about its settings.
11275                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11276            }
11277            if (bp.packageSetting == null) {
11278                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11279                        + " from package " + bp.sourcePackage);
11280                it.remove();
11281            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11282                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11283                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11284                            + " from package " + bp.sourcePackage);
11285                    flags |= UPDATE_PERMISSIONS_ALL;
11286                    it.remove();
11287                }
11288            }
11289        }
11290
11291        // Make sure all dynamic permissions have been assigned to a package,
11292        // and make sure there are no dangling permissions.
11293        it = mSettings.mPermissions.values().iterator();
11294        while (it.hasNext()) {
11295            final BasePermission bp = it.next();
11296            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11297                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11298                        + bp.name + " pkg=" + bp.sourcePackage
11299                        + " info=" + bp.pendingInfo);
11300                if (bp.packageSetting == null && bp.pendingInfo != null) {
11301                    final BasePermission tree = findPermissionTreeLP(bp.name);
11302                    if (tree != null && tree.perm != null) {
11303                        bp.packageSetting = tree.packageSetting;
11304                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11305                                new PermissionInfo(bp.pendingInfo));
11306                        bp.perm.info.packageName = tree.perm.info.packageName;
11307                        bp.perm.info.name = bp.name;
11308                        bp.uid = tree.uid;
11309                    }
11310                }
11311            }
11312            if (bp.packageSetting == null) {
11313                // We may not yet have parsed the package, so just see if
11314                // we still know about its settings.
11315                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11316            }
11317            if (bp.packageSetting == null) {
11318                Slog.w(TAG, "Removing dangling permission: " + bp.name
11319                        + " from package " + bp.sourcePackage);
11320                it.remove();
11321            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11322                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11323                    Slog.i(TAG, "Removing old permission: " + bp.name
11324                            + " from package " + bp.sourcePackage);
11325                    flags |= UPDATE_PERMISSIONS_ALL;
11326                    it.remove();
11327                }
11328            }
11329        }
11330
11331        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11332        // Now update the permissions for all packages, in particular
11333        // replace the granted permissions of the system packages.
11334        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11335            for (PackageParser.Package pkg : mPackages.values()) {
11336                if (pkg != pkgInfo) {
11337                    // Only replace for packages on requested volume
11338                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11339                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11340                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11341                    grantPermissionsLPw(pkg, replace, changingPkg);
11342                }
11343            }
11344        }
11345
11346        if (pkgInfo != null) {
11347            // Only replace for packages on requested volume
11348            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11349            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11350                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11351            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11352        }
11353        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11354    }
11355
11356    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11357            String packageOfInterest) {
11358        // IMPORTANT: There are two types of permissions: install and runtime.
11359        // Install time permissions are granted when the app is installed to
11360        // all device users and users added in the future. Runtime permissions
11361        // are granted at runtime explicitly to specific users. Normal and signature
11362        // protected permissions are install time permissions. Dangerous permissions
11363        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11364        // otherwise they are runtime permissions. This function does not manage
11365        // runtime permissions except for the case an app targeting Lollipop MR1
11366        // being upgraded to target a newer SDK, in which case dangerous permissions
11367        // are transformed from install time to runtime ones.
11368
11369        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11370        if (ps == null) {
11371            return;
11372        }
11373
11374        PermissionsState permissionsState = ps.getPermissionsState();
11375        PermissionsState origPermissions = permissionsState;
11376
11377        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11378
11379        boolean runtimePermissionsRevoked = false;
11380        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11381
11382        boolean changedInstallPermission = false;
11383
11384        if (replace) {
11385            ps.installPermissionsFixed = false;
11386            if (!ps.isSharedUser()) {
11387                origPermissions = new PermissionsState(permissionsState);
11388                permissionsState.reset();
11389            } else {
11390                // We need to know only about runtime permission changes since the
11391                // calling code always writes the install permissions state but
11392                // the runtime ones are written only if changed. The only cases of
11393                // changed runtime permissions here are promotion of an install to
11394                // runtime and revocation of a runtime from a shared user.
11395                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11396                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11397                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11398                    runtimePermissionsRevoked = true;
11399                }
11400            }
11401        }
11402
11403        permissionsState.setGlobalGids(mGlobalGids);
11404
11405        final int N = pkg.requestedPermissions.size();
11406        for (int i=0; i<N; i++) {
11407            final String name = pkg.requestedPermissions.get(i);
11408            final BasePermission bp = mSettings.mPermissions.get(name);
11409
11410            if (DEBUG_INSTALL) {
11411                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11412            }
11413
11414            if (bp == null || bp.packageSetting == null) {
11415                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11416                    Slog.w(TAG, "Unknown permission " + name
11417                            + " in package " + pkg.packageName);
11418                }
11419                continue;
11420            }
11421
11422
11423            // Limit ephemeral apps to ephemeral allowed permissions.
11424            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11425                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11426                        + pkg.packageName);
11427                continue;
11428            }
11429
11430            final String perm = bp.name;
11431            boolean allowedSig = false;
11432            int grant = GRANT_DENIED;
11433
11434            // Keep track of app op permissions.
11435            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11436                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11437                if (pkgs == null) {
11438                    pkgs = new ArraySet<>();
11439                    mAppOpPermissionPackages.put(bp.name, pkgs);
11440                }
11441                pkgs.add(pkg.packageName);
11442            }
11443
11444            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11445            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11446                    >= Build.VERSION_CODES.M;
11447            switch (level) {
11448                case PermissionInfo.PROTECTION_NORMAL: {
11449                    // For all apps normal permissions are install time ones.
11450                    grant = GRANT_INSTALL;
11451                } break;
11452
11453                case PermissionInfo.PROTECTION_DANGEROUS: {
11454                    // If a permission review is required for legacy apps we represent
11455                    // their permissions as always granted runtime ones since we need
11456                    // to keep the review required permission flag per user while an
11457                    // install permission's state is shared across all users.
11458                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11459                        // For legacy apps dangerous permissions are install time ones.
11460                        grant = GRANT_INSTALL;
11461                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11462                        // For legacy apps that became modern, install becomes runtime.
11463                        grant = GRANT_UPGRADE;
11464                    } else if (mPromoteSystemApps
11465                            && isSystemApp(ps)
11466                            && mExistingSystemPackages.contains(ps.name)) {
11467                        // For legacy system apps, install becomes runtime.
11468                        // We cannot check hasInstallPermission() for system apps since those
11469                        // permissions were granted implicitly and not persisted pre-M.
11470                        grant = GRANT_UPGRADE;
11471                    } else {
11472                        // For modern apps keep runtime permissions unchanged.
11473                        grant = GRANT_RUNTIME;
11474                    }
11475                } break;
11476
11477                case PermissionInfo.PROTECTION_SIGNATURE: {
11478                    // For all apps signature permissions are install time ones.
11479                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11480                    if (allowedSig) {
11481                        grant = GRANT_INSTALL;
11482                    }
11483                } break;
11484            }
11485
11486            if (DEBUG_INSTALL) {
11487                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11488            }
11489
11490            if (grant != GRANT_DENIED) {
11491                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11492                    // If this is an existing, non-system package, then
11493                    // we can't add any new permissions to it.
11494                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11495                        // Except...  if this is a permission that was added
11496                        // to the platform (note: need to only do this when
11497                        // updating the platform).
11498                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11499                            grant = GRANT_DENIED;
11500                        }
11501                    }
11502                }
11503
11504                switch (grant) {
11505                    case GRANT_INSTALL: {
11506                        // Revoke this as runtime permission to handle the case of
11507                        // a runtime permission being downgraded to an install one.
11508                        // Also in permission review mode we keep dangerous permissions
11509                        // for legacy apps
11510                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11511                            if (origPermissions.getRuntimePermissionState(
11512                                    bp.name, userId) != null) {
11513                                // Revoke the runtime permission and clear the flags.
11514                                origPermissions.revokeRuntimePermission(bp, userId);
11515                                origPermissions.updatePermissionFlags(bp, userId,
11516                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11517                                // If we revoked a permission permission, we have to write.
11518                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11519                                        changedRuntimePermissionUserIds, userId);
11520                            }
11521                        }
11522                        // Grant an install permission.
11523                        if (permissionsState.grantInstallPermission(bp) !=
11524                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11525                            changedInstallPermission = true;
11526                        }
11527                    } break;
11528
11529                    case GRANT_RUNTIME: {
11530                        // Grant previously granted runtime permissions.
11531                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11532                            PermissionState permissionState = origPermissions
11533                                    .getRuntimePermissionState(bp.name, userId);
11534                            int flags = permissionState != null
11535                                    ? permissionState.getFlags() : 0;
11536                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11537                                // Don't propagate the permission in a permission review mode if
11538                                // the former was revoked, i.e. marked to not propagate on upgrade.
11539                                // Note that in a permission review mode install permissions are
11540                                // represented as constantly granted runtime ones since we need to
11541                                // keep a per user state associated with the permission. Also the
11542                                // revoke on upgrade flag is no longer applicable and is reset.
11543                                final boolean revokeOnUpgrade = (flags & PackageManager
11544                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11545                                if (revokeOnUpgrade) {
11546                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11547                                    // Since we changed the flags, we have to write.
11548                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11549                                            changedRuntimePermissionUserIds, userId);
11550                                }
11551                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11552                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11553                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11554                                        // If we cannot put the permission as it was,
11555                                        // we have to write.
11556                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11557                                                changedRuntimePermissionUserIds, userId);
11558                                    }
11559                                }
11560
11561                                // If the app supports runtime permissions no need for a review.
11562                                if (mPermissionReviewRequired
11563                                        && appSupportsRuntimePermissions
11564                                        && (flags & PackageManager
11565                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11566                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11567                                    // Since we changed the flags, we have to write.
11568                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11569                                            changedRuntimePermissionUserIds, userId);
11570                                }
11571                            } else if (mPermissionReviewRequired
11572                                    && !appSupportsRuntimePermissions) {
11573                                // For legacy apps that need a permission review, every new
11574                                // runtime permission is granted but it is pending a review.
11575                                // We also need to review only platform defined runtime
11576                                // permissions as these are the only ones the platform knows
11577                                // how to disable the API to simulate revocation as legacy
11578                                // apps don't expect to run with revoked permissions.
11579                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11580                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11581                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11582                                        // We changed the flags, hence have to write.
11583                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11584                                                changedRuntimePermissionUserIds, userId);
11585                                    }
11586                                }
11587                                if (permissionsState.grantRuntimePermission(bp, userId)
11588                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11589                                    // We changed the permission, hence have to write.
11590                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11591                                            changedRuntimePermissionUserIds, userId);
11592                                }
11593                            }
11594                            // Propagate the permission flags.
11595                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11596                        }
11597                    } break;
11598
11599                    case GRANT_UPGRADE: {
11600                        // Grant runtime permissions for a previously held install permission.
11601                        PermissionState permissionState = origPermissions
11602                                .getInstallPermissionState(bp.name);
11603                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11604
11605                        if (origPermissions.revokeInstallPermission(bp)
11606                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11607                            // We will be transferring the permission flags, so clear them.
11608                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11609                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11610                            changedInstallPermission = true;
11611                        }
11612
11613                        // If the permission is not to be promoted to runtime we ignore it and
11614                        // also its other flags as they are not applicable to install permissions.
11615                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11616                            for (int userId : currentUserIds) {
11617                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11618                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11619                                    // Transfer the permission flags.
11620                                    permissionsState.updatePermissionFlags(bp, userId,
11621                                            flags, flags);
11622                                    // If we granted the permission, we have to write.
11623                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11624                                            changedRuntimePermissionUserIds, userId);
11625                                }
11626                            }
11627                        }
11628                    } break;
11629
11630                    default: {
11631                        if (packageOfInterest == null
11632                                || packageOfInterest.equals(pkg.packageName)) {
11633                            Slog.w(TAG, "Not granting permission " + perm
11634                                    + " to package " + pkg.packageName
11635                                    + " because it was previously installed without");
11636                        }
11637                    } break;
11638                }
11639            } else {
11640                if (permissionsState.revokeInstallPermission(bp) !=
11641                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11642                    // Also drop the permission flags.
11643                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11644                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11645                    changedInstallPermission = true;
11646                    Slog.i(TAG, "Un-granting permission " + perm
11647                            + " from package " + pkg.packageName
11648                            + " (protectionLevel=" + bp.protectionLevel
11649                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11650                            + ")");
11651                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11652                    // Don't print warning for app op permissions, since it is fine for them
11653                    // not to be granted, there is a UI for the user to decide.
11654                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11655                        Slog.w(TAG, "Not granting permission " + perm
11656                                + " to package " + pkg.packageName
11657                                + " (protectionLevel=" + bp.protectionLevel
11658                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11659                                + ")");
11660                    }
11661                }
11662            }
11663        }
11664
11665        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11666                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11667            // This is the first that we have heard about this package, so the
11668            // permissions we have now selected are fixed until explicitly
11669            // changed.
11670            ps.installPermissionsFixed = true;
11671        }
11672
11673        // Persist the runtime permissions state for users with changes. If permissions
11674        // were revoked because no app in the shared user declares them we have to
11675        // write synchronously to avoid losing runtime permissions state.
11676        for (int userId : changedRuntimePermissionUserIds) {
11677            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11678        }
11679    }
11680
11681    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11682        boolean allowed = false;
11683        final int NP = PackageParser.NEW_PERMISSIONS.length;
11684        for (int ip=0; ip<NP; ip++) {
11685            final PackageParser.NewPermissionInfo npi
11686                    = PackageParser.NEW_PERMISSIONS[ip];
11687            if (npi.name.equals(perm)
11688                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11689                allowed = true;
11690                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11691                        + pkg.packageName);
11692                break;
11693            }
11694        }
11695        return allowed;
11696    }
11697
11698    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11699            BasePermission bp, PermissionsState origPermissions) {
11700        boolean privilegedPermission = (bp.protectionLevel
11701                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11702        boolean privappPermissionsDisable =
11703                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11704        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11705        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11706        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11707                && !platformPackage && platformPermission) {
11708            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11709                    .getPrivAppPermissions(pkg.packageName);
11710            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11711            if (!whitelisted) {
11712                Slog.w(TAG, "Privileged permission " + perm + " for package "
11713                        + pkg.packageName + " - not in privapp-permissions whitelist");
11714                if (!mSystemReady) {
11715                    if (mPrivappPermissionsViolations == null) {
11716                        mPrivappPermissionsViolations = new ArraySet<>();
11717                    }
11718                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11719                }
11720                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11721                    return false;
11722                }
11723            }
11724        }
11725        boolean allowed = (compareSignatures(
11726                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11727                        == PackageManager.SIGNATURE_MATCH)
11728                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11729                        == PackageManager.SIGNATURE_MATCH);
11730        if (!allowed && privilegedPermission) {
11731            if (isSystemApp(pkg)) {
11732                // For updated system applications, a system permission
11733                // is granted only if it had been defined by the original application.
11734                if (pkg.isUpdatedSystemApp()) {
11735                    final PackageSetting sysPs = mSettings
11736                            .getDisabledSystemPkgLPr(pkg.packageName);
11737                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11738                        // If the original was granted this permission, we take
11739                        // that grant decision as read and propagate it to the
11740                        // update.
11741                        if (sysPs.isPrivileged()) {
11742                            allowed = true;
11743                        }
11744                    } else {
11745                        // The system apk may have been updated with an older
11746                        // version of the one on the data partition, but which
11747                        // granted a new system permission that it didn't have
11748                        // before.  In this case we do want to allow the app to
11749                        // now get the new permission if the ancestral apk is
11750                        // privileged to get it.
11751                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11752                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11753                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11754                                    allowed = true;
11755                                    break;
11756                                }
11757                            }
11758                        }
11759                        // Also if a privileged parent package on the system image or any of
11760                        // its children requested a privileged permission, the updated child
11761                        // packages can also get the permission.
11762                        if (pkg.parentPackage != null) {
11763                            final PackageSetting disabledSysParentPs = mSettings
11764                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11765                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11766                                    && disabledSysParentPs.isPrivileged()) {
11767                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11768                                    allowed = true;
11769                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11770                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11771                                    for (int i = 0; i < count; i++) {
11772                                        PackageParser.Package disabledSysChildPkg =
11773                                                disabledSysParentPs.pkg.childPackages.get(i);
11774                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11775                                                perm)) {
11776                                            allowed = true;
11777                                            break;
11778                                        }
11779                                    }
11780                                }
11781                            }
11782                        }
11783                    }
11784                } else {
11785                    allowed = isPrivilegedApp(pkg);
11786                }
11787            }
11788        }
11789        if (!allowed) {
11790            if (!allowed && (bp.protectionLevel
11791                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11792                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11793                // If this was a previously normal/dangerous permission that got moved
11794                // to a system permission as part of the runtime permission redesign, then
11795                // we still want to blindly grant it to old apps.
11796                allowed = true;
11797            }
11798            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11799                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11800                // If this permission is to be granted to the system installer and
11801                // this app is an installer, then it gets the permission.
11802                allowed = true;
11803            }
11804            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11805                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11806                // If this permission is to be granted to the system verifier and
11807                // this app is a verifier, then it gets the permission.
11808                allowed = true;
11809            }
11810            if (!allowed && (bp.protectionLevel
11811                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11812                    && isSystemApp(pkg)) {
11813                // Any pre-installed system app is allowed to get this permission.
11814                allowed = true;
11815            }
11816            if (!allowed && (bp.protectionLevel
11817                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11818                // For development permissions, a development permission
11819                // is granted only if it was already granted.
11820                allowed = origPermissions.hasInstallPermission(perm);
11821            }
11822            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11823                    && pkg.packageName.equals(mSetupWizardPackage)) {
11824                // If this permission is to be granted to the system setup wizard and
11825                // this app is a setup wizard, then it gets the permission.
11826                allowed = true;
11827            }
11828        }
11829        return allowed;
11830    }
11831
11832    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11833        final int permCount = pkg.requestedPermissions.size();
11834        for (int j = 0; j < permCount; j++) {
11835            String requestedPermission = pkg.requestedPermissions.get(j);
11836            if (permission.equals(requestedPermission)) {
11837                return true;
11838            }
11839        }
11840        return false;
11841    }
11842
11843    final class ActivityIntentResolver
11844            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11845        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11846                boolean defaultOnly, int userId) {
11847            if (!sUserManager.exists(userId)) return null;
11848            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11849            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11850        }
11851
11852        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11853                int userId) {
11854            if (!sUserManager.exists(userId)) return null;
11855            mFlags = flags;
11856            return super.queryIntent(intent, resolvedType,
11857                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11858                    userId);
11859        }
11860
11861        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11862                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11863            if (!sUserManager.exists(userId)) return null;
11864            if (packageActivities == null) {
11865                return null;
11866            }
11867            mFlags = flags;
11868            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11869            final int N = packageActivities.size();
11870            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11871                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11872
11873            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11874            for (int i = 0; i < N; ++i) {
11875                intentFilters = packageActivities.get(i).intents;
11876                if (intentFilters != null && intentFilters.size() > 0) {
11877                    PackageParser.ActivityIntentInfo[] array =
11878                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11879                    intentFilters.toArray(array);
11880                    listCut.add(array);
11881                }
11882            }
11883            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11884        }
11885
11886        /**
11887         * Finds a privileged activity that matches the specified activity names.
11888         */
11889        private PackageParser.Activity findMatchingActivity(
11890                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11891            for (PackageParser.Activity sysActivity : activityList) {
11892                if (sysActivity.info.name.equals(activityInfo.name)) {
11893                    return sysActivity;
11894                }
11895                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11896                    return sysActivity;
11897                }
11898                if (sysActivity.info.targetActivity != null) {
11899                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11900                        return sysActivity;
11901                    }
11902                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11903                        return sysActivity;
11904                    }
11905                }
11906            }
11907            return null;
11908        }
11909
11910        public class IterGenerator<E> {
11911            public Iterator<E> generate(ActivityIntentInfo info) {
11912                return null;
11913            }
11914        }
11915
11916        public class ActionIterGenerator extends IterGenerator<String> {
11917            @Override
11918            public Iterator<String> generate(ActivityIntentInfo info) {
11919                return info.actionsIterator();
11920            }
11921        }
11922
11923        public class CategoriesIterGenerator extends IterGenerator<String> {
11924            @Override
11925            public Iterator<String> generate(ActivityIntentInfo info) {
11926                return info.categoriesIterator();
11927            }
11928        }
11929
11930        public class SchemesIterGenerator extends IterGenerator<String> {
11931            @Override
11932            public Iterator<String> generate(ActivityIntentInfo info) {
11933                return info.schemesIterator();
11934            }
11935        }
11936
11937        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11938            @Override
11939            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11940                return info.authoritiesIterator();
11941            }
11942        }
11943
11944        /**
11945         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11946         * MODIFIED. Do not pass in a list that should not be changed.
11947         */
11948        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11949                IterGenerator<T> generator, Iterator<T> searchIterator) {
11950            // loop through the set of actions; every one must be found in the intent filter
11951            while (searchIterator.hasNext()) {
11952                // we must have at least one filter in the list to consider a match
11953                if (intentList.size() == 0) {
11954                    break;
11955                }
11956
11957                final T searchAction = searchIterator.next();
11958
11959                // loop through the set of intent filters
11960                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11961                while (intentIter.hasNext()) {
11962                    final ActivityIntentInfo intentInfo = intentIter.next();
11963                    boolean selectionFound = false;
11964
11965                    // loop through the intent filter's selection criteria; at least one
11966                    // of them must match the searched criteria
11967                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11968                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11969                        final T intentSelection = intentSelectionIter.next();
11970                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11971                            selectionFound = true;
11972                            break;
11973                        }
11974                    }
11975
11976                    // the selection criteria wasn't found in this filter's set; this filter
11977                    // is not a potential match
11978                    if (!selectionFound) {
11979                        intentIter.remove();
11980                    }
11981                }
11982            }
11983        }
11984
11985        private boolean isProtectedAction(ActivityIntentInfo filter) {
11986            final Iterator<String> actionsIter = filter.actionsIterator();
11987            while (actionsIter != null && actionsIter.hasNext()) {
11988                final String filterAction = actionsIter.next();
11989                if (PROTECTED_ACTIONS.contains(filterAction)) {
11990                    return true;
11991                }
11992            }
11993            return false;
11994        }
11995
11996        /**
11997         * Adjusts the priority of the given intent filter according to policy.
11998         * <p>
11999         * <ul>
12000         * <li>The priority for non privileged applications is capped to '0'</li>
12001         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12002         * <li>The priority for unbundled updates to privileged applications is capped to the
12003         *      priority defined on the system partition</li>
12004         * </ul>
12005         * <p>
12006         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12007         * allowed to obtain any priority on any action.
12008         */
12009        private void adjustPriority(
12010                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12011            // nothing to do; priority is fine as-is
12012            if (intent.getPriority() <= 0) {
12013                return;
12014            }
12015
12016            final ActivityInfo activityInfo = intent.activity.info;
12017            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12018
12019            final boolean privilegedApp =
12020                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12021            if (!privilegedApp) {
12022                // non-privileged applications can never define a priority >0
12023                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
12024                        + " package: " + applicationInfo.packageName
12025                        + " activity: " + intent.activity.className
12026                        + " origPrio: " + intent.getPriority());
12027                intent.setPriority(0);
12028                return;
12029            }
12030
12031            if (systemActivities == null) {
12032                // the system package is not disabled; we're parsing the system partition
12033                if (isProtectedAction(intent)) {
12034                    if (mDeferProtectedFilters) {
12035                        // We can't deal with these just yet. No component should ever obtain a
12036                        // >0 priority for a protected actions, with ONE exception -- the setup
12037                        // wizard. The setup wizard, however, cannot be known until we're able to
12038                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12039                        // until all intent filters have been processed. Chicken, meet egg.
12040                        // Let the filter temporarily have a high priority and rectify the
12041                        // priorities after all system packages have been scanned.
12042                        mProtectedFilters.add(intent);
12043                        if (DEBUG_FILTERS) {
12044                            Slog.i(TAG, "Protected action; save for later;"
12045                                    + " package: " + applicationInfo.packageName
12046                                    + " activity: " + intent.activity.className
12047                                    + " origPrio: " + intent.getPriority());
12048                        }
12049                        return;
12050                    } else {
12051                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12052                            Slog.i(TAG, "No setup wizard;"
12053                                + " All protected intents capped to priority 0");
12054                        }
12055                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12056                            if (DEBUG_FILTERS) {
12057                                Slog.i(TAG, "Found setup wizard;"
12058                                    + " allow priority " + intent.getPriority() + ";"
12059                                    + " package: " + intent.activity.info.packageName
12060                                    + " activity: " + intent.activity.className
12061                                    + " priority: " + intent.getPriority());
12062                            }
12063                            // setup wizard gets whatever it wants
12064                            return;
12065                        }
12066                        Slog.w(TAG, "Protected action; cap priority to 0;"
12067                                + " package: " + intent.activity.info.packageName
12068                                + " activity: " + intent.activity.className
12069                                + " origPrio: " + intent.getPriority());
12070                        intent.setPriority(0);
12071                        return;
12072                    }
12073                }
12074                // privileged apps on the system image get whatever priority they request
12075                return;
12076            }
12077
12078            // privileged app unbundled update ... try to find the same activity
12079            final PackageParser.Activity foundActivity =
12080                    findMatchingActivity(systemActivities, activityInfo);
12081            if (foundActivity == null) {
12082                // this is a new activity; it cannot obtain >0 priority
12083                if (DEBUG_FILTERS) {
12084                    Slog.i(TAG, "New activity; cap priority to 0;"
12085                            + " package: " + applicationInfo.packageName
12086                            + " activity: " + intent.activity.className
12087                            + " origPrio: " + intent.getPriority());
12088                }
12089                intent.setPriority(0);
12090                return;
12091            }
12092
12093            // found activity, now check for filter equivalence
12094
12095            // a shallow copy is enough; we modify the list, not its contents
12096            final List<ActivityIntentInfo> intentListCopy =
12097                    new ArrayList<>(foundActivity.intents);
12098            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12099
12100            // find matching action subsets
12101            final Iterator<String> actionsIterator = intent.actionsIterator();
12102            if (actionsIterator != null) {
12103                getIntentListSubset(
12104                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12105                if (intentListCopy.size() == 0) {
12106                    // no more intents to match; we're not equivalent
12107                    if (DEBUG_FILTERS) {
12108                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12109                                + " package: " + applicationInfo.packageName
12110                                + " activity: " + intent.activity.className
12111                                + " origPrio: " + intent.getPriority());
12112                    }
12113                    intent.setPriority(0);
12114                    return;
12115                }
12116            }
12117
12118            // find matching category subsets
12119            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12120            if (categoriesIterator != null) {
12121                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12122                        categoriesIterator);
12123                if (intentListCopy.size() == 0) {
12124                    // no more intents to match; we're not equivalent
12125                    if (DEBUG_FILTERS) {
12126                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12127                                + " package: " + applicationInfo.packageName
12128                                + " activity: " + intent.activity.className
12129                                + " origPrio: " + intent.getPriority());
12130                    }
12131                    intent.setPriority(0);
12132                    return;
12133                }
12134            }
12135
12136            // find matching schemes subsets
12137            final Iterator<String> schemesIterator = intent.schemesIterator();
12138            if (schemesIterator != null) {
12139                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12140                        schemesIterator);
12141                if (intentListCopy.size() == 0) {
12142                    // no more intents to match; we're not equivalent
12143                    if (DEBUG_FILTERS) {
12144                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12145                                + " package: " + applicationInfo.packageName
12146                                + " activity: " + intent.activity.className
12147                                + " origPrio: " + intent.getPriority());
12148                    }
12149                    intent.setPriority(0);
12150                    return;
12151                }
12152            }
12153
12154            // find matching authorities subsets
12155            final Iterator<IntentFilter.AuthorityEntry>
12156                    authoritiesIterator = intent.authoritiesIterator();
12157            if (authoritiesIterator != null) {
12158                getIntentListSubset(intentListCopy,
12159                        new AuthoritiesIterGenerator(),
12160                        authoritiesIterator);
12161                if (intentListCopy.size() == 0) {
12162                    // no more intents to match; we're not equivalent
12163                    if (DEBUG_FILTERS) {
12164                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12165                                + " package: " + applicationInfo.packageName
12166                                + " activity: " + intent.activity.className
12167                                + " origPrio: " + intent.getPriority());
12168                    }
12169                    intent.setPriority(0);
12170                    return;
12171                }
12172            }
12173
12174            // we found matching filter(s); app gets the max priority of all intents
12175            int cappedPriority = 0;
12176            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12177                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12178            }
12179            if (intent.getPriority() > cappedPriority) {
12180                if (DEBUG_FILTERS) {
12181                    Slog.i(TAG, "Found matching filter(s);"
12182                            + " cap priority to " + cappedPriority + ";"
12183                            + " package: " + applicationInfo.packageName
12184                            + " activity: " + intent.activity.className
12185                            + " origPrio: " + intent.getPriority());
12186                }
12187                intent.setPriority(cappedPriority);
12188                return;
12189            }
12190            // all this for nothing; the requested priority was <= what was on the system
12191        }
12192
12193        public final void addActivity(PackageParser.Activity a, String type) {
12194            mActivities.put(a.getComponentName(), a);
12195            if (DEBUG_SHOW_INFO)
12196                Log.v(
12197                TAG, "  " + type + " " +
12198                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12199            if (DEBUG_SHOW_INFO)
12200                Log.v(TAG, "    Class=" + a.info.name);
12201            final int NI = a.intents.size();
12202            for (int j=0; j<NI; j++) {
12203                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12204                if ("activity".equals(type)) {
12205                    final PackageSetting ps =
12206                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12207                    final List<PackageParser.Activity> systemActivities =
12208                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12209                    adjustPriority(systemActivities, intent);
12210                }
12211                if (DEBUG_SHOW_INFO) {
12212                    Log.v(TAG, "    IntentFilter:");
12213                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12214                }
12215                if (!intent.debugCheck()) {
12216                    Log.w(TAG, "==> For Activity " + a.info.name);
12217                }
12218                addFilter(intent);
12219            }
12220        }
12221
12222        public final void removeActivity(PackageParser.Activity a, String type) {
12223            mActivities.remove(a.getComponentName());
12224            if (DEBUG_SHOW_INFO) {
12225                Log.v(TAG, "  " + type + " "
12226                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12227                                : a.info.name) + ":");
12228                Log.v(TAG, "    Class=" + a.info.name);
12229            }
12230            final int NI = a.intents.size();
12231            for (int j=0; j<NI; j++) {
12232                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12233                if (DEBUG_SHOW_INFO) {
12234                    Log.v(TAG, "    IntentFilter:");
12235                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12236                }
12237                removeFilter(intent);
12238            }
12239        }
12240
12241        @Override
12242        protected boolean allowFilterResult(
12243                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12244            ActivityInfo filterAi = filter.activity.info;
12245            for (int i=dest.size()-1; i>=0; i--) {
12246                ActivityInfo destAi = dest.get(i).activityInfo;
12247                if (destAi.name == filterAi.name
12248                        && destAi.packageName == filterAi.packageName) {
12249                    return false;
12250                }
12251            }
12252            return true;
12253        }
12254
12255        @Override
12256        protected ActivityIntentInfo[] newArray(int size) {
12257            return new ActivityIntentInfo[size];
12258        }
12259
12260        @Override
12261        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12262            if (!sUserManager.exists(userId)) return true;
12263            PackageParser.Package p = filter.activity.owner;
12264            if (p != null) {
12265                PackageSetting ps = (PackageSetting)p.mExtras;
12266                if (ps != null) {
12267                    // System apps are never considered stopped for purposes of
12268                    // filtering, because there may be no way for the user to
12269                    // actually re-launch them.
12270                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12271                            && ps.getStopped(userId);
12272                }
12273            }
12274            return false;
12275        }
12276
12277        @Override
12278        protected boolean isPackageForFilter(String packageName,
12279                PackageParser.ActivityIntentInfo info) {
12280            return packageName.equals(info.activity.owner.packageName);
12281        }
12282
12283        @Override
12284        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12285                int match, int userId) {
12286            if (!sUserManager.exists(userId)) return null;
12287            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12288                return null;
12289            }
12290            final PackageParser.Activity activity = info.activity;
12291            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12292            if (ps == null) {
12293                return null;
12294            }
12295            final PackageUserState userState = ps.readUserState(userId);
12296            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12297                    userState, userId);
12298            if (ai == null) {
12299                return null;
12300            }
12301            final boolean matchVisibleToInstantApp =
12302                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12303            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12304            // throw out filters that aren't visible to ephemeral apps
12305            if (matchVisibleToInstantApp
12306                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12307                return null;
12308            }
12309            // throw out ephemeral filters if we're not explicitly requesting them
12310            if (!isInstantApp && userState.instantApp) {
12311                return null;
12312            }
12313            final ResolveInfo res = new ResolveInfo();
12314            res.activityInfo = ai;
12315            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12316                res.filter = info;
12317            }
12318            if (info != null) {
12319                res.handleAllWebDataURI = info.handleAllWebDataURI();
12320            }
12321            res.priority = info.getPriority();
12322            res.preferredOrder = activity.owner.mPreferredOrder;
12323            //System.out.println("Result: " + res.activityInfo.className +
12324            //                   " = " + res.priority);
12325            res.match = match;
12326            res.isDefault = info.hasDefault;
12327            res.labelRes = info.labelRes;
12328            res.nonLocalizedLabel = info.nonLocalizedLabel;
12329            if (userNeedsBadging(userId)) {
12330                res.noResourceId = true;
12331            } else {
12332                res.icon = info.icon;
12333            }
12334            res.iconResourceId = info.icon;
12335            res.system = res.activityInfo.applicationInfo.isSystemApp();
12336            return res;
12337        }
12338
12339        @Override
12340        protected void sortResults(List<ResolveInfo> results) {
12341            Collections.sort(results, mResolvePrioritySorter);
12342        }
12343
12344        @Override
12345        protected void dumpFilter(PrintWriter out, String prefix,
12346                PackageParser.ActivityIntentInfo filter) {
12347            out.print(prefix); out.print(
12348                    Integer.toHexString(System.identityHashCode(filter.activity)));
12349                    out.print(' ');
12350                    filter.activity.printComponentShortName(out);
12351                    out.print(" filter ");
12352                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12353        }
12354
12355        @Override
12356        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12357            return filter.activity;
12358        }
12359
12360        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12361            PackageParser.Activity activity = (PackageParser.Activity)label;
12362            out.print(prefix); out.print(
12363                    Integer.toHexString(System.identityHashCode(activity)));
12364                    out.print(' ');
12365                    activity.printComponentShortName(out);
12366            if (count > 1) {
12367                out.print(" ("); out.print(count); out.print(" filters)");
12368            }
12369            out.println();
12370        }
12371
12372        // Keys are String (activity class name), values are Activity.
12373        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12374                = new ArrayMap<ComponentName, PackageParser.Activity>();
12375        private int mFlags;
12376    }
12377
12378    private final class ServiceIntentResolver
12379            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12380        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12381                boolean defaultOnly, int userId) {
12382            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12383            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12384        }
12385
12386        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12387                int userId) {
12388            if (!sUserManager.exists(userId)) return null;
12389            mFlags = flags;
12390            return super.queryIntent(intent, resolvedType,
12391                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12392                    userId);
12393        }
12394
12395        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12396                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12397            if (!sUserManager.exists(userId)) return null;
12398            if (packageServices == null) {
12399                return null;
12400            }
12401            mFlags = flags;
12402            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12403            final int N = packageServices.size();
12404            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12405                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12406
12407            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12408            for (int i = 0; i < N; ++i) {
12409                intentFilters = packageServices.get(i).intents;
12410                if (intentFilters != null && intentFilters.size() > 0) {
12411                    PackageParser.ServiceIntentInfo[] array =
12412                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12413                    intentFilters.toArray(array);
12414                    listCut.add(array);
12415                }
12416            }
12417            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12418        }
12419
12420        public final void addService(PackageParser.Service s) {
12421            mServices.put(s.getComponentName(), s);
12422            if (DEBUG_SHOW_INFO) {
12423                Log.v(TAG, "  "
12424                        + (s.info.nonLocalizedLabel != null
12425                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12426                Log.v(TAG, "    Class=" + s.info.name);
12427            }
12428            final int NI = s.intents.size();
12429            int j;
12430            for (j=0; j<NI; j++) {
12431                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12432                if (DEBUG_SHOW_INFO) {
12433                    Log.v(TAG, "    IntentFilter:");
12434                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12435                }
12436                if (!intent.debugCheck()) {
12437                    Log.w(TAG, "==> For Service " + s.info.name);
12438                }
12439                addFilter(intent);
12440            }
12441        }
12442
12443        public final void removeService(PackageParser.Service s) {
12444            mServices.remove(s.getComponentName());
12445            if (DEBUG_SHOW_INFO) {
12446                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12447                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12448                Log.v(TAG, "    Class=" + s.info.name);
12449            }
12450            final int NI = s.intents.size();
12451            int j;
12452            for (j=0; j<NI; j++) {
12453                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12454                if (DEBUG_SHOW_INFO) {
12455                    Log.v(TAG, "    IntentFilter:");
12456                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12457                }
12458                removeFilter(intent);
12459            }
12460        }
12461
12462        @Override
12463        protected boolean allowFilterResult(
12464                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12465            ServiceInfo filterSi = filter.service.info;
12466            for (int i=dest.size()-1; i>=0; i--) {
12467                ServiceInfo destAi = dest.get(i).serviceInfo;
12468                if (destAi.name == filterSi.name
12469                        && destAi.packageName == filterSi.packageName) {
12470                    return false;
12471                }
12472            }
12473            return true;
12474        }
12475
12476        @Override
12477        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12478            return new PackageParser.ServiceIntentInfo[size];
12479        }
12480
12481        @Override
12482        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12483            if (!sUserManager.exists(userId)) return true;
12484            PackageParser.Package p = filter.service.owner;
12485            if (p != null) {
12486                PackageSetting ps = (PackageSetting)p.mExtras;
12487                if (ps != null) {
12488                    // System apps are never considered stopped for purposes of
12489                    // filtering, because there may be no way for the user to
12490                    // actually re-launch them.
12491                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12492                            && ps.getStopped(userId);
12493                }
12494            }
12495            return false;
12496        }
12497
12498        @Override
12499        protected boolean isPackageForFilter(String packageName,
12500                PackageParser.ServiceIntentInfo info) {
12501            return packageName.equals(info.service.owner.packageName);
12502        }
12503
12504        @Override
12505        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12506                int match, int userId) {
12507            if (!sUserManager.exists(userId)) return null;
12508            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12509            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12510                return null;
12511            }
12512            final PackageParser.Service service = info.service;
12513            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12514            if (ps == null) {
12515                return null;
12516            }
12517            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12518                    ps.readUserState(userId), userId);
12519            if (si == null) {
12520                return null;
12521            }
12522            final ResolveInfo res = new ResolveInfo();
12523            res.serviceInfo = si;
12524            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12525                res.filter = filter;
12526            }
12527            res.priority = info.getPriority();
12528            res.preferredOrder = service.owner.mPreferredOrder;
12529            res.match = match;
12530            res.isDefault = info.hasDefault;
12531            res.labelRes = info.labelRes;
12532            res.nonLocalizedLabel = info.nonLocalizedLabel;
12533            res.icon = info.icon;
12534            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12535            return res;
12536        }
12537
12538        @Override
12539        protected void sortResults(List<ResolveInfo> results) {
12540            Collections.sort(results, mResolvePrioritySorter);
12541        }
12542
12543        @Override
12544        protected void dumpFilter(PrintWriter out, String prefix,
12545                PackageParser.ServiceIntentInfo filter) {
12546            out.print(prefix); out.print(
12547                    Integer.toHexString(System.identityHashCode(filter.service)));
12548                    out.print(' ');
12549                    filter.service.printComponentShortName(out);
12550                    out.print(" filter ");
12551                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12552        }
12553
12554        @Override
12555        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12556            return filter.service;
12557        }
12558
12559        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12560            PackageParser.Service service = (PackageParser.Service)label;
12561            out.print(prefix); out.print(
12562                    Integer.toHexString(System.identityHashCode(service)));
12563                    out.print(' ');
12564                    service.printComponentShortName(out);
12565            if (count > 1) {
12566                out.print(" ("); out.print(count); out.print(" filters)");
12567            }
12568            out.println();
12569        }
12570
12571//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12572//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12573//            final List<ResolveInfo> retList = Lists.newArrayList();
12574//            while (i.hasNext()) {
12575//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12576//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12577//                    retList.add(resolveInfo);
12578//                }
12579//            }
12580//            return retList;
12581//        }
12582
12583        // Keys are String (activity class name), values are Activity.
12584        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12585                = new ArrayMap<ComponentName, PackageParser.Service>();
12586        private int mFlags;
12587    }
12588
12589    private final class ProviderIntentResolver
12590            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12591        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12592                boolean defaultOnly, int userId) {
12593            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12594            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12595        }
12596
12597        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12598                int userId) {
12599            if (!sUserManager.exists(userId))
12600                return null;
12601            mFlags = flags;
12602            return super.queryIntent(intent, resolvedType,
12603                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12604                    userId);
12605        }
12606
12607        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12608                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12609            if (!sUserManager.exists(userId))
12610                return null;
12611            if (packageProviders == null) {
12612                return null;
12613            }
12614            mFlags = flags;
12615            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12616            final int N = packageProviders.size();
12617            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12618                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12619
12620            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12621            for (int i = 0; i < N; ++i) {
12622                intentFilters = packageProviders.get(i).intents;
12623                if (intentFilters != null && intentFilters.size() > 0) {
12624                    PackageParser.ProviderIntentInfo[] array =
12625                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12626                    intentFilters.toArray(array);
12627                    listCut.add(array);
12628                }
12629            }
12630            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12631        }
12632
12633        public final void addProvider(PackageParser.Provider p) {
12634            if (mProviders.containsKey(p.getComponentName())) {
12635                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12636                return;
12637            }
12638
12639            mProviders.put(p.getComponentName(), p);
12640            if (DEBUG_SHOW_INFO) {
12641                Log.v(TAG, "  "
12642                        + (p.info.nonLocalizedLabel != null
12643                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12644                Log.v(TAG, "    Class=" + p.info.name);
12645            }
12646            final int NI = p.intents.size();
12647            int j;
12648            for (j = 0; j < NI; j++) {
12649                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12650                if (DEBUG_SHOW_INFO) {
12651                    Log.v(TAG, "    IntentFilter:");
12652                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12653                }
12654                if (!intent.debugCheck()) {
12655                    Log.w(TAG, "==> For Provider " + p.info.name);
12656                }
12657                addFilter(intent);
12658            }
12659        }
12660
12661        public final void removeProvider(PackageParser.Provider p) {
12662            mProviders.remove(p.getComponentName());
12663            if (DEBUG_SHOW_INFO) {
12664                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12665                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12666                Log.v(TAG, "    Class=" + p.info.name);
12667            }
12668            final int NI = p.intents.size();
12669            int j;
12670            for (j = 0; j < NI; j++) {
12671                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12672                if (DEBUG_SHOW_INFO) {
12673                    Log.v(TAG, "    IntentFilter:");
12674                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12675                }
12676                removeFilter(intent);
12677            }
12678        }
12679
12680        @Override
12681        protected boolean allowFilterResult(
12682                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12683            ProviderInfo filterPi = filter.provider.info;
12684            for (int i = dest.size() - 1; i >= 0; i--) {
12685                ProviderInfo destPi = dest.get(i).providerInfo;
12686                if (destPi.name == filterPi.name
12687                        && destPi.packageName == filterPi.packageName) {
12688                    return false;
12689                }
12690            }
12691            return true;
12692        }
12693
12694        @Override
12695        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12696            return new PackageParser.ProviderIntentInfo[size];
12697        }
12698
12699        @Override
12700        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12701            if (!sUserManager.exists(userId))
12702                return true;
12703            PackageParser.Package p = filter.provider.owner;
12704            if (p != null) {
12705                PackageSetting ps = (PackageSetting) p.mExtras;
12706                if (ps != null) {
12707                    // System apps are never considered stopped for purposes of
12708                    // filtering, because there may be no way for the user to
12709                    // actually re-launch them.
12710                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12711                            && ps.getStopped(userId);
12712                }
12713            }
12714            return false;
12715        }
12716
12717        @Override
12718        protected boolean isPackageForFilter(String packageName,
12719                PackageParser.ProviderIntentInfo info) {
12720            return packageName.equals(info.provider.owner.packageName);
12721        }
12722
12723        @Override
12724        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12725                int match, int userId) {
12726            if (!sUserManager.exists(userId))
12727                return null;
12728            final PackageParser.ProviderIntentInfo info = filter;
12729            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12730                return null;
12731            }
12732            final PackageParser.Provider provider = info.provider;
12733            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12734            if (ps == null) {
12735                return null;
12736            }
12737            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12738                    ps.readUserState(userId), userId);
12739            if (pi == null) {
12740                return null;
12741            }
12742            final ResolveInfo res = new ResolveInfo();
12743            res.providerInfo = pi;
12744            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12745                res.filter = filter;
12746            }
12747            res.priority = info.getPriority();
12748            res.preferredOrder = provider.owner.mPreferredOrder;
12749            res.match = match;
12750            res.isDefault = info.hasDefault;
12751            res.labelRes = info.labelRes;
12752            res.nonLocalizedLabel = info.nonLocalizedLabel;
12753            res.icon = info.icon;
12754            res.system = res.providerInfo.applicationInfo.isSystemApp();
12755            return res;
12756        }
12757
12758        @Override
12759        protected void sortResults(List<ResolveInfo> results) {
12760            Collections.sort(results, mResolvePrioritySorter);
12761        }
12762
12763        @Override
12764        protected void dumpFilter(PrintWriter out, String prefix,
12765                PackageParser.ProviderIntentInfo filter) {
12766            out.print(prefix);
12767            out.print(
12768                    Integer.toHexString(System.identityHashCode(filter.provider)));
12769            out.print(' ');
12770            filter.provider.printComponentShortName(out);
12771            out.print(" filter ");
12772            out.println(Integer.toHexString(System.identityHashCode(filter)));
12773        }
12774
12775        @Override
12776        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12777            return filter.provider;
12778        }
12779
12780        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12781            PackageParser.Provider provider = (PackageParser.Provider)label;
12782            out.print(prefix); out.print(
12783                    Integer.toHexString(System.identityHashCode(provider)));
12784                    out.print(' ');
12785                    provider.printComponentShortName(out);
12786            if (count > 1) {
12787                out.print(" ("); out.print(count); out.print(" filters)");
12788            }
12789            out.println();
12790        }
12791
12792        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12793                = new ArrayMap<ComponentName, PackageParser.Provider>();
12794        private int mFlags;
12795    }
12796
12797    static final class EphemeralIntentResolver
12798            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12799        /**
12800         * The result that has the highest defined order. Ordering applies on a
12801         * per-package basis. Mapping is from package name to Pair of order and
12802         * EphemeralResolveInfo.
12803         * <p>
12804         * NOTE: This is implemented as a field variable for convenience and efficiency.
12805         * By having a field variable, we're able to track filter ordering as soon as
12806         * a non-zero order is defined. Otherwise, multiple loops across the result set
12807         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12808         * this needs to be contained entirely within {@link #filterResults()}.
12809         */
12810        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
12811
12812        @Override
12813        protected AuxiliaryResolveInfo[] newArray(int size) {
12814            return new AuxiliaryResolveInfo[size];
12815        }
12816
12817        @Override
12818        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12819            return true;
12820        }
12821
12822        @Override
12823        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12824                int userId) {
12825            if (!sUserManager.exists(userId)) {
12826                return null;
12827            }
12828            final String packageName = responseObj.resolveInfo.getPackageName();
12829            final Integer order = responseObj.getOrder();
12830            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
12831                    mOrderResult.get(packageName);
12832            // ordering is enabled and this item's order isn't high enough
12833            if (lastOrderResult != null && lastOrderResult.first >= order) {
12834                return null;
12835            }
12836            final EphemeralResolveInfo res = responseObj.resolveInfo;
12837            if (order > 0) {
12838                // non-zero order, enable ordering
12839                mOrderResult.put(packageName, new Pair<>(order, res));
12840            }
12841            return responseObj;
12842        }
12843
12844        @Override
12845        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12846            // only do work if ordering is enabled [most of the time it won't be]
12847            if (mOrderResult.size() == 0) {
12848                return;
12849            }
12850            int resultSize = results.size();
12851            for (int i = 0; i < resultSize; i++) {
12852                final EphemeralResolveInfo info = results.get(i).resolveInfo;
12853                final String packageName = info.getPackageName();
12854                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
12855                if (savedInfo == null) {
12856                    // package doesn't having ordering
12857                    continue;
12858                }
12859                if (savedInfo.second == info) {
12860                    // circled back to the highest ordered item; remove from order list
12861                    mOrderResult.remove(savedInfo);
12862                    if (mOrderResult.size() == 0) {
12863                        // no more ordered items
12864                        break;
12865                    }
12866                    continue;
12867                }
12868                // item has a worse order, remove it from the result list
12869                results.remove(i);
12870                resultSize--;
12871                i--;
12872            }
12873        }
12874    }
12875
12876    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12877            new Comparator<ResolveInfo>() {
12878        public int compare(ResolveInfo r1, ResolveInfo r2) {
12879            int v1 = r1.priority;
12880            int v2 = r2.priority;
12881            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12882            if (v1 != v2) {
12883                return (v1 > v2) ? -1 : 1;
12884            }
12885            v1 = r1.preferredOrder;
12886            v2 = r2.preferredOrder;
12887            if (v1 != v2) {
12888                return (v1 > v2) ? -1 : 1;
12889            }
12890            if (r1.isDefault != r2.isDefault) {
12891                return r1.isDefault ? -1 : 1;
12892            }
12893            v1 = r1.match;
12894            v2 = r2.match;
12895            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12896            if (v1 != v2) {
12897                return (v1 > v2) ? -1 : 1;
12898            }
12899            if (r1.system != r2.system) {
12900                return r1.system ? -1 : 1;
12901            }
12902            if (r1.activityInfo != null) {
12903                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12904            }
12905            if (r1.serviceInfo != null) {
12906                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12907            }
12908            if (r1.providerInfo != null) {
12909                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12910            }
12911            return 0;
12912        }
12913    };
12914
12915    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12916            new Comparator<ProviderInfo>() {
12917        public int compare(ProviderInfo p1, ProviderInfo p2) {
12918            final int v1 = p1.initOrder;
12919            final int v2 = p2.initOrder;
12920            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12921        }
12922    };
12923
12924    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12925            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12926            final int[] userIds) {
12927        mHandler.post(new Runnable() {
12928            @Override
12929            public void run() {
12930                try {
12931                    final IActivityManager am = ActivityManager.getService();
12932                    if (am == null) return;
12933                    final int[] resolvedUserIds;
12934                    if (userIds == null) {
12935                        resolvedUserIds = am.getRunningUserIds();
12936                    } else {
12937                        resolvedUserIds = userIds;
12938                    }
12939                    for (int id : resolvedUserIds) {
12940                        final Intent intent = new Intent(action,
12941                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12942                        if (extras != null) {
12943                            intent.putExtras(extras);
12944                        }
12945                        if (targetPkg != null) {
12946                            intent.setPackage(targetPkg);
12947                        }
12948                        // Modify the UID when posting to other users
12949                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12950                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12951                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12952                            intent.putExtra(Intent.EXTRA_UID, uid);
12953                        }
12954                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12955                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12956                        if (DEBUG_BROADCASTS) {
12957                            RuntimeException here = new RuntimeException("here");
12958                            here.fillInStackTrace();
12959                            Slog.d(TAG, "Sending to user " + id + ": "
12960                                    + intent.toShortString(false, true, false, false)
12961                                    + " " + intent.getExtras(), here);
12962                        }
12963                        am.broadcastIntent(null, intent, null, finishedReceiver,
12964                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12965                                null, finishedReceiver != null, false, id);
12966                    }
12967                } catch (RemoteException ex) {
12968                }
12969            }
12970        });
12971    }
12972
12973    /**
12974     * Check if the external storage media is available. This is true if there
12975     * is a mounted external storage medium or if the external storage is
12976     * emulated.
12977     */
12978    private boolean isExternalMediaAvailable() {
12979        return mMediaMounted || Environment.isExternalStorageEmulated();
12980    }
12981
12982    @Override
12983    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12984        // writer
12985        synchronized (mPackages) {
12986            if (!isExternalMediaAvailable()) {
12987                // If the external storage is no longer mounted at this point,
12988                // the caller may not have been able to delete all of this
12989                // packages files and can not delete any more.  Bail.
12990                return null;
12991            }
12992            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12993            if (lastPackage != null) {
12994                pkgs.remove(lastPackage);
12995            }
12996            if (pkgs.size() > 0) {
12997                return pkgs.get(0);
12998            }
12999        }
13000        return null;
13001    }
13002
13003    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13004        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13005                userId, andCode ? 1 : 0, packageName);
13006        if (mSystemReady) {
13007            msg.sendToTarget();
13008        } else {
13009            if (mPostSystemReadyMessages == null) {
13010                mPostSystemReadyMessages = new ArrayList<>();
13011            }
13012            mPostSystemReadyMessages.add(msg);
13013        }
13014    }
13015
13016    void startCleaningPackages() {
13017        // reader
13018        if (!isExternalMediaAvailable()) {
13019            return;
13020        }
13021        synchronized (mPackages) {
13022            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13023                return;
13024            }
13025        }
13026        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13027        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13028        IActivityManager am = ActivityManager.getService();
13029        if (am != null) {
13030            try {
13031                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
13032                        UserHandle.USER_SYSTEM);
13033            } catch (RemoteException e) {
13034            }
13035        }
13036    }
13037
13038    @Override
13039    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13040            int installFlags, String installerPackageName, int userId) {
13041        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13042
13043        final int callingUid = Binder.getCallingUid();
13044        enforceCrossUserPermission(callingUid, userId,
13045                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13046
13047        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13048            try {
13049                if (observer != null) {
13050                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13051                }
13052            } catch (RemoteException re) {
13053            }
13054            return;
13055        }
13056
13057        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13058            installFlags |= PackageManager.INSTALL_FROM_ADB;
13059
13060        } else {
13061            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13062            // about installerPackageName.
13063
13064            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13065            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13066        }
13067
13068        UserHandle user;
13069        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13070            user = UserHandle.ALL;
13071        } else {
13072            user = new UserHandle(userId);
13073        }
13074
13075        // Only system components can circumvent runtime permissions when installing.
13076        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13077                && mContext.checkCallingOrSelfPermission(Manifest.permission
13078                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13079            throw new SecurityException("You need the "
13080                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13081                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13082        }
13083
13084        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13085                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13086            throw new IllegalArgumentException(
13087                    "New installs into ASEC containers no longer supported");
13088        }
13089
13090        final File originFile = new File(originPath);
13091        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13092
13093        final Message msg = mHandler.obtainMessage(INIT_COPY);
13094        final VerificationInfo verificationInfo = new VerificationInfo(
13095                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13096        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13097                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13098                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13099                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13100        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13101        msg.obj = params;
13102
13103        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13104                System.identityHashCode(msg.obj));
13105        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13106                System.identityHashCode(msg.obj));
13107
13108        mHandler.sendMessage(msg);
13109    }
13110
13111
13112    /**
13113     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13114     * it is acting on behalf on an enterprise or the user).
13115     *
13116     * Note that the ordering of the conditionals in this method is important. The checks we perform
13117     * are as follows, in this order:
13118     *
13119     * 1) If the install is being performed by a system app, we can trust the app to have set the
13120     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13121     *    what it is.
13122     * 2) If the install is being performed by a device or profile owner app, the install reason
13123     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13124     *    set the install reason correctly. If the app targets an older SDK version where install
13125     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13126     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13127     * 3) In all other cases, the install is being performed by a regular app that is neither part
13128     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13129     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13130     *    set to enterprise policy and if so, change it to unknown instead.
13131     */
13132    private int fixUpInstallReason(String installerPackageName, int installerUid,
13133            int installReason) {
13134        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13135                == PERMISSION_GRANTED) {
13136            // If the install is being performed by a system app, we trust that app to have set the
13137            // install reason correctly.
13138            return installReason;
13139        }
13140
13141        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13142            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13143        if (dpm != null) {
13144            ComponentName owner = null;
13145            try {
13146                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13147                if (owner == null) {
13148                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13149                }
13150            } catch (RemoteException e) {
13151            }
13152            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13153                // If the install is being performed by a device or profile owner, the install
13154                // reason should be enterprise policy.
13155                return PackageManager.INSTALL_REASON_POLICY;
13156            }
13157        }
13158
13159        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13160            // If the install is being performed by a regular app (i.e. neither system app nor
13161            // device or profile owner), we have no reason to believe that the app is acting on
13162            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13163            // change it to unknown instead.
13164            return PackageManager.INSTALL_REASON_UNKNOWN;
13165        }
13166
13167        // If the install is being performed by a regular app and the install reason was set to any
13168        // value but enterprise policy, leave the install reason unchanged.
13169        return installReason;
13170    }
13171
13172    void installStage(String packageName, File stagedDir, String stagedCid,
13173            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13174            String installerPackageName, int installerUid, UserHandle user,
13175            Certificate[][] certificates) {
13176        if (DEBUG_EPHEMERAL) {
13177            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13178                Slog.d(TAG, "Ephemeral install of " + packageName);
13179            }
13180        }
13181        final VerificationInfo verificationInfo = new VerificationInfo(
13182                sessionParams.originatingUri, sessionParams.referrerUri,
13183                sessionParams.originatingUid, installerUid);
13184
13185        final OriginInfo origin;
13186        if (stagedDir != null) {
13187            origin = OriginInfo.fromStagedFile(stagedDir);
13188        } else {
13189            origin = OriginInfo.fromStagedContainer(stagedCid);
13190        }
13191
13192        final Message msg = mHandler.obtainMessage(INIT_COPY);
13193        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13194                sessionParams.installReason);
13195        final InstallParams params = new InstallParams(origin, null, observer,
13196                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13197                verificationInfo, user, sessionParams.abiOverride,
13198                sessionParams.grantedRuntimePermissions, certificates, installReason);
13199        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13200        msg.obj = params;
13201
13202        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13203                System.identityHashCode(msg.obj));
13204        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13205                System.identityHashCode(msg.obj));
13206
13207        mHandler.sendMessage(msg);
13208    }
13209
13210    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13211            int userId) {
13212        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13213        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13214    }
13215
13216    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13217            int appId, int... userIds) {
13218        if (ArrayUtils.isEmpty(userIds)) {
13219            return;
13220        }
13221        Bundle extras = new Bundle(1);
13222        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13223        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13224
13225        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13226                packageName, extras, 0, null, null, userIds);
13227        if (isSystem) {
13228            mHandler.post(() -> {
13229                        for (int userId : userIds) {
13230                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13231                        }
13232                    }
13233            );
13234        }
13235    }
13236
13237    /**
13238     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13239     * automatically without needing an explicit launch.
13240     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13241     */
13242    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13243        // If user is not running, the app didn't miss any broadcast
13244        if (!mUserManagerInternal.isUserRunning(userId)) {
13245            return;
13246        }
13247        final IActivityManager am = ActivityManager.getService();
13248        try {
13249            // Deliver LOCKED_BOOT_COMPLETED first
13250            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13251                    .setPackage(packageName);
13252            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13253            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13254                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13255
13256            // Deliver BOOT_COMPLETED only if user is unlocked
13257            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13258                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13259                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13260                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13261            }
13262        } catch (RemoteException e) {
13263            throw e.rethrowFromSystemServer();
13264        }
13265    }
13266
13267    @Override
13268    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13269            int userId) {
13270        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13271        PackageSetting pkgSetting;
13272        final int uid = Binder.getCallingUid();
13273        enforceCrossUserPermission(uid, userId,
13274                true /* requireFullPermission */, true /* checkShell */,
13275                "setApplicationHiddenSetting for user " + userId);
13276
13277        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13278            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13279            return false;
13280        }
13281
13282        long callingId = Binder.clearCallingIdentity();
13283        try {
13284            boolean sendAdded = false;
13285            boolean sendRemoved = false;
13286            // writer
13287            synchronized (mPackages) {
13288                pkgSetting = mSettings.mPackages.get(packageName);
13289                if (pkgSetting == null) {
13290                    return false;
13291                }
13292                // Do not allow "android" is being disabled
13293                if ("android".equals(packageName)) {
13294                    Slog.w(TAG, "Cannot hide package: android");
13295                    return false;
13296                }
13297                // Cannot hide static shared libs as they are considered
13298                // a part of the using app (emulating static linking). Also
13299                // static libs are installed always on internal storage.
13300                PackageParser.Package pkg = mPackages.get(packageName);
13301                if (pkg != null && pkg.staticSharedLibName != null) {
13302                    Slog.w(TAG, "Cannot hide package: " + packageName
13303                            + " providing static shared library: "
13304                            + pkg.staticSharedLibName);
13305                    return false;
13306                }
13307                // Only allow protected packages to hide themselves.
13308                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13309                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13310                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13311                    return false;
13312                }
13313
13314                if (pkgSetting.getHidden(userId) != hidden) {
13315                    pkgSetting.setHidden(hidden, userId);
13316                    mSettings.writePackageRestrictionsLPr(userId);
13317                    if (hidden) {
13318                        sendRemoved = true;
13319                    } else {
13320                        sendAdded = true;
13321                    }
13322                }
13323            }
13324            if (sendAdded) {
13325                sendPackageAddedForUser(packageName, pkgSetting, userId);
13326                return true;
13327            }
13328            if (sendRemoved) {
13329                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13330                        "hiding pkg");
13331                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13332                return true;
13333            }
13334        } finally {
13335            Binder.restoreCallingIdentity(callingId);
13336        }
13337        return false;
13338    }
13339
13340    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13341            int userId) {
13342        final PackageRemovedInfo info = new PackageRemovedInfo();
13343        info.removedPackage = packageName;
13344        info.removedUsers = new int[] {userId};
13345        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13346        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13347    }
13348
13349    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13350        if (pkgList.length > 0) {
13351            Bundle extras = new Bundle(1);
13352            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13353
13354            sendPackageBroadcast(
13355                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13356                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13357                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13358                    new int[] {userId});
13359        }
13360    }
13361
13362    /**
13363     * Returns true if application is not found or there was an error. Otherwise it returns
13364     * the hidden state of the package for the given user.
13365     */
13366    @Override
13367    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13368        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13369        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13370                true /* requireFullPermission */, false /* checkShell */,
13371                "getApplicationHidden for user " + userId);
13372        PackageSetting pkgSetting;
13373        long callingId = Binder.clearCallingIdentity();
13374        try {
13375            // writer
13376            synchronized (mPackages) {
13377                pkgSetting = mSettings.mPackages.get(packageName);
13378                if (pkgSetting == null) {
13379                    return true;
13380                }
13381                return pkgSetting.getHidden(userId);
13382            }
13383        } finally {
13384            Binder.restoreCallingIdentity(callingId);
13385        }
13386    }
13387
13388    /**
13389     * @hide
13390     */
13391    @Override
13392    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13393            int installReason) {
13394        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13395                null);
13396        PackageSetting pkgSetting;
13397        final int uid = Binder.getCallingUid();
13398        enforceCrossUserPermission(uid, userId,
13399                true /* requireFullPermission */, true /* checkShell */,
13400                "installExistingPackage for user " + userId);
13401        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13402            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13403        }
13404
13405        long callingId = Binder.clearCallingIdentity();
13406        try {
13407            boolean installed = false;
13408            final boolean instantApp =
13409                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13410            final boolean fullApp =
13411                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13412
13413            // writer
13414            synchronized (mPackages) {
13415                pkgSetting = mSettings.mPackages.get(packageName);
13416                if (pkgSetting == null) {
13417                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13418                }
13419                if (!pkgSetting.getInstalled(userId)) {
13420                    pkgSetting.setInstalled(true, userId);
13421                    pkgSetting.setHidden(false, userId);
13422                    pkgSetting.setInstallReason(installReason, userId);
13423                    mSettings.writePackageRestrictionsLPr(userId);
13424                    mSettings.writeKernelMappingLPr(pkgSetting);
13425                    installed = true;
13426                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13427                    // upgrade app from instant to full; we don't allow app downgrade
13428                    installed = true;
13429                }
13430                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13431            }
13432
13433            if (installed) {
13434                if (pkgSetting.pkg != null) {
13435                    synchronized (mInstallLock) {
13436                        // We don't need to freeze for a brand new install
13437                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13438                    }
13439                }
13440                sendPackageAddedForUser(packageName, pkgSetting, userId);
13441                synchronized (mPackages) {
13442                    updateSequenceNumberLP(packageName, new int[]{ userId });
13443                }
13444            }
13445        } finally {
13446            Binder.restoreCallingIdentity(callingId);
13447        }
13448
13449        return PackageManager.INSTALL_SUCCEEDED;
13450    }
13451
13452    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13453            boolean instantApp, boolean fullApp) {
13454        // no state specified; do nothing
13455        if (!instantApp && !fullApp) {
13456            return;
13457        }
13458        if (userId != UserHandle.USER_ALL) {
13459            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13460                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13461            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13462                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13463            }
13464        } else {
13465            for (int currentUserId : sUserManager.getUserIds()) {
13466                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13467                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13468                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13469                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13470                }
13471            }
13472        }
13473    }
13474
13475    boolean isUserRestricted(int userId, String restrictionKey) {
13476        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13477        if (restrictions.getBoolean(restrictionKey, false)) {
13478            Log.w(TAG, "User is restricted: " + restrictionKey);
13479            return true;
13480        }
13481        return false;
13482    }
13483
13484    @Override
13485    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13486            int userId) {
13487        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13488        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13489                true /* requireFullPermission */, true /* checkShell */,
13490                "setPackagesSuspended for user " + userId);
13491
13492        if (ArrayUtils.isEmpty(packageNames)) {
13493            return packageNames;
13494        }
13495
13496        // List of package names for whom the suspended state has changed.
13497        List<String> changedPackages = new ArrayList<>(packageNames.length);
13498        // List of package names for whom the suspended state is not set as requested in this
13499        // method.
13500        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13501        long callingId = Binder.clearCallingIdentity();
13502        try {
13503            for (int i = 0; i < packageNames.length; i++) {
13504                String packageName = packageNames[i];
13505                boolean changed = false;
13506                final int appId;
13507                synchronized (mPackages) {
13508                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13509                    if (pkgSetting == null) {
13510                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13511                                + "\". Skipping suspending/un-suspending.");
13512                        unactionedPackages.add(packageName);
13513                        continue;
13514                    }
13515                    appId = pkgSetting.appId;
13516                    if (pkgSetting.getSuspended(userId) != suspended) {
13517                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13518                            unactionedPackages.add(packageName);
13519                            continue;
13520                        }
13521                        pkgSetting.setSuspended(suspended, userId);
13522                        mSettings.writePackageRestrictionsLPr(userId);
13523                        changed = true;
13524                        changedPackages.add(packageName);
13525                    }
13526                }
13527
13528                if (changed && suspended) {
13529                    killApplication(packageName, UserHandle.getUid(userId, appId),
13530                            "suspending package");
13531                }
13532            }
13533        } finally {
13534            Binder.restoreCallingIdentity(callingId);
13535        }
13536
13537        if (!changedPackages.isEmpty()) {
13538            sendPackagesSuspendedForUser(changedPackages.toArray(
13539                    new String[changedPackages.size()]), userId, suspended);
13540        }
13541
13542        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13543    }
13544
13545    @Override
13546    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13547        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13548                true /* requireFullPermission */, false /* checkShell */,
13549                "isPackageSuspendedForUser for user " + userId);
13550        synchronized (mPackages) {
13551            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13552            if (pkgSetting == null) {
13553                throw new IllegalArgumentException("Unknown target package: " + packageName);
13554            }
13555            return pkgSetting.getSuspended(userId);
13556        }
13557    }
13558
13559    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13560        if (isPackageDeviceAdmin(packageName, userId)) {
13561            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13562                    + "\": has an active device admin");
13563            return false;
13564        }
13565
13566        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13567        if (packageName.equals(activeLauncherPackageName)) {
13568            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13569                    + "\": contains the active launcher");
13570            return false;
13571        }
13572
13573        if (packageName.equals(mRequiredInstallerPackage)) {
13574            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13575                    + "\": required for package installation");
13576            return false;
13577        }
13578
13579        if (packageName.equals(mRequiredUninstallerPackage)) {
13580            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13581                    + "\": required for package uninstallation");
13582            return false;
13583        }
13584
13585        if (packageName.equals(mRequiredVerifierPackage)) {
13586            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13587                    + "\": required for package verification");
13588            return false;
13589        }
13590
13591        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13592            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13593                    + "\": is the default dialer");
13594            return false;
13595        }
13596
13597        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13598            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13599                    + "\": protected package");
13600            return false;
13601        }
13602
13603        // Cannot suspend static shared libs as they are considered
13604        // a part of the using app (emulating static linking). Also
13605        // static libs are installed always on internal storage.
13606        PackageParser.Package pkg = mPackages.get(packageName);
13607        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13608            Slog.w(TAG, "Cannot suspend package: " + packageName
13609                    + " providing static shared library: "
13610                    + pkg.staticSharedLibName);
13611            return false;
13612        }
13613
13614        return true;
13615    }
13616
13617    private String getActiveLauncherPackageName(int userId) {
13618        Intent intent = new Intent(Intent.ACTION_MAIN);
13619        intent.addCategory(Intent.CATEGORY_HOME);
13620        ResolveInfo resolveInfo = resolveIntent(
13621                intent,
13622                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13623                PackageManager.MATCH_DEFAULT_ONLY,
13624                userId);
13625
13626        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13627    }
13628
13629    private String getDefaultDialerPackageName(int userId) {
13630        synchronized (mPackages) {
13631            return mSettings.getDefaultDialerPackageNameLPw(userId);
13632        }
13633    }
13634
13635    @Override
13636    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13637        mContext.enforceCallingOrSelfPermission(
13638                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13639                "Only package verification agents can verify applications");
13640
13641        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13642        final PackageVerificationResponse response = new PackageVerificationResponse(
13643                verificationCode, Binder.getCallingUid());
13644        msg.arg1 = id;
13645        msg.obj = response;
13646        mHandler.sendMessage(msg);
13647    }
13648
13649    @Override
13650    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13651            long millisecondsToDelay) {
13652        mContext.enforceCallingOrSelfPermission(
13653                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13654                "Only package verification agents can extend verification timeouts");
13655
13656        final PackageVerificationState state = mPendingVerification.get(id);
13657        final PackageVerificationResponse response = new PackageVerificationResponse(
13658                verificationCodeAtTimeout, Binder.getCallingUid());
13659
13660        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13661            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13662        }
13663        if (millisecondsToDelay < 0) {
13664            millisecondsToDelay = 0;
13665        }
13666        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13667                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13668            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13669        }
13670
13671        if ((state != null) && !state.timeoutExtended()) {
13672            state.extendTimeout();
13673
13674            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13675            msg.arg1 = id;
13676            msg.obj = response;
13677            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13678        }
13679    }
13680
13681    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13682            int verificationCode, UserHandle user) {
13683        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13684        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13685        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13686        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13687        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13688
13689        mContext.sendBroadcastAsUser(intent, user,
13690                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13691    }
13692
13693    private ComponentName matchComponentForVerifier(String packageName,
13694            List<ResolveInfo> receivers) {
13695        ActivityInfo targetReceiver = null;
13696
13697        final int NR = receivers.size();
13698        for (int i = 0; i < NR; i++) {
13699            final ResolveInfo info = receivers.get(i);
13700            if (info.activityInfo == null) {
13701                continue;
13702            }
13703
13704            if (packageName.equals(info.activityInfo.packageName)) {
13705                targetReceiver = info.activityInfo;
13706                break;
13707            }
13708        }
13709
13710        if (targetReceiver == null) {
13711            return null;
13712        }
13713
13714        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13715    }
13716
13717    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13718            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13719        if (pkgInfo.verifiers.length == 0) {
13720            return null;
13721        }
13722
13723        final int N = pkgInfo.verifiers.length;
13724        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13725        for (int i = 0; i < N; i++) {
13726            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13727
13728            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13729                    receivers);
13730            if (comp == null) {
13731                continue;
13732            }
13733
13734            final int verifierUid = getUidForVerifier(verifierInfo);
13735            if (verifierUid == -1) {
13736                continue;
13737            }
13738
13739            if (DEBUG_VERIFY) {
13740                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13741                        + " with the correct signature");
13742            }
13743            sufficientVerifiers.add(comp);
13744            verificationState.addSufficientVerifier(verifierUid);
13745        }
13746
13747        return sufficientVerifiers;
13748    }
13749
13750    private int getUidForVerifier(VerifierInfo verifierInfo) {
13751        synchronized (mPackages) {
13752            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13753            if (pkg == null) {
13754                return -1;
13755            } else if (pkg.mSignatures.length != 1) {
13756                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13757                        + " has more than one signature; ignoring");
13758                return -1;
13759            }
13760
13761            /*
13762             * If the public key of the package's signature does not match
13763             * our expected public key, then this is a different package and
13764             * we should skip.
13765             */
13766
13767            final byte[] expectedPublicKey;
13768            try {
13769                final Signature verifierSig = pkg.mSignatures[0];
13770                final PublicKey publicKey = verifierSig.getPublicKey();
13771                expectedPublicKey = publicKey.getEncoded();
13772            } catch (CertificateException e) {
13773                return -1;
13774            }
13775
13776            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13777
13778            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13779                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13780                        + " does not have the expected public key; ignoring");
13781                return -1;
13782            }
13783
13784            return pkg.applicationInfo.uid;
13785        }
13786    }
13787
13788    @Override
13789    public void finishPackageInstall(int token, boolean didLaunch) {
13790        enforceSystemOrRoot("Only the system is allowed to finish installs");
13791
13792        if (DEBUG_INSTALL) {
13793            Slog.v(TAG, "BM finishing package install for " + token);
13794        }
13795        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13796
13797        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13798        mHandler.sendMessage(msg);
13799    }
13800
13801    /**
13802     * Get the verification agent timeout.
13803     *
13804     * @return verification timeout in milliseconds
13805     */
13806    private long getVerificationTimeout() {
13807        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13808                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13809                DEFAULT_VERIFICATION_TIMEOUT);
13810    }
13811
13812    /**
13813     * Get the default verification agent response code.
13814     *
13815     * @return default verification response code
13816     */
13817    private int getDefaultVerificationResponse() {
13818        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13819                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13820                DEFAULT_VERIFICATION_RESPONSE);
13821    }
13822
13823    /**
13824     * Check whether or not package verification has been enabled.
13825     *
13826     * @return true if verification should be performed
13827     */
13828    private boolean isVerificationEnabled(int userId, int installFlags) {
13829        if (!DEFAULT_VERIFY_ENABLE) {
13830            return false;
13831        }
13832        // Ephemeral apps don't get the full verification treatment
13833        if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13834            if (DEBUG_EPHEMERAL) {
13835                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
13836            }
13837            return false;
13838        }
13839
13840        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13841
13842        // Check if installing from ADB
13843        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13844            // Do not run verification in a test harness environment
13845            if (ActivityManager.isRunningInTestHarness()) {
13846                return false;
13847            }
13848            if (ensureVerifyAppsEnabled) {
13849                return true;
13850            }
13851            // Check if the developer does not want package verification for ADB installs
13852            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13853                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13854                return false;
13855            }
13856        }
13857
13858        if (ensureVerifyAppsEnabled) {
13859            return true;
13860        }
13861
13862        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13863                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13864    }
13865
13866    @Override
13867    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13868            throws RemoteException {
13869        mContext.enforceCallingOrSelfPermission(
13870                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13871                "Only intentfilter verification agents can verify applications");
13872
13873        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13874        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13875                Binder.getCallingUid(), verificationCode, failedDomains);
13876        msg.arg1 = id;
13877        msg.obj = response;
13878        mHandler.sendMessage(msg);
13879    }
13880
13881    @Override
13882    public int getIntentVerificationStatus(String packageName, int userId) {
13883        synchronized (mPackages) {
13884            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13885        }
13886    }
13887
13888    @Override
13889    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13890        mContext.enforceCallingOrSelfPermission(
13891                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13892
13893        boolean result = false;
13894        synchronized (mPackages) {
13895            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13896        }
13897        if (result) {
13898            scheduleWritePackageRestrictionsLocked(userId);
13899        }
13900        return result;
13901    }
13902
13903    @Override
13904    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13905            String packageName) {
13906        synchronized (mPackages) {
13907            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13908        }
13909    }
13910
13911    @Override
13912    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13913        if (TextUtils.isEmpty(packageName)) {
13914            return ParceledListSlice.emptyList();
13915        }
13916        synchronized (mPackages) {
13917            PackageParser.Package pkg = mPackages.get(packageName);
13918            if (pkg == null || pkg.activities == null) {
13919                return ParceledListSlice.emptyList();
13920            }
13921            final int count = pkg.activities.size();
13922            ArrayList<IntentFilter> result = new ArrayList<>();
13923            for (int n=0; n<count; n++) {
13924                PackageParser.Activity activity = pkg.activities.get(n);
13925                if (activity.intents != null && activity.intents.size() > 0) {
13926                    result.addAll(activity.intents);
13927                }
13928            }
13929            return new ParceledListSlice<>(result);
13930        }
13931    }
13932
13933    @Override
13934    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13935        mContext.enforceCallingOrSelfPermission(
13936                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13937
13938        synchronized (mPackages) {
13939            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13940            if (packageName != null) {
13941                result |= updateIntentVerificationStatus(packageName,
13942                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13943                        userId);
13944                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13945                        packageName, userId);
13946            }
13947            return result;
13948        }
13949    }
13950
13951    @Override
13952    public String getDefaultBrowserPackageName(int userId) {
13953        synchronized (mPackages) {
13954            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13955        }
13956    }
13957
13958    /**
13959     * Get the "allow unknown sources" setting.
13960     *
13961     * @return the current "allow unknown sources" setting
13962     */
13963    private int getUnknownSourcesSettings() {
13964        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13965                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13966                -1);
13967    }
13968
13969    @Override
13970    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13971        final int uid = Binder.getCallingUid();
13972        // writer
13973        synchronized (mPackages) {
13974            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13975            if (targetPackageSetting == null) {
13976                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13977            }
13978
13979            PackageSetting installerPackageSetting;
13980            if (installerPackageName != null) {
13981                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13982                if (installerPackageSetting == null) {
13983                    throw new IllegalArgumentException("Unknown installer package: "
13984                            + installerPackageName);
13985                }
13986            } else {
13987                installerPackageSetting = null;
13988            }
13989
13990            Signature[] callerSignature;
13991            Object obj = mSettings.getUserIdLPr(uid);
13992            if (obj != null) {
13993                if (obj instanceof SharedUserSetting) {
13994                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13995                } else if (obj instanceof PackageSetting) {
13996                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13997                } else {
13998                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13999                }
14000            } else {
14001                throw new SecurityException("Unknown calling UID: " + uid);
14002            }
14003
14004            // Verify: can't set installerPackageName to a package that is
14005            // not signed with the same cert as the caller.
14006            if (installerPackageSetting != null) {
14007                if (compareSignatures(callerSignature,
14008                        installerPackageSetting.signatures.mSignatures)
14009                        != PackageManager.SIGNATURE_MATCH) {
14010                    throw new SecurityException(
14011                            "Caller does not have same cert as new installer package "
14012                            + installerPackageName);
14013                }
14014            }
14015
14016            // Verify: if target already has an installer package, it must
14017            // be signed with the same cert as the caller.
14018            if (targetPackageSetting.installerPackageName != null) {
14019                PackageSetting setting = mSettings.mPackages.get(
14020                        targetPackageSetting.installerPackageName);
14021                // If the currently set package isn't valid, then it's always
14022                // okay to change it.
14023                if (setting != null) {
14024                    if (compareSignatures(callerSignature,
14025                            setting.signatures.mSignatures)
14026                            != PackageManager.SIGNATURE_MATCH) {
14027                        throw new SecurityException(
14028                                "Caller does not have same cert as old installer package "
14029                                + targetPackageSetting.installerPackageName);
14030                    }
14031                }
14032            }
14033
14034            // Okay!
14035            targetPackageSetting.installerPackageName = installerPackageName;
14036            if (installerPackageName != null) {
14037                mSettings.mInstallerPackages.add(installerPackageName);
14038            }
14039            scheduleWriteSettingsLocked();
14040        }
14041    }
14042
14043    @Override
14044    public void setApplicationCategoryHint(String packageName, int categoryHint,
14045            String callerPackageName) {
14046        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14047                callerPackageName);
14048        synchronized (mPackages) {
14049            PackageSetting ps = mSettings.mPackages.get(packageName);
14050            if (ps == null) {
14051                throw new IllegalArgumentException("Unknown target package " + packageName);
14052            }
14053
14054            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14055                throw new IllegalArgumentException("Calling package " + callerPackageName
14056                        + " is not installer for " + packageName);
14057            }
14058
14059            if (ps.categoryHint != categoryHint) {
14060                ps.categoryHint = categoryHint;
14061                scheduleWriteSettingsLocked();
14062            }
14063        }
14064    }
14065
14066    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14067        // Queue up an async operation since the package installation may take a little while.
14068        mHandler.post(new Runnable() {
14069            public void run() {
14070                mHandler.removeCallbacks(this);
14071                 // Result object to be returned
14072                PackageInstalledInfo res = new PackageInstalledInfo();
14073                res.setReturnCode(currentStatus);
14074                res.uid = -1;
14075                res.pkg = null;
14076                res.removedInfo = null;
14077                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14078                    args.doPreInstall(res.returnCode);
14079                    synchronized (mInstallLock) {
14080                        installPackageTracedLI(args, res);
14081                    }
14082                    args.doPostInstall(res.returnCode, res.uid);
14083                }
14084
14085                // A restore should be performed at this point if (a) the install
14086                // succeeded, (b) the operation is not an update, and (c) the new
14087                // package has not opted out of backup participation.
14088                final boolean update = res.removedInfo != null
14089                        && res.removedInfo.removedPackage != null;
14090                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14091                boolean doRestore = !update
14092                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14093
14094                // Set up the post-install work request bookkeeping.  This will be used
14095                // and cleaned up by the post-install event handling regardless of whether
14096                // there's a restore pass performed.  Token values are >= 1.
14097                int token;
14098                if (mNextInstallToken < 0) mNextInstallToken = 1;
14099                token = mNextInstallToken++;
14100
14101                PostInstallData data = new PostInstallData(args, res);
14102                mRunningInstalls.put(token, data);
14103                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14104
14105                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14106                    // Pass responsibility to the Backup Manager.  It will perform a
14107                    // restore if appropriate, then pass responsibility back to the
14108                    // Package Manager to run the post-install observer callbacks
14109                    // and broadcasts.
14110                    IBackupManager bm = IBackupManager.Stub.asInterface(
14111                            ServiceManager.getService(Context.BACKUP_SERVICE));
14112                    if (bm != null) {
14113                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14114                                + " to BM for possible restore");
14115                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14116                        try {
14117                            // TODO: http://b/22388012
14118                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14119                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14120                            } else {
14121                                doRestore = false;
14122                            }
14123                        } catch (RemoteException e) {
14124                            // can't happen; the backup manager is local
14125                        } catch (Exception e) {
14126                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14127                            doRestore = false;
14128                        }
14129                    } else {
14130                        Slog.e(TAG, "Backup Manager not found!");
14131                        doRestore = false;
14132                    }
14133                }
14134
14135                if (!doRestore) {
14136                    // No restore possible, or the Backup Manager was mysteriously not
14137                    // available -- just fire the post-install work request directly.
14138                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14139
14140                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14141
14142                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14143                    mHandler.sendMessage(msg);
14144                }
14145            }
14146        });
14147    }
14148
14149    /**
14150     * Callback from PackageSettings whenever an app is first transitioned out of the
14151     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14152     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14153     * here whether the app is the target of an ongoing install, and only send the
14154     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14155     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14156     * handling.
14157     */
14158    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14159        // Serialize this with the rest of the install-process message chain.  In the
14160        // restore-at-install case, this Runnable will necessarily run before the
14161        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14162        // are coherent.  In the non-restore case, the app has already completed install
14163        // and been launched through some other means, so it is not in a problematic
14164        // state for observers to see the FIRST_LAUNCH signal.
14165        mHandler.post(new Runnable() {
14166            @Override
14167            public void run() {
14168                for (int i = 0; i < mRunningInstalls.size(); i++) {
14169                    final PostInstallData data = mRunningInstalls.valueAt(i);
14170                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14171                        continue;
14172                    }
14173                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14174                        // right package; but is it for the right user?
14175                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14176                            if (userId == data.res.newUsers[uIndex]) {
14177                                if (DEBUG_BACKUP) {
14178                                    Slog.i(TAG, "Package " + pkgName
14179                                            + " being restored so deferring FIRST_LAUNCH");
14180                                }
14181                                return;
14182                            }
14183                        }
14184                    }
14185                }
14186                // didn't find it, so not being restored
14187                if (DEBUG_BACKUP) {
14188                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14189                }
14190                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14191            }
14192        });
14193    }
14194
14195    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14196        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14197                installerPkg, null, userIds);
14198    }
14199
14200    private abstract class HandlerParams {
14201        private static final int MAX_RETRIES = 4;
14202
14203        /**
14204         * Number of times startCopy() has been attempted and had a non-fatal
14205         * error.
14206         */
14207        private int mRetries = 0;
14208
14209        /** User handle for the user requesting the information or installation. */
14210        private final UserHandle mUser;
14211        String traceMethod;
14212        int traceCookie;
14213
14214        HandlerParams(UserHandle user) {
14215            mUser = user;
14216        }
14217
14218        UserHandle getUser() {
14219            return mUser;
14220        }
14221
14222        HandlerParams setTraceMethod(String traceMethod) {
14223            this.traceMethod = traceMethod;
14224            return this;
14225        }
14226
14227        HandlerParams setTraceCookie(int traceCookie) {
14228            this.traceCookie = traceCookie;
14229            return this;
14230        }
14231
14232        final boolean startCopy() {
14233            boolean res;
14234            try {
14235                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14236
14237                if (++mRetries > MAX_RETRIES) {
14238                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14239                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14240                    handleServiceError();
14241                    return false;
14242                } else {
14243                    handleStartCopy();
14244                    res = true;
14245                }
14246            } catch (RemoteException e) {
14247                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14248                mHandler.sendEmptyMessage(MCS_RECONNECT);
14249                res = false;
14250            }
14251            handleReturnCode();
14252            return res;
14253        }
14254
14255        final void serviceError() {
14256            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14257            handleServiceError();
14258            handleReturnCode();
14259        }
14260
14261        abstract void handleStartCopy() throws RemoteException;
14262        abstract void handleServiceError();
14263        abstract void handleReturnCode();
14264    }
14265
14266    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14267        for (File path : paths) {
14268            try {
14269                mcs.clearDirectory(path.getAbsolutePath());
14270            } catch (RemoteException e) {
14271            }
14272        }
14273    }
14274
14275    static class OriginInfo {
14276        /**
14277         * Location where install is coming from, before it has been
14278         * copied/renamed into place. This could be a single monolithic APK
14279         * file, or a cluster directory. This location may be untrusted.
14280         */
14281        final File file;
14282        final String cid;
14283
14284        /**
14285         * Flag indicating that {@link #file} or {@link #cid} has already been
14286         * staged, meaning downstream users don't need to defensively copy the
14287         * contents.
14288         */
14289        final boolean staged;
14290
14291        /**
14292         * Flag indicating that {@link #file} or {@link #cid} is an already
14293         * installed app that is being moved.
14294         */
14295        final boolean existing;
14296
14297        final String resolvedPath;
14298        final File resolvedFile;
14299
14300        static OriginInfo fromNothing() {
14301            return new OriginInfo(null, null, false, false);
14302        }
14303
14304        static OriginInfo fromUntrustedFile(File file) {
14305            return new OriginInfo(file, null, false, false);
14306        }
14307
14308        static OriginInfo fromExistingFile(File file) {
14309            return new OriginInfo(file, null, false, true);
14310        }
14311
14312        static OriginInfo fromStagedFile(File file) {
14313            return new OriginInfo(file, null, true, false);
14314        }
14315
14316        static OriginInfo fromStagedContainer(String cid) {
14317            return new OriginInfo(null, cid, true, false);
14318        }
14319
14320        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14321            this.file = file;
14322            this.cid = cid;
14323            this.staged = staged;
14324            this.existing = existing;
14325
14326            if (cid != null) {
14327                resolvedPath = PackageHelper.getSdDir(cid);
14328                resolvedFile = new File(resolvedPath);
14329            } else if (file != null) {
14330                resolvedPath = file.getAbsolutePath();
14331                resolvedFile = file;
14332            } else {
14333                resolvedPath = null;
14334                resolvedFile = null;
14335            }
14336        }
14337    }
14338
14339    static class MoveInfo {
14340        final int moveId;
14341        final String fromUuid;
14342        final String toUuid;
14343        final String packageName;
14344        final String dataAppName;
14345        final int appId;
14346        final String seinfo;
14347        final int targetSdkVersion;
14348
14349        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14350                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14351            this.moveId = moveId;
14352            this.fromUuid = fromUuid;
14353            this.toUuid = toUuid;
14354            this.packageName = packageName;
14355            this.dataAppName = dataAppName;
14356            this.appId = appId;
14357            this.seinfo = seinfo;
14358            this.targetSdkVersion = targetSdkVersion;
14359        }
14360    }
14361
14362    static class VerificationInfo {
14363        /** A constant used to indicate that a uid value is not present. */
14364        public static final int NO_UID = -1;
14365
14366        /** URI referencing where the package was downloaded from. */
14367        final Uri originatingUri;
14368
14369        /** HTTP referrer URI associated with the originatingURI. */
14370        final Uri referrer;
14371
14372        /** UID of the application that the install request originated from. */
14373        final int originatingUid;
14374
14375        /** UID of application requesting the install */
14376        final int installerUid;
14377
14378        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14379            this.originatingUri = originatingUri;
14380            this.referrer = referrer;
14381            this.originatingUid = originatingUid;
14382            this.installerUid = installerUid;
14383        }
14384    }
14385
14386    class InstallParams extends HandlerParams {
14387        final OriginInfo origin;
14388        final MoveInfo move;
14389        final IPackageInstallObserver2 observer;
14390        int installFlags;
14391        final String installerPackageName;
14392        final String volumeUuid;
14393        private InstallArgs mArgs;
14394        private int mRet;
14395        final String packageAbiOverride;
14396        final String[] grantedRuntimePermissions;
14397        final VerificationInfo verificationInfo;
14398        final Certificate[][] certificates;
14399        final int installReason;
14400
14401        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14402                int installFlags, String installerPackageName, String volumeUuid,
14403                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14404                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14405            super(user);
14406            this.origin = origin;
14407            this.move = move;
14408            this.observer = observer;
14409            this.installFlags = installFlags;
14410            this.installerPackageName = installerPackageName;
14411            this.volumeUuid = volumeUuid;
14412            this.verificationInfo = verificationInfo;
14413            this.packageAbiOverride = packageAbiOverride;
14414            this.grantedRuntimePermissions = grantedPermissions;
14415            this.certificates = certificates;
14416            this.installReason = installReason;
14417        }
14418
14419        @Override
14420        public String toString() {
14421            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14422                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14423        }
14424
14425        private int installLocationPolicy(PackageInfoLite pkgLite) {
14426            String packageName = pkgLite.packageName;
14427            int installLocation = pkgLite.installLocation;
14428            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14429            // reader
14430            synchronized (mPackages) {
14431                // Currently installed package which the new package is attempting to replace or
14432                // null if no such package is installed.
14433                PackageParser.Package installedPkg = mPackages.get(packageName);
14434                // Package which currently owns the data which the new package will own if installed.
14435                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14436                // will be null whereas dataOwnerPkg will contain information about the package
14437                // which was uninstalled while keeping its data.
14438                PackageParser.Package dataOwnerPkg = installedPkg;
14439                if (dataOwnerPkg  == null) {
14440                    PackageSetting ps = mSettings.mPackages.get(packageName);
14441                    if (ps != null) {
14442                        dataOwnerPkg = ps.pkg;
14443                    }
14444                }
14445
14446                if (dataOwnerPkg != null) {
14447                    // If installed, the package will get access to data left on the device by its
14448                    // predecessor. As a security measure, this is permited only if this is not a
14449                    // version downgrade or if the predecessor package is marked as debuggable and
14450                    // a downgrade is explicitly requested.
14451                    //
14452                    // On debuggable platform builds, downgrades are permitted even for
14453                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14454                    // not offer security guarantees and thus it's OK to disable some security
14455                    // mechanisms to make debugging/testing easier on those builds. However, even on
14456                    // debuggable builds downgrades of packages are permitted only if requested via
14457                    // installFlags. This is because we aim to keep the behavior of debuggable
14458                    // platform builds as close as possible to the behavior of non-debuggable
14459                    // platform builds.
14460                    final boolean downgradeRequested =
14461                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14462                    final boolean packageDebuggable =
14463                                (dataOwnerPkg.applicationInfo.flags
14464                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14465                    final boolean downgradePermitted =
14466                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14467                    if (!downgradePermitted) {
14468                        try {
14469                            checkDowngrade(dataOwnerPkg, pkgLite);
14470                        } catch (PackageManagerException e) {
14471                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14472                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14473                        }
14474                    }
14475                }
14476
14477                if (installedPkg != null) {
14478                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14479                        // Check for updated system application.
14480                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14481                            if (onSd) {
14482                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14483                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14484                            }
14485                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14486                        } else {
14487                            if (onSd) {
14488                                // Install flag overrides everything.
14489                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14490                            }
14491                            // If current upgrade specifies particular preference
14492                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14493                                // Application explicitly specified internal.
14494                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14495                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14496                                // App explictly prefers external. Let policy decide
14497                            } else {
14498                                // Prefer previous location
14499                                if (isExternal(installedPkg)) {
14500                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14501                                }
14502                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14503                            }
14504                        }
14505                    } else {
14506                        // Invalid install. Return error code
14507                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14508                    }
14509                }
14510            }
14511            // All the special cases have been taken care of.
14512            // Return result based on recommended install location.
14513            if (onSd) {
14514                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14515            }
14516            return pkgLite.recommendedInstallLocation;
14517        }
14518
14519        /*
14520         * Invoke remote method to get package information and install
14521         * location values. Override install location based on default
14522         * policy if needed and then create install arguments based
14523         * on the install location.
14524         */
14525        public void handleStartCopy() throws RemoteException {
14526            int ret = PackageManager.INSTALL_SUCCEEDED;
14527
14528            // If we're already staged, we've firmly committed to an install location
14529            if (origin.staged) {
14530                if (origin.file != null) {
14531                    installFlags |= PackageManager.INSTALL_INTERNAL;
14532                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14533                } else if (origin.cid != null) {
14534                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14535                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14536                } else {
14537                    throw new IllegalStateException("Invalid stage location");
14538                }
14539            }
14540
14541            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14542            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14543            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14544            PackageInfoLite pkgLite = null;
14545
14546            if (onInt && onSd) {
14547                // Check if both bits are set.
14548                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14549                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14550            } else if (onSd && ephemeral) {
14551                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14552                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14553            } else {
14554                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14555                        packageAbiOverride);
14556
14557                if (DEBUG_EPHEMERAL && ephemeral) {
14558                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14559                }
14560
14561                /*
14562                 * If we have too little free space, try to free cache
14563                 * before giving up.
14564                 */
14565                if (!origin.staged && pkgLite.recommendedInstallLocation
14566                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14567                    // TODO: focus freeing disk space on the target device
14568                    final StorageManager storage = StorageManager.from(mContext);
14569                    final long lowThreshold = storage.getStorageLowBytes(
14570                            Environment.getDataDirectory());
14571
14572                    final long sizeBytes = mContainerService.calculateInstalledSize(
14573                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14574
14575                    try {
14576                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14577                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14578                                installFlags, packageAbiOverride);
14579                    } catch (InstallerException e) {
14580                        Slog.w(TAG, "Failed to free cache", e);
14581                    }
14582
14583                    /*
14584                     * The cache free must have deleted the file we
14585                     * downloaded to install.
14586                     *
14587                     * TODO: fix the "freeCache" call to not delete
14588                     *       the file we care about.
14589                     */
14590                    if (pkgLite.recommendedInstallLocation
14591                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14592                        pkgLite.recommendedInstallLocation
14593                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14594                    }
14595                }
14596            }
14597
14598            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14599                int loc = pkgLite.recommendedInstallLocation;
14600                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14601                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14602                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14603                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14604                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14605                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14606                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14607                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14608                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14609                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14610                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14611                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14612                } else {
14613                    // Override with defaults if needed.
14614                    loc = installLocationPolicy(pkgLite);
14615                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14616                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14617                    } else if (!onSd && !onInt) {
14618                        // Override install location with flags
14619                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14620                            // Set the flag to install on external media.
14621                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14622                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14623                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14624                            if (DEBUG_EPHEMERAL) {
14625                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14626                            }
14627                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14628                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14629                                    |PackageManager.INSTALL_INTERNAL);
14630                        } else {
14631                            // Make sure the flag for installing on external
14632                            // media is unset
14633                            installFlags |= PackageManager.INSTALL_INTERNAL;
14634                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14635                        }
14636                    }
14637                }
14638            }
14639
14640            final InstallArgs args = createInstallArgs(this);
14641            mArgs = args;
14642
14643            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14644                // TODO: http://b/22976637
14645                // Apps installed for "all" users use the device owner to verify the app
14646                UserHandle verifierUser = getUser();
14647                if (verifierUser == UserHandle.ALL) {
14648                    verifierUser = UserHandle.SYSTEM;
14649                }
14650
14651                /*
14652                 * Determine if we have any installed package verifiers. If we
14653                 * do, then we'll defer to them to verify the packages.
14654                 */
14655                final int requiredUid = mRequiredVerifierPackage == null ? -1
14656                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14657                                verifierUser.getIdentifier());
14658                if (!origin.existing && requiredUid != -1
14659                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14660                    final Intent verification = new Intent(
14661                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14662                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14663                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14664                            PACKAGE_MIME_TYPE);
14665                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14666
14667                    // Query all live verifiers based on current user state
14668                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14669                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14670
14671                    if (DEBUG_VERIFY) {
14672                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14673                                + verification.toString() + " with " + pkgLite.verifiers.length
14674                                + " optional verifiers");
14675                    }
14676
14677                    final int verificationId = mPendingVerificationToken++;
14678
14679                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14680
14681                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14682                            installerPackageName);
14683
14684                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14685                            installFlags);
14686
14687                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14688                            pkgLite.packageName);
14689
14690                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14691                            pkgLite.versionCode);
14692
14693                    if (verificationInfo != null) {
14694                        if (verificationInfo.originatingUri != null) {
14695                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14696                                    verificationInfo.originatingUri);
14697                        }
14698                        if (verificationInfo.referrer != null) {
14699                            verification.putExtra(Intent.EXTRA_REFERRER,
14700                                    verificationInfo.referrer);
14701                        }
14702                        if (verificationInfo.originatingUid >= 0) {
14703                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14704                                    verificationInfo.originatingUid);
14705                        }
14706                        if (verificationInfo.installerUid >= 0) {
14707                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14708                                    verificationInfo.installerUid);
14709                        }
14710                    }
14711
14712                    final PackageVerificationState verificationState = new PackageVerificationState(
14713                            requiredUid, args);
14714
14715                    mPendingVerification.append(verificationId, verificationState);
14716
14717                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14718                            receivers, verificationState);
14719
14720                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14721                    final long idleDuration = getVerificationTimeout();
14722
14723                    /*
14724                     * If any sufficient verifiers were listed in the package
14725                     * manifest, attempt to ask them.
14726                     */
14727                    if (sufficientVerifiers != null) {
14728                        final int N = sufficientVerifiers.size();
14729                        if (N == 0) {
14730                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14731                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14732                        } else {
14733                            for (int i = 0; i < N; i++) {
14734                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14735                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14736                                        verifierComponent.getPackageName(), idleDuration,
14737                                        verifierUser.getIdentifier(), false, "package verifier");
14738
14739                                final Intent sufficientIntent = new Intent(verification);
14740                                sufficientIntent.setComponent(verifierComponent);
14741                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14742                            }
14743                        }
14744                    }
14745
14746                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14747                            mRequiredVerifierPackage, receivers);
14748                    if (ret == PackageManager.INSTALL_SUCCEEDED
14749                            && mRequiredVerifierPackage != null) {
14750                        Trace.asyncTraceBegin(
14751                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14752                        /*
14753                         * Send the intent to the required verification agent,
14754                         * but only start the verification timeout after the
14755                         * target BroadcastReceivers have run.
14756                         */
14757                        verification.setComponent(requiredVerifierComponent);
14758                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14759                                requiredVerifierComponent.getPackageName(), idleDuration,
14760                                verifierUser.getIdentifier(), false, "package verifier");
14761                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14762                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14763                                new BroadcastReceiver() {
14764                                    @Override
14765                                    public void onReceive(Context context, Intent intent) {
14766                                        final Message msg = mHandler
14767                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14768                                        msg.arg1 = verificationId;
14769                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14770                                    }
14771                                }, null, 0, null, null);
14772
14773                        /*
14774                         * We don't want the copy to proceed until verification
14775                         * succeeds, so null out this field.
14776                         */
14777                        mArgs = null;
14778                    }
14779                } else {
14780                    /*
14781                     * No package verification is enabled, so immediately start
14782                     * the remote call to initiate copy using temporary file.
14783                     */
14784                    ret = args.copyApk(mContainerService, true);
14785                }
14786            }
14787
14788            mRet = ret;
14789        }
14790
14791        @Override
14792        void handleReturnCode() {
14793            // If mArgs is null, then MCS couldn't be reached. When it
14794            // reconnects, it will try again to install. At that point, this
14795            // will succeed.
14796            if (mArgs != null) {
14797                processPendingInstall(mArgs, mRet);
14798            }
14799        }
14800
14801        @Override
14802        void handleServiceError() {
14803            mArgs = createInstallArgs(this);
14804            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14805        }
14806
14807        public boolean isForwardLocked() {
14808            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14809        }
14810    }
14811
14812    /**
14813     * Used during creation of InstallArgs
14814     *
14815     * @param installFlags package installation flags
14816     * @return true if should be installed on external storage
14817     */
14818    private static boolean installOnExternalAsec(int installFlags) {
14819        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14820            return false;
14821        }
14822        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14823            return true;
14824        }
14825        return false;
14826    }
14827
14828    /**
14829     * Used during creation of InstallArgs
14830     *
14831     * @param installFlags package installation flags
14832     * @return true if should be installed as forward locked
14833     */
14834    private static boolean installForwardLocked(int installFlags) {
14835        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14836    }
14837
14838    private InstallArgs createInstallArgs(InstallParams params) {
14839        if (params.move != null) {
14840            return new MoveInstallArgs(params);
14841        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14842            return new AsecInstallArgs(params);
14843        } else {
14844            return new FileInstallArgs(params);
14845        }
14846    }
14847
14848    /**
14849     * Create args that describe an existing installed package. Typically used
14850     * when cleaning up old installs, or used as a move source.
14851     */
14852    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14853            String resourcePath, String[] instructionSets) {
14854        final boolean isInAsec;
14855        if (installOnExternalAsec(installFlags)) {
14856            /* Apps on SD card are always in ASEC containers. */
14857            isInAsec = true;
14858        } else if (installForwardLocked(installFlags)
14859                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14860            /*
14861             * Forward-locked apps are only in ASEC containers if they're the
14862             * new style
14863             */
14864            isInAsec = true;
14865        } else {
14866            isInAsec = false;
14867        }
14868
14869        if (isInAsec) {
14870            return new AsecInstallArgs(codePath, instructionSets,
14871                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14872        } else {
14873            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14874        }
14875    }
14876
14877    static abstract class InstallArgs {
14878        /** @see InstallParams#origin */
14879        final OriginInfo origin;
14880        /** @see InstallParams#move */
14881        final MoveInfo move;
14882
14883        final IPackageInstallObserver2 observer;
14884        // Always refers to PackageManager flags only
14885        final int installFlags;
14886        final String installerPackageName;
14887        final String volumeUuid;
14888        final UserHandle user;
14889        final String abiOverride;
14890        final String[] installGrantPermissions;
14891        /** If non-null, drop an async trace when the install completes */
14892        final String traceMethod;
14893        final int traceCookie;
14894        final Certificate[][] certificates;
14895        final int installReason;
14896
14897        // The list of instruction sets supported by this app. This is currently
14898        // only used during the rmdex() phase to clean up resources. We can get rid of this
14899        // if we move dex files under the common app path.
14900        /* nullable */ String[] instructionSets;
14901
14902        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14903                int installFlags, String installerPackageName, String volumeUuid,
14904                UserHandle user, String[] instructionSets,
14905                String abiOverride, String[] installGrantPermissions,
14906                String traceMethod, int traceCookie, Certificate[][] certificates,
14907                int installReason) {
14908            this.origin = origin;
14909            this.move = move;
14910            this.installFlags = installFlags;
14911            this.observer = observer;
14912            this.installerPackageName = installerPackageName;
14913            this.volumeUuid = volumeUuid;
14914            this.user = user;
14915            this.instructionSets = instructionSets;
14916            this.abiOverride = abiOverride;
14917            this.installGrantPermissions = installGrantPermissions;
14918            this.traceMethod = traceMethod;
14919            this.traceCookie = traceCookie;
14920            this.certificates = certificates;
14921            this.installReason = installReason;
14922        }
14923
14924        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14925        abstract int doPreInstall(int status);
14926
14927        /**
14928         * Rename package into final resting place. All paths on the given
14929         * scanned package should be updated to reflect the rename.
14930         */
14931        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14932        abstract int doPostInstall(int status, int uid);
14933
14934        /** @see PackageSettingBase#codePathString */
14935        abstract String getCodePath();
14936        /** @see PackageSettingBase#resourcePathString */
14937        abstract String getResourcePath();
14938
14939        // Need installer lock especially for dex file removal.
14940        abstract void cleanUpResourcesLI();
14941        abstract boolean doPostDeleteLI(boolean delete);
14942
14943        /**
14944         * Called before the source arguments are copied. This is used mostly
14945         * for MoveParams when it needs to read the source file to put it in the
14946         * destination.
14947         */
14948        int doPreCopy() {
14949            return PackageManager.INSTALL_SUCCEEDED;
14950        }
14951
14952        /**
14953         * Called after the source arguments are copied. This is used mostly for
14954         * MoveParams when it needs to read the source file to put it in the
14955         * destination.
14956         */
14957        int doPostCopy(int uid) {
14958            return PackageManager.INSTALL_SUCCEEDED;
14959        }
14960
14961        protected boolean isFwdLocked() {
14962            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14963        }
14964
14965        protected boolean isExternalAsec() {
14966            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14967        }
14968
14969        protected boolean isEphemeral() {
14970            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14971        }
14972
14973        UserHandle getUser() {
14974            return user;
14975        }
14976    }
14977
14978    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14979        if (!allCodePaths.isEmpty()) {
14980            if (instructionSets == null) {
14981                throw new IllegalStateException("instructionSet == null");
14982            }
14983            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14984            for (String codePath : allCodePaths) {
14985                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14986                    try {
14987                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14988                    } catch (InstallerException ignored) {
14989                    }
14990                }
14991            }
14992        }
14993    }
14994
14995    /**
14996     * Logic to handle installation of non-ASEC applications, including copying
14997     * and renaming logic.
14998     */
14999    class FileInstallArgs extends InstallArgs {
15000        private File codeFile;
15001        private File resourceFile;
15002
15003        // Example topology:
15004        // /data/app/com.example/base.apk
15005        // /data/app/com.example/split_foo.apk
15006        // /data/app/com.example/lib/arm/libfoo.so
15007        // /data/app/com.example/lib/arm64/libfoo.so
15008        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15009
15010        /** New install */
15011        FileInstallArgs(InstallParams params) {
15012            super(params.origin, params.move, params.observer, params.installFlags,
15013                    params.installerPackageName, params.volumeUuid,
15014                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15015                    params.grantedRuntimePermissions,
15016                    params.traceMethod, params.traceCookie, params.certificates,
15017                    params.installReason);
15018            if (isFwdLocked()) {
15019                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15020            }
15021        }
15022
15023        /** Existing install */
15024        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15025            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15026                    null, null, null, 0, null /*certificates*/,
15027                    PackageManager.INSTALL_REASON_UNKNOWN);
15028            this.codeFile = (codePath != null) ? new File(codePath) : null;
15029            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15030        }
15031
15032        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15033            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15034            try {
15035                return doCopyApk(imcs, temp);
15036            } finally {
15037                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15038            }
15039        }
15040
15041        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15042            if (origin.staged) {
15043                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15044                codeFile = origin.file;
15045                resourceFile = origin.file;
15046                return PackageManager.INSTALL_SUCCEEDED;
15047            }
15048
15049            try {
15050                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15051                final File tempDir =
15052                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15053                codeFile = tempDir;
15054                resourceFile = tempDir;
15055            } catch (IOException e) {
15056                Slog.w(TAG, "Failed to create copy file: " + e);
15057                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15058            }
15059
15060            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15061                @Override
15062                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15063                    if (!FileUtils.isValidExtFilename(name)) {
15064                        throw new IllegalArgumentException("Invalid filename: " + name);
15065                    }
15066                    try {
15067                        final File file = new File(codeFile, name);
15068                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15069                                O_RDWR | O_CREAT, 0644);
15070                        Os.chmod(file.getAbsolutePath(), 0644);
15071                        return new ParcelFileDescriptor(fd);
15072                    } catch (ErrnoException e) {
15073                        throw new RemoteException("Failed to open: " + e.getMessage());
15074                    }
15075                }
15076            };
15077
15078            int ret = PackageManager.INSTALL_SUCCEEDED;
15079            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15080            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15081                Slog.e(TAG, "Failed to copy package");
15082                return ret;
15083            }
15084
15085            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15086            NativeLibraryHelper.Handle handle = null;
15087            try {
15088                handle = NativeLibraryHelper.Handle.create(codeFile);
15089                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15090                        abiOverride);
15091            } catch (IOException e) {
15092                Slog.e(TAG, "Copying native libraries failed", e);
15093                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15094            } finally {
15095                IoUtils.closeQuietly(handle);
15096            }
15097
15098            return ret;
15099        }
15100
15101        int doPreInstall(int status) {
15102            if (status != PackageManager.INSTALL_SUCCEEDED) {
15103                cleanUp();
15104            }
15105            return status;
15106        }
15107
15108        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15109            if (status != PackageManager.INSTALL_SUCCEEDED) {
15110                cleanUp();
15111                return false;
15112            }
15113
15114            final File targetDir = codeFile.getParentFile();
15115            final File beforeCodeFile = codeFile;
15116            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15117
15118            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15119            try {
15120                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15121            } catch (ErrnoException e) {
15122                Slog.w(TAG, "Failed to rename", e);
15123                return false;
15124            }
15125
15126            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15127                Slog.w(TAG, "Failed to restorecon");
15128                return false;
15129            }
15130
15131            // Reflect the rename internally
15132            codeFile = afterCodeFile;
15133            resourceFile = afterCodeFile;
15134
15135            // Reflect the rename in scanned details
15136            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15137            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15138                    afterCodeFile, pkg.baseCodePath));
15139            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15140                    afterCodeFile, pkg.splitCodePaths));
15141
15142            // Reflect the rename in app info
15143            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15144            pkg.setApplicationInfoCodePath(pkg.codePath);
15145            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15146            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15147            pkg.setApplicationInfoResourcePath(pkg.codePath);
15148            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15149            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15150
15151            return true;
15152        }
15153
15154        int doPostInstall(int status, int uid) {
15155            if (status != PackageManager.INSTALL_SUCCEEDED) {
15156                cleanUp();
15157            }
15158            return status;
15159        }
15160
15161        @Override
15162        String getCodePath() {
15163            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15164        }
15165
15166        @Override
15167        String getResourcePath() {
15168            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15169        }
15170
15171        private boolean cleanUp() {
15172            if (codeFile == null || !codeFile.exists()) {
15173                return false;
15174            }
15175
15176            removeCodePathLI(codeFile);
15177
15178            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15179                resourceFile.delete();
15180            }
15181
15182            return true;
15183        }
15184
15185        void cleanUpResourcesLI() {
15186            // Try enumerating all code paths before deleting
15187            List<String> allCodePaths = Collections.EMPTY_LIST;
15188            if (codeFile != null && codeFile.exists()) {
15189                try {
15190                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15191                    allCodePaths = pkg.getAllCodePaths();
15192                } catch (PackageParserException e) {
15193                    // Ignored; we tried our best
15194                }
15195            }
15196
15197            cleanUp();
15198            removeDexFiles(allCodePaths, instructionSets);
15199        }
15200
15201        boolean doPostDeleteLI(boolean delete) {
15202            // XXX err, shouldn't we respect the delete flag?
15203            cleanUpResourcesLI();
15204            return true;
15205        }
15206    }
15207
15208    private boolean isAsecExternal(String cid) {
15209        final String asecPath = PackageHelper.getSdFilesystem(cid);
15210        return !asecPath.startsWith(mAsecInternalPath);
15211    }
15212
15213    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15214            PackageManagerException {
15215        if (copyRet < 0) {
15216            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15217                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15218                throw new PackageManagerException(copyRet, message);
15219            }
15220        }
15221    }
15222
15223    /**
15224     * Extract the StorageManagerService "container ID" from the full code path of an
15225     * .apk.
15226     */
15227    static String cidFromCodePath(String fullCodePath) {
15228        int eidx = fullCodePath.lastIndexOf("/");
15229        String subStr1 = fullCodePath.substring(0, eidx);
15230        int sidx = subStr1.lastIndexOf("/");
15231        return subStr1.substring(sidx+1, eidx);
15232    }
15233
15234    /**
15235     * Logic to handle installation of ASEC applications, including copying and
15236     * renaming logic.
15237     */
15238    class AsecInstallArgs extends InstallArgs {
15239        static final String RES_FILE_NAME = "pkg.apk";
15240        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15241
15242        String cid;
15243        String packagePath;
15244        String resourcePath;
15245
15246        /** New install */
15247        AsecInstallArgs(InstallParams params) {
15248            super(params.origin, params.move, params.observer, params.installFlags,
15249                    params.installerPackageName, params.volumeUuid,
15250                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15251                    params.grantedRuntimePermissions,
15252                    params.traceMethod, params.traceCookie, params.certificates,
15253                    params.installReason);
15254        }
15255
15256        /** Existing install */
15257        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15258                        boolean isExternal, boolean isForwardLocked) {
15259            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15260                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15261                    instructionSets, null, null, null, 0, null /*certificates*/,
15262                    PackageManager.INSTALL_REASON_UNKNOWN);
15263            // Hackily pretend we're still looking at a full code path
15264            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15265                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15266            }
15267
15268            // Extract cid from fullCodePath
15269            int eidx = fullCodePath.lastIndexOf("/");
15270            String subStr1 = fullCodePath.substring(0, eidx);
15271            int sidx = subStr1.lastIndexOf("/");
15272            cid = subStr1.substring(sidx+1, eidx);
15273            setMountPath(subStr1);
15274        }
15275
15276        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15277            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15278                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15279                    instructionSets, null, null, null, 0, null /*certificates*/,
15280                    PackageManager.INSTALL_REASON_UNKNOWN);
15281            this.cid = cid;
15282            setMountPath(PackageHelper.getSdDir(cid));
15283        }
15284
15285        void createCopyFile() {
15286            cid = mInstallerService.allocateExternalStageCidLegacy();
15287        }
15288
15289        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15290            if (origin.staged && origin.cid != null) {
15291                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15292                cid = origin.cid;
15293                setMountPath(PackageHelper.getSdDir(cid));
15294                return PackageManager.INSTALL_SUCCEEDED;
15295            }
15296
15297            if (temp) {
15298                createCopyFile();
15299            } else {
15300                /*
15301                 * Pre-emptively destroy the container since it's destroyed if
15302                 * copying fails due to it existing anyway.
15303                 */
15304                PackageHelper.destroySdDir(cid);
15305            }
15306
15307            final String newMountPath = imcs.copyPackageToContainer(
15308                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15309                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15310
15311            if (newMountPath != null) {
15312                setMountPath(newMountPath);
15313                return PackageManager.INSTALL_SUCCEEDED;
15314            } else {
15315                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15316            }
15317        }
15318
15319        @Override
15320        String getCodePath() {
15321            return packagePath;
15322        }
15323
15324        @Override
15325        String getResourcePath() {
15326            return resourcePath;
15327        }
15328
15329        int doPreInstall(int status) {
15330            if (status != PackageManager.INSTALL_SUCCEEDED) {
15331                // Destroy container
15332                PackageHelper.destroySdDir(cid);
15333            } else {
15334                boolean mounted = PackageHelper.isContainerMounted(cid);
15335                if (!mounted) {
15336                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15337                            Process.SYSTEM_UID);
15338                    if (newMountPath != null) {
15339                        setMountPath(newMountPath);
15340                    } else {
15341                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15342                    }
15343                }
15344            }
15345            return status;
15346        }
15347
15348        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15349            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15350            String newMountPath = null;
15351            if (PackageHelper.isContainerMounted(cid)) {
15352                // Unmount the container
15353                if (!PackageHelper.unMountSdDir(cid)) {
15354                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15355                    return false;
15356                }
15357            }
15358            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15359                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15360                        " which might be stale. Will try to clean up.");
15361                // Clean up the stale container and proceed to recreate.
15362                if (!PackageHelper.destroySdDir(newCacheId)) {
15363                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15364                    return false;
15365                }
15366                // Successfully cleaned up stale container. Try to rename again.
15367                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15368                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15369                            + " inspite of cleaning it up.");
15370                    return false;
15371                }
15372            }
15373            if (!PackageHelper.isContainerMounted(newCacheId)) {
15374                Slog.w(TAG, "Mounting container " + newCacheId);
15375                newMountPath = PackageHelper.mountSdDir(newCacheId,
15376                        getEncryptKey(), Process.SYSTEM_UID);
15377            } else {
15378                newMountPath = PackageHelper.getSdDir(newCacheId);
15379            }
15380            if (newMountPath == null) {
15381                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15382                return false;
15383            }
15384            Log.i(TAG, "Succesfully renamed " + cid +
15385                    " to " + newCacheId +
15386                    " at new path: " + newMountPath);
15387            cid = newCacheId;
15388
15389            final File beforeCodeFile = new File(packagePath);
15390            setMountPath(newMountPath);
15391            final File afterCodeFile = new File(packagePath);
15392
15393            // Reflect the rename in scanned details
15394            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15395            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15396                    afterCodeFile, pkg.baseCodePath));
15397            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15398                    afterCodeFile, pkg.splitCodePaths));
15399
15400            // Reflect the rename in app info
15401            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15402            pkg.setApplicationInfoCodePath(pkg.codePath);
15403            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15404            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15405            pkg.setApplicationInfoResourcePath(pkg.codePath);
15406            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15407            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15408
15409            return true;
15410        }
15411
15412        private void setMountPath(String mountPath) {
15413            final File mountFile = new File(mountPath);
15414
15415            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15416            if (monolithicFile.exists()) {
15417                packagePath = monolithicFile.getAbsolutePath();
15418                if (isFwdLocked()) {
15419                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15420                } else {
15421                    resourcePath = packagePath;
15422                }
15423            } else {
15424                packagePath = mountFile.getAbsolutePath();
15425                resourcePath = packagePath;
15426            }
15427        }
15428
15429        int doPostInstall(int status, int uid) {
15430            if (status != PackageManager.INSTALL_SUCCEEDED) {
15431                cleanUp();
15432            } else {
15433                final int groupOwner;
15434                final String protectedFile;
15435                if (isFwdLocked()) {
15436                    groupOwner = UserHandle.getSharedAppGid(uid);
15437                    protectedFile = RES_FILE_NAME;
15438                } else {
15439                    groupOwner = -1;
15440                    protectedFile = null;
15441                }
15442
15443                if (uid < Process.FIRST_APPLICATION_UID
15444                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15445                    Slog.e(TAG, "Failed to finalize " + cid);
15446                    PackageHelper.destroySdDir(cid);
15447                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15448                }
15449
15450                boolean mounted = PackageHelper.isContainerMounted(cid);
15451                if (!mounted) {
15452                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15453                }
15454            }
15455            return status;
15456        }
15457
15458        private void cleanUp() {
15459            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15460
15461            // Destroy secure container
15462            PackageHelper.destroySdDir(cid);
15463        }
15464
15465        private List<String> getAllCodePaths() {
15466            final File codeFile = new File(getCodePath());
15467            if (codeFile != null && codeFile.exists()) {
15468                try {
15469                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15470                    return pkg.getAllCodePaths();
15471                } catch (PackageParserException e) {
15472                    // Ignored; we tried our best
15473                }
15474            }
15475            return Collections.EMPTY_LIST;
15476        }
15477
15478        void cleanUpResourcesLI() {
15479            // Enumerate all code paths before deleting
15480            cleanUpResourcesLI(getAllCodePaths());
15481        }
15482
15483        private void cleanUpResourcesLI(List<String> allCodePaths) {
15484            cleanUp();
15485            removeDexFiles(allCodePaths, instructionSets);
15486        }
15487
15488        String getPackageName() {
15489            return getAsecPackageName(cid);
15490        }
15491
15492        boolean doPostDeleteLI(boolean delete) {
15493            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15494            final List<String> allCodePaths = getAllCodePaths();
15495            boolean mounted = PackageHelper.isContainerMounted(cid);
15496            if (mounted) {
15497                // Unmount first
15498                if (PackageHelper.unMountSdDir(cid)) {
15499                    mounted = false;
15500                }
15501            }
15502            if (!mounted && delete) {
15503                cleanUpResourcesLI(allCodePaths);
15504            }
15505            return !mounted;
15506        }
15507
15508        @Override
15509        int doPreCopy() {
15510            if (isFwdLocked()) {
15511                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15512                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15513                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15514                }
15515            }
15516
15517            return PackageManager.INSTALL_SUCCEEDED;
15518        }
15519
15520        @Override
15521        int doPostCopy(int uid) {
15522            if (isFwdLocked()) {
15523                if (uid < Process.FIRST_APPLICATION_UID
15524                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15525                                RES_FILE_NAME)) {
15526                    Slog.e(TAG, "Failed to finalize " + cid);
15527                    PackageHelper.destroySdDir(cid);
15528                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15529                }
15530            }
15531
15532            return PackageManager.INSTALL_SUCCEEDED;
15533        }
15534    }
15535
15536    /**
15537     * Logic to handle movement of existing installed applications.
15538     */
15539    class MoveInstallArgs extends InstallArgs {
15540        private File codeFile;
15541        private File resourceFile;
15542
15543        /** New install */
15544        MoveInstallArgs(InstallParams params) {
15545            super(params.origin, params.move, params.observer, params.installFlags,
15546                    params.installerPackageName, params.volumeUuid,
15547                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15548                    params.grantedRuntimePermissions,
15549                    params.traceMethod, params.traceCookie, params.certificates,
15550                    params.installReason);
15551        }
15552
15553        int copyApk(IMediaContainerService imcs, boolean temp) {
15554            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15555                    + move.fromUuid + " to " + move.toUuid);
15556            synchronized (mInstaller) {
15557                try {
15558                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15559                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15560                } catch (InstallerException e) {
15561                    Slog.w(TAG, "Failed to move app", e);
15562                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15563                }
15564            }
15565
15566            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15567            resourceFile = codeFile;
15568            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15569
15570            return PackageManager.INSTALL_SUCCEEDED;
15571        }
15572
15573        int doPreInstall(int status) {
15574            if (status != PackageManager.INSTALL_SUCCEEDED) {
15575                cleanUp(move.toUuid);
15576            }
15577            return status;
15578        }
15579
15580        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15581            if (status != PackageManager.INSTALL_SUCCEEDED) {
15582                cleanUp(move.toUuid);
15583                return false;
15584            }
15585
15586            // Reflect the move in app info
15587            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15588            pkg.setApplicationInfoCodePath(pkg.codePath);
15589            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15590            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15591            pkg.setApplicationInfoResourcePath(pkg.codePath);
15592            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15593            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15594
15595            return true;
15596        }
15597
15598        int doPostInstall(int status, int uid) {
15599            if (status == PackageManager.INSTALL_SUCCEEDED) {
15600                cleanUp(move.fromUuid);
15601            } else {
15602                cleanUp(move.toUuid);
15603            }
15604            return status;
15605        }
15606
15607        @Override
15608        String getCodePath() {
15609            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15610        }
15611
15612        @Override
15613        String getResourcePath() {
15614            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15615        }
15616
15617        private boolean cleanUp(String volumeUuid) {
15618            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15619                    move.dataAppName);
15620            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15621            final int[] userIds = sUserManager.getUserIds();
15622            synchronized (mInstallLock) {
15623                // Clean up both app data and code
15624                // All package moves are frozen until finished
15625                for (int userId : userIds) {
15626                    try {
15627                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15628                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15629                    } catch (InstallerException e) {
15630                        Slog.w(TAG, String.valueOf(e));
15631                    }
15632                }
15633                removeCodePathLI(codeFile);
15634            }
15635            return true;
15636        }
15637
15638        void cleanUpResourcesLI() {
15639            throw new UnsupportedOperationException();
15640        }
15641
15642        boolean doPostDeleteLI(boolean delete) {
15643            throw new UnsupportedOperationException();
15644        }
15645    }
15646
15647    static String getAsecPackageName(String packageCid) {
15648        int idx = packageCid.lastIndexOf("-");
15649        if (idx == -1) {
15650            return packageCid;
15651        }
15652        return packageCid.substring(0, idx);
15653    }
15654
15655    // Utility method used to create code paths based on package name and available index.
15656    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15657        String idxStr = "";
15658        int idx = 1;
15659        // Fall back to default value of idx=1 if prefix is not
15660        // part of oldCodePath
15661        if (oldCodePath != null) {
15662            String subStr = oldCodePath;
15663            // Drop the suffix right away
15664            if (suffix != null && subStr.endsWith(suffix)) {
15665                subStr = subStr.substring(0, subStr.length() - suffix.length());
15666            }
15667            // If oldCodePath already contains prefix find out the
15668            // ending index to either increment or decrement.
15669            int sidx = subStr.lastIndexOf(prefix);
15670            if (sidx != -1) {
15671                subStr = subStr.substring(sidx + prefix.length());
15672                if (subStr != null) {
15673                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15674                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15675                    }
15676                    try {
15677                        idx = Integer.parseInt(subStr);
15678                        if (idx <= 1) {
15679                            idx++;
15680                        } else {
15681                            idx--;
15682                        }
15683                    } catch(NumberFormatException e) {
15684                    }
15685                }
15686            }
15687        }
15688        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15689        return prefix + idxStr;
15690    }
15691
15692    private File getNextCodePath(File targetDir, String packageName) {
15693        File result;
15694        SecureRandom random = new SecureRandom();
15695        byte[] bytes = new byte[16];
15696        do {
15697            random.nextBytes(bytes);
15698            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15699            result = new File(targetDir, packageName + "-" + suffix);
15700        } while (result.exists());
15701        return result;
15702    }
15703
15704    // Utility method that returns the relative package path with respect
15705    // to the installation directory. Like say for /data/data/com.test-1.apk
15706    // string com.test-1 is returned.
15707    static String deriveCodePathName(String codePath) {
15708        if (codePath == null) {
15709            return null;
15710        }
15711        final File codeFile = new File(codePath);
15712        final String name = codeFile.getName();
15713        if (codeFile.isDirectory()) {
15714            return name;
15715        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15716            final int lastDot = name.lastIndexOf('.');
15717            return name.substring(0, lastDot);
15718        } else {
15719            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15720            return null;
15721        }
15722    }
15723
15724    static class PackageInstalledInfo {
15725        String name;
15726        int uid;
15727        // The set of users that originally had this package installed.
15728        int[] origUsers;
15729        // The set of users that now have this package installed.
15730        int[] newUsers;
15731        PackageParser.Package pkg;
15732        int returnCode;
15733        String returnMsg;
15734        PackageRemovedInfo removedInfo;
15735        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15736
15737        public void setError(int code, String msg) {
15738            setReturnCode(code);
15739            setReturnMessage(msg);
15740            Slog.w(TAG, msg);
15741        }
15742
15743        public void setError(String msg, PackageParserException e) {
15744            setReturnCode(e.error);
15745            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15746            Slog.w(TAG, msg, e);
15747        }
15748
15749        public void setError(String msg, PackageManagerException e) {
15750            returnCode = e.error;
15751            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15752            Slog.w(TAG, msg, e);
15753        }
15754
15755        public void setReturnCode(int returnCode) {
15756            this.returnCode = returnCode;
15757            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15758            for (int i = 0; i < childCount; i++) {
15759                addedChildPackages.valueAt(i).returnCode = returnCode;
15760            }
15761        }
15762
15763        private void setReturnMessage(String returnMsg) {
15764            this.returnMsg = returnMsg;
15765            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15766            for (int i = 0; i < childCount; i++) {
15767                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15768            }
15769        }
15770
15771        // In some error cases we want to convey more info back to the observer
15772        String origPackage;
15773        String origPermission;
15774    }
15775
15776    /*
15777     * Install a non-existing package.
15778     */
15779    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15780            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15781            PackageInstalledInfo res, int installReason) {
15782        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15783
15784        // Remember this for later, in case we need to rollback this install
15785        String pkgName = pkg.packageName;
15786
15787        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15788
15789        synchronized(mPackages) {
15790            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15791            if (renamedPackage != null) {
15792                // A package with the same name is already installed, though
15793                // it has been renamed to an older name.  The package we
15794                // are trying to install should be installed as an update to
15795                // the existing one, but that has not been requested, so bail.
15796                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15797                        + " without first uninstalling package running as "
15798                        + renamedPackage);
15799                return;
15800            }
15801            if (mPackages.containsKey(pkgName)) {
15802                // Don't allow installation over an existing package with the same name.
15803                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15804                        + " without first uninstalling.");
15805                return;
15806            }
15807        }
15808
15809        try {
15810            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15811                    System.currentTimeMillis(), user);
15812
15813            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15814
15815            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15816                prepareAppDataAfterInstallLIF(newPackage);
15817
15818            } else {
15819                // Remove package from internal structures, but keep around any
15820                // data that might have already existed
15821                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15822                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15823            }
15824        } catch (PackageManagerException e) {
15825            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15826        }
15827
15828        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15829    }
15830
15831    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15832        // Can't rotate keys during boot or if sharedUser.
15833        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15834                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15835            return false;
15836        }
15837        // app is using upgradeKeySets; make sure all are valid
15838        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15839        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15840        for (int i = 0; i < upgradeKeySets.length; i++) {
15841            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15842                Slog.wtf(TAG, "Package "
15843                         + (oldPs.name != null ? oldPs.name : "<null>")
15844                         + " contains upgrade-key-set reference to unknown key-set: "
15845                         + upgradeKeySets[i]
15846                         + " reverting to signatures check.");
15847                return false;
15848            }
15849        }
15850        return true;
15851    }
15852
15853    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15854        // Upgrade keysets are being used.  Determine if new package has a superset of the
15855        // required keys.
15856        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15857        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15858        for (int i = 0; i < upgradeKeySets.length; i++) {
15859            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15860            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15861                return true;
15862            }
15863        }
15864        return false;
15865    }
15866
15867    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15868        try (DigestInputStream digestStream =
15869                new DigestInputStream(new FileInputStream(file), digest)) {
15870            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15871        }
15872    }
15873
15874    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15875            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15876            int installReason) {
15877        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15878
15879        final PackageParser.Package oldPackage;
15880        final String pkgName = pkg.packageName;
15881        final int[] allUsers;
15882        final int[] installedUsers;
15883
15884        synchronized(mPackages) {
15885            oldPackage = mPackages.get(pkgName);
15886            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15887
15888            // don't allow upgrade to target a release SDK from a pre-release SDK
15889            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15890                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15891            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15892                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15893            if (oldTargetsPreRelease
15894                    && !newTargetsPreRelease
15895                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15896                Slog.w(TAG, "Can't install package targeting released sdk");
15897                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15898                return;
15899            }
15900
15901            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15902
15903            // don't allow an upgrade from full to ephemeral
15904            if (isInstantApp && !ps.getInstantApp(user.getIdentifier())) {
15905                // can't downgrade from full to instant
15906                Slog.w(TAG, "Can't replace app with instant app: " + pkgName);
15907                res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15908                return;
15909            }
15910
15911            // verify signatures are valid
15912            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15913                if (!checkUpgradeKeySetLP(ps, pkg)) {
15914                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15915                            "New package not signed by keys specified by upgrade-keysets: "
15916                                    + pkgName);
15917                    return;
15918                }
15919            } else {
15920                // default to original signature matching
15921                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15922                        != PackageManager.SIGNATURE_MATCH) {
15923                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15924                            "New package has a different signature: " + pkgName);
15925                    return;
15926                }
15927            }
15928
15929            // don't allow a system upgrade unless the upgrade hash matches
15930            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15931                byte[] digestBytes = null;
15932                try {
15933                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15934                    updateDigest(digest, new File(pkg.baseCodePath));
15935                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15936                        for (String path : pkg.splitCodePaths) {
15937                            updateDigest(digest, new File(path));
15938                        }
15939                    }
15940                    digestBytes = digest.digest();
15941                } catch (NoSuchAlgorithmException | IOException e) {
15942                    res.setError(INSTALL_FAILED_INVALID_APK,
15943                            "Could not compute hash: " + pkgName);
15944                    return;
15945                }
15946                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15947                    res.setError(INSTALL_FAILED_INVALID_APK,
15948                            "New package fails restrict-update check: " + pkgName);
15949                    return;
15950                }
15951                // retain upgrade restriction
15952                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15953            }
15954
15955            // Check for shared user id changes
15956            String invalidPackageName =
15957                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15958            if (invalidPackageName != null) {
15959                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15960                        "Package " + invalidPackageName + " tried to change user "
15961                                + oldPackage.mSharedUserId);
15962                return;
15963            }
15964
15965            // In case of rollback, remember per-user/profile install state
15966            allUsers = sUserManager.getUserIds();
15967            installedUsers = ps.queryInstalledUsers(allUsers, true);
15968        }
15969
15970        // Update what is removed
15971        res.removedInfo = new PackageRemovedInfo();
15972        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15973        res.removedInfo.removedPackage = oldPackage.packageName;
15974        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15975        res.removedInfo.isUpdate = true;
15976        res.removedInfo.origUsers = installedUsers;
15977        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15978        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15979        for (int i = 0; i < installedUsers.length; i++) {
15980            final int userId = installedUsers[i];
15981            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15982        }
15983
15984        final int childCount = (oldPackage.childPackages != null)
15985                ? oldPackage.childPackages.size() : 0;
15986        for (int i = 0; i < childCount; i++) {
15987            boolean childPackageUpdated = false;
15988            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15989            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15990            if (res.addedChildPackages != null) {
15991                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15992                if (childRes != null) {
15993                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15994                    childRes.removedInfo.removedPackage = childPkg.packageName;
15995                    childRes.removedInfo.isUpdate = true;
15996                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15997                    childPackageUpdated = true;
15998                }
15999            }
16000            if (!childPackageUpdated) {
16001                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
16002                childRemovedRes.removedPackage = childPkg.packageName;
16003                childRemovedRes.isUpdate = false;
16004                childRemovedRes.dataRemoved = true;
16005                synchronized (mPackages) {
16006                    if (childPs != null) {
16007                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16008                    }
16009                }
16010                if (res.removedInfo.removedChildPackages == null) {
16011                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16012                }
16013                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16014            }
16015        }
16016
16017        boolean sysPkg = (isSystemApp(oldPackage));
16018        if (sysPkg) {
16019            // Set the system/privileged flags as needed
16020            final boolean privileged =
16021                    (oldPackage.applicationInfo.privateFlags
16022                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16023            final int systemPolicyFlags = policyFlags
16024                    | PackageParser.PARSE_IS_SYSTEM
16025                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16026
16027            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16028                    user, allUsers, installerPackageName, res, installReason);
16029        } else {
16030            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16031                    user, allUsers, installerPackageName, res, installReason);
16032        }
16033    }
16034
16035    public List<String> getPreviousCodePaths(String packageName) {
16036        final PackageSetting ps = mSettings.mPackages.get(packageName);
16037        final List<String> result = new ArrayList<String>();
16038        if (ps != null && ps.oldCodePaths != null) {
16039            result.addAll(ps.oldCodePaths);
16040        }
16041        return result;
16042    }
16043
16044    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16045            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16046            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16047            int installReason) {
16048        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16049                + deletedPackage);
16050
16051        String pkgName = deletedPackage.packageName;
16052        boolean deletedPkg = true;
16053        boolean addedPkg = false;
16054        boolean updatedSettings = false;
16055        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16056        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16057                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16058
16059        final long origUpdateTime = (pkg.mExtras != null)
16060                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16061
16062        // First delete the existing package while retaining the data directory
16063        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16064                res.removedInfo, true, pkg)) {
16065            // If the existing package wasn't successfully deleted
16066            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16067            deletedPkg = false;
16068        } else {
16069            // Successfully deleted the old package; proceed with replace.
16070
16071            // If deleted package lived in a container, give users a chance to
16072            // relinquish resources before killing.
16073            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16074                if (DEBUG_INSTALL) {
16075                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16076                }
16077                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16078                final ArrayList<String> pkgList = new ArrayList<String>(1);
16079                pkgList.add(deletedPackage.applicationInfo.packageName);
16080                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16081            }
16082
16083            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16084                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16085            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16086
16087            try {
16088                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16089                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16090                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16091                        installReason);
16092
16093                // Update the in-memory copy of the previous code paths.
16094                PackageSetting ps = mSettings.mPackages.get(pkgName);
16095                if (!killApp) {
16096                    if (ps.oldCodePaths == null) {
16097                        ps.oldCodePaths = new ArraySet<>();
16098                    }
16099                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16100                    if (deletedPackage.splitCodePaths != null) {
16101                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16102                    }
16103                } else {
16104                    ps.oldCodePaths = null;
16105                }
16106                if (ps.childPackageNames != null) {
16107                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16108                        final String childPkgName = ps.childPackageNames.get(i);
16109                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16110                        childPs.oldCodePaths = ps.oldCodePaths;
16111                    }
16112                }
16113                // set instant app status, but, only if it's explicitly specified
16114                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16115                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16116                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16117                prepareAppDataAfterInstallLIF(newPackage);
16118                addedPkg = true;
16119            } catch (PackageManagerException e) {
16120                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16121            }
16122        }
16123
16124        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16125            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16126
16127            // Revert all internal state mutations and added folders for the failed install
16128            if (addedPkg) {
16129                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16130                        res.removedInfo, true, null);
16131            }
16132
16133            // Restore the old package
16134            if (deletedPkg) {
16135                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16136                File restoreFile = new File(deletedPackage.codePath);
16137                // Parse old package
16138                boolean oldExternal = isExternal(deletedPackage);
16139                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16140                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16141                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16142                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16143                try {
16144                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16145                            null);
16146                } catch (PackageManagerException e) {
16147                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16148                            + e.getMessage());
16149                    return;
16150                }
16151
16152                synchronized (mPackages) {
16153                    // Ensure the installer package name up to date
16154                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16155
16156                    // Update permissions for restored package
16157                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16158
16159                    mSettings.writeLPr();
16160                }
16161
16162                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16163            }
16164        } else {
16165            synchronized (mPackages) {
16166                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16167                if (ps != null) {
16168                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16169                    if (res.removedInfo.removedChildPackages != null) {
16170                        final int childCount = res.removedInfo.removedChildPackages.size();
16171                        // Iterate in reverse as we may modify the collection
16172                        for (int i = childCount - 1; i >= 0; i--) {
16173                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16174                            if (res.addedChildPackages.containsKey(childPackageName)) {
16175                                res.removedInfo.removedChildPackages.removeAt(i);
16176                            } else {
16177                                PackageRemovedInfo childInfo = res.removedInfo
16178                                        .removedChildPackages.valueAt(i);
16179                                childInfo.removedForAllUsers = mPackages.get(
16180                                        childInfo.removedPackage) == null;
16181                            }
16182                        }
16183                    }
16184                }
16185            }
16186        }
16187    }
16188
16189    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16190            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16191            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16192            int installReason) {
16193        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16194                + ", old=" + deletedPackage);
16195
16196        final boolean disabledSystem;
16197
16198        // Remove existing system package
16199        removePackageLI(deletedPackage, true);
16200
16201        synchronized (mPackages) {
16202            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16203        }
16204        if (!disabledSystem) {
16205            // We didn't need to disable the .apk as a current system package,
16206            // which means we are replacing another update that is already
16207            // installed.  We need to make sure to delete the older one's .apk.
16208            res.removedInfo.args = createInstallArgsForExisting(0,
16209                    deletedPackage.applicationInfo.getCodePath(),
16210                    deletedPackage.applicationInfo.getResourcePath(),
16211                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16212        } else {
16213            res.removedInfo.args = null;
16214        }
16215
16216        // Successfully disabled the old package. Now proceed with re-installation
16217        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16218                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16219        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16220
16221        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16222        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16223                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16224
16225        PackageParser.Package newPackage = null;
16226        try {
16227            // Add the package to the internal data structures
16228            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16229
16230            // Set the update and install times
16231            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16232            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16233                    System.currentTimeMillis());
16234
16235            // Update the package dynamic state if succeeded
16236            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16237                // Now that the install succeeded make sure we remove data
16238                // directories for any child package the update removed.
16239                final int deletedChildCount = (deletedPackage.childPackages != null)
16240                        ? deletedPackage.childPackages.size() : 0;
16241                final int newChildCount = (newPackage.childPackages != null)
16242                        ? newPackage.childPackages.size() : 0;
16243                for (int i = 0; i < deletedChildCount; i++) {
16244                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16245                    boolean childPackageDeleted = true;
16246                    for (int j = 0; j < newChildCount; j++) {
16247                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16248                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16249                            childPackageDeleted = false;
16250                            break;
16251                        }
16252                    }
16253                    if (childPackageDeleted) {
16254                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16255                                deletedChildPkg.packageName);
16256                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16257                            PackageRemovedInfo removedChildRes = res.removedInfo
16258                                    .removedChildPackages.get(deletedChildPkg.packageName);
16259                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16260                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16261                        }
16262                    }
16263                }
16264
16265                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16266                        installReason);
16267                prepareAppDataAfterInstallLIF(newPackage);
16268            }
16269        } catch (PackageManagerException e) {
16270            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16271            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16272        }
16273
16274        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16275            // Re installation failed. Restore old information
16276            // Remove new pkg information
16277            if (newPackage != null) {
16278                removeInstalledPackageLI(newPackage, true);
16279            }
16280            // Add back the old system package
16281            try {
16282                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16283            } catch (PackageManagerException e) {
16284                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16285            }
16286
16287            synchronized (mPackages) {
16288                if (disabledSystem) {
16289                    enableSystemPackageLPw(deletedPackage);
16290                }
16291
16292                // Ensure the installer package name up to date
16293                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16294
16295                // Update permissions for restored package
16296                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16297
16298                mSettings.writeLPr();
16299            }
16300
16301            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16302                    + " after failed upgrade");
16303        }
16304    }
16305
16306    /**
16307     * Checks whether the parent or any of the child packages have a change shared
16308     * user. For a package to be a valid update the shred users of the parent and
16309     * the children should match. We may later support changing child shared users.
16310     * @param oldPkg The updated package.
16311     * @param newPkg The update package.
16312     * @return The shared user that change between the versions.
16313     */
16314    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16315            PackageParser.Package newPkg) {
16316        // Check parent shared user
16317        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16318            return newPkg.packageName;
16319        }
16320        // Check child shared users
16321        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16322        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16323        for (int i = 0; i < newChildCount; i++) {
16324            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16325            // If this child was present, did it have the same shared user?
16326            for (int j = 0; j < oldChildCount; j++) {
16327                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16328                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16329                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16330                    return newChildPkg.packageName;
16331                }
16332            }
16333        }
16334        return null;
16335    }
16336
16337    private void removeNativeBinariesLI(PackageSetting ps) {
16338        // Remove the lib path for the parent package
16339        if (ps != null) {
16340            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16341            // Remove the lib path for the child packages
16342            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16343            for (int i = 0; i < childCount; i++) {
16344                PackageSetting childPs = null;
16345                synchronized (mPackages) {
16346                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16347                }
16348                if (childPs != null) {
16349                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16350                            .legacyNativeLibraryPathString);
16351                }
16352            }
16353        }
16354    }
16355
16356    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16357        // Enable the parent package
16358        mSettings.enableSystemPackageLPw(pkg.packageName);
16359        // Enable the child packages
16360        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16361        for (int i = 0; i < childCount; i++) {
16362            PackageParser.Package childPkg = pkg.childPackages.get(i);
16363            mSettings.enableSystemPackageLPw(childPkg.packageName);
16364        }
16365    }
16366
16367    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16368            PackageParser.Package newPkg) {
16369        // Disable the parent package (parent always replaced)
16370        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16371        // Disable the child packages
16372        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16373        for (int i = 0; i < childCount; i++) {
16374            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16375            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16376            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16377        }
16378        return disabled;
16379    }
16380
16381    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16382            String installerPackageName) {
16383        // Enable the parent package
16384        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16385        // Enable the child packages
16386        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16387        for (int i = 0; i < childCount; i++) {
16388            PackageParser.Package childPkg = pkg.childPackages.get(i);
16389            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16390        }
16391    }
16392
16393    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16394        // Collect all used permissions in the UID
16395        ArraySet<String> usedPermissions = new ArraySet<>();
16396        final int packageCount = su.packages.size();
16397        for (int i = 0; i < packageCount; i++) {
16398            PackageSetting ps = su.packages.valueAt(i);
16399            if (ps.pkg == null) {
16400                continue;
16401            }
16402            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16403            for (int j = 0; j < requestedPermCount; j++) {
16404                String permission = ps.pkg.requestedPermissions.get(j);
16405                BasePermission bp = mSettings.mPermissions.get(permission);
16406                if (bp != null) {
16407                    usedPermissions.add(permission);
16408                }
16409            }
16410        }
16411
16412        PermissionsState permissionsState = su.getPermissionsState();
16413        // Prune install permissions
16414        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16415        final int installPermCount = installPermStates.size();
16416        for (int i = installPermCount - 1; i >= 0;  i--) {
16417            PermissionState permissionState = installPermStates.get(i);
16418            if (!usedPermissions.contains(permissionState.getName())) {
16419                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16420                if (bp != null) {
16421                    permissionsState.revokeInstallPermission(bp);
16422                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16423                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16424                }
16425            }
16426        }
16427
16428        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16429
16430        // Prune runtime permissions
16431        for (int userId : allUserIds) {
16432            List<PermissionState> runtimePermStates = permissionsState
16433                    .getRuntimePermissionStates(userId);
16434            final int runtimePermCount = runtimePermStates.size();
16435            for (int i = runtimePermCount - 1; i >= 0; i--) {
16436                PermissionState permissionState = runtimePermStates.get(i);
16437                if (!usedPermissions.contains(permissionState.getName())) {
16438                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16439                    if (bp != null) {
16440                        permissionsState.revokeRuntimePermission(bp, userId);
16441                        permissionsState.updatePermissionFlags(bp, userId,
16442                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16443                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16444                                runtimePermissionChangedUserIds, userId);
16445                    }
16446                }
16447            }
16448        }
16449
16450        return runtimePermissionChangedUserIds;
16451    }
16452
16453    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16454            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16455        // Update the parent package setting
16456        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16457                res, user, installReason);
16458        // Update the child packages setting
16459        final int childCount = (newPackage.childPackages != null)
16460                ? newPackage.childPackages.size() : 0;
16461        for (int i = 0; i < childCount; i++) {
16462            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16463            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16464            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16465                    childRes.origUsers, childRes, user, installReason);
16466        }
16467    }
16468
16469    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16470            String installerPackageName, int[] allUsers, int[] installedForUsers,
16471            PackageInstalledInfo res, UserHandle user, int installReason) {
16472        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16473
16474        String pkgName = newPackage.packageName;
16475        synchronized (mPackages) {
16476            //write settings. the installStatus will be incomplete at this stage.
16477            //note that the new package setting would have already been
16478            //added to mPackages. It hasn't been persisted yet.
16479            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16480            // TODO: Remove this write? It's also written at the end of this method
16481            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16482            mSettings.writeLPr();
16483            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16484        }
16485
16486        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16487        synchronized (mPackages) {
16488            updatePermissionsLPw(newPackage.packageName, newPackage,
16489                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16490                            ? UPDATE_PERMISSIONS_ALL : 0));
16491            // For system-bundled packages, we assume that installing an upgraded version
16492            // of the package implies that the user actually wants to run that new code,
16493            // so we enable the package.
16494            PackageSetting ps = mSettings.mPackages.get(pkgName);
16495            final int userId = user.getIdentifier();
16496            if (ps != null) {
16497                if (isSystemApp(newPackage)) {
16498                    if (DEBUG_INSTALL) {
16499                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16500                    }
16501                    // Enable system package for requested users
16502                    if (res.origUsers != null) {
16503                        for (int origUserId : res.origUsers) {
16504                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16505                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16506                                        origUserId, installerPackageName);
16507                            }
16508                        }
16509                    }
16510                    // Also convey the prior install/uninstall state
16511                    if (allUsers != null && installedForUsers != null) {
16512                        for (int currentUserId : allUsers) {
16513                            final boolean installed = ArrayUtils.contains(
16514                                    installedForUsers, currentUserId);
16515                            if (DEBUG_INSTALL) {
16516                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16517                            }
16518                            ps.setInstalled(installed, currentUserId);
16519                        }
16520                        // these install state changes will be persisted in the
16521                        // upcoming call to mSettings.writeLPr().
16522                    }
16523                }
16524                // It's implied that when a user requests installation, they want the app to be
16525                // installed and enabled.
16526                if (userId != UserHandle.USER_ALL) {
16527                    ps.setInstalled(true, userId);
16528                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16529                }
16530
16531                // When replacing an existing package, preserve the original install reason for all
16532                // users that had the package installed before.
16533                final Set<Integer> previousUserIds = new ArraySet<>();
16534                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16535                    final int installReasonCount = res.removedInfo.installReasons.size();
16536                    for (int i = 0; i < installReasonCount; i++) {
16537                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16538                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16539                        ps.setInstallReason(previousInstallReason, previousUserId);
16540                        previousUserIds.add(previousUserId);
16541                    }
16542                }
16543
16544                // Set install reason for users that are having the package newly installed.
16545                if (userId == UserHandle.USER_ALL) {
16546                    for (int currentUserId : sUserManager.getUserIds()) {
16547                        if (!previousUserIds.contains(currentUserId)) {
16548                            ps.setInstallReason(installReason, currentUserId);
16549                        }
16550                    }
16551                } else if (!previousUserIds.contains(userId)) {
16552                    ps.setInstallReason(installReason, userId);
16553                }
16554                mSettings.writeKernelMappingLPr(ps);
16555            }
16556            res.name = pkgName;
16557            res.uid = newPackage.applicationInfo.uid;
16558            res.pkg = newPackage;
16559            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16560            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16561            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16562            //to update install status
16563            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16564            mSettings.writeLPr();
16565            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16566        }
16567
16568        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16569    }
16570
16571    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16572        try {
16573            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16574            installPackageLI(args, res);
16575        } finally {
16576            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16577        }
16578    }
16579
16580    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16581        final int installFlags = args.installFlags;
16582        final String installerPackageName = args.installerPackageName;
16583        final String volumeUuid = args.volumeUuid;
16584        final File tmpPackageFile = new File(args.getCodePath());
16585        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16586        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16587                || (args.volumeUuid != null));
16588        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16589        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16590        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16591        boolean replace = false;
16592        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16593        if (args.move != null) {
16594            // moving a complete application; perform an initial scan on the new install location
16595            scanFlags |= SCAN_INITIAL;
16596        }
16597        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16598            scanFlags |= SCAN_DONT_KILL_APP;
16599        }
16600        if (instantApp) {
16601            scanFlags |= SCAN_AS_INSTANT_APP;
16602        }
16603        if (fullApp) {
16604            scanFlags |= SCAN_AS_FULL_APP;
16605        }
16606
16607        // Result object to be returned
16608        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16609
16610        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16611
16612        // Sanity check
16613        if (instantApp && (forwardLocked || onExternal)) {
16614            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16615                    + " external=" + onExternal);
16616            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16617            return;
16618        }
16619
16620        // Retrieve PackageSettings and parse package
16621        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16622                | PackageParser.PARSE_ENFORCE_CODE
16623                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16624                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16625                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16626                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16627        PackageParser pp = new PackageParser();
16628        pp.setSeparateProcesses(mSeparateProcesses);
16629        pp.setDisplayMetrics(mMetrics);
16630
16631        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16632        final PackageParser.Package pkg;
16633        try {
16634            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16635        } catch (PackageParserException e) {
16636            res.setError("Failed parse during installPackageLI", e);
16637            return;
16638        } finally {
16639            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16640        }
16641
16642//        // Ephemeral apps must have target SDK >= O.
16643//        // TODO: Update conditional and error message when O gets locked down
16644//        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16645//            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
16646//                    "Ephemeral apps must have target SDK version of at least O");
16647//            return;
16648//        }
16649
16650        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16651            // Static shared libraries have synthetic package names
16652            renameStaticSharedLibraryPackage(pkg);
16653
16654            // No static shared libs on external storage
16655            if (onExternal) {
16656                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16657                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16658                        "Packages declaring static-shared libs cannot be updated");
16659                return;
16660            }
16661        }
16662
16663        // If we are installing a clustered package add results for the children
16664        if (pkg.childPackages != null) {
16665            synchronized (mPackages) {
16666                final int childCount = pkg.childPackages.size();
16667                for (int i = 0; i < childCount; i++) {
16668                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16669                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16670                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16671                    childRes.pkg = childPkg;
16672                    childRes.name = childPkg.packageName;
16673                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16674                    if (childPs != null) {
16675                        childRes.origUsers = childPs.queryInstalledUsers(
16676                                sUserManager.getUserIds(), true);
16677                    }
16678                    if ((mPackages.containsKey(childPkg.packageName))) {
16679                        childRes.removedInfo = new PackageRemovedInfo();
16680                        childRes.removedInfo.removedPackage = childPkg.packageName;
16681                    }
16682                    if (res.addedChildPackages == null) {
16683                        res.addedChildPackages = new ArrayMap<>();
16684                    }
16685                    res.addedChildPackages.put(childPkg.packageName, childRes);
16686                }
16687            }
16688        }
16689
16690        // If package doesn't declare API override, mark that we have an install
16691        // time CPU ABI override.
16692        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16693            pkg.cpuAbiOverride = args.abiOverride;
16694        }
16695
16696        String pkgName = res.name = pkg.packageName;
16697        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16698            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16699                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16700                return;
16701            }
16702        }
16703
16704        try {
16705            // either use what we've been given or parse directly from the APK
16706            if (args.certificates != null) {
16707                try {
16708                    PackageParser.populateCertificates(pkg, args.certificates);
16709                } catch (PackageParserException e) {
16710                    // there was something wrong with the certificates we were given;
16711                    // try to pull them from the APK
16712                    PackageParser.collectCertificates(pkg, parseFlags);
16713                }
16714            } else {
16715                PackageParser.collectCertificates(pkg, parseFlags);
16716            }
16717        } catch (PackageParserException e) {
16718            res.setError("Failed collect during installPackageLI", e);
16719            return;
16720        }
16721
16722        // Get rid of all references to package scan path via parser.
16723        pp = null;
16724        String oldCodePath = null;
16725        boolean systemApp = false;
16726        synchronized (mPackages) {
16727            // Check if installing already existing package
16728            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16729                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16730                if (pkg.mOriginalPackages != null
16731                        && pkg.mOriginalPackages.contains(oldName)
16732                        && mPackages.containsKey(oldName)) {
16733                    // This package is derived from an original package,
16734                    // and this device has been updating from that original
16735                    // name.  We must continue using the original name, so
16736                    // rename the new package here.
16737                    pkg.setPackageName(oldName);
16738                    pkgName = pkg.packageName;
16739                    replace = true;
16740                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16741                            + oldName + " pkgName=" + pkgName);
16742                } else if (mPackages.containsKey(pkgName)) {
16743                    // This package, under its official name, already exists
16744                    // on the device; we should replace it.
16745                    replace = true;
16746                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16747                }
16748
16749                // Child packages are installed through the parent package
16750                if (pkg.parentPackage != null) {
16751                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16752                            "Package " + pkg.packageName + " is child of package "
16753                                    + pkg.parentPackage.parentPackage + ". Child packages "
16754                                    + "can be updated only through the parent package.");
16755                    return;
16756                }
16757
16758                if (replace) {
16759                    // Prevent apps opting out from runtime permissions
16760                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16761                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16762                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16763                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16764                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16765                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16766                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16767                                        + " doesn't support runtime permissions but the old"
16768                                        + " target SDK " + oldTargetSdk + " does.");
16769                        return;
16770                    }
16771
16772                    // Prevent installing of child packages
16773                    if (oldPackage.parentPackage != null) {
16774                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16775                                "Package " + pkg.packageName + " is child of package "
16776                                        + oldPackage.parentPackage + ". Child packages "
16777                                        + "can be updated only through the parent package.");
16778                        return;
16779                    }
16780                }
16781            }
16782
16783            PackageSetting ps = mSettings.mPackages.get(pkgName);
16784            if (ps != null) {
16785                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16786
16787                // Static shared libs have same package with different versions where
16788                // we internally use a synthetic package name to allow multiple versions
16789                // of the same package, therefore we need to compare signatures against
16790                // the package setting for the latest library version.
16791                PackageSetting signatureCheckPs = ps;
16792                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16793                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16794                    if (libraryEntry != null) {
16795                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16796                    }
16797                }
16798
16799                // Quick sanity check that we're signed correctly if updating;
16800                // we'll check this again later when scanning, but we want to
16801                // bail early here before tripping over redefined permissions.
16802                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16803                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16804                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16805                                + pkg.packageName + " upgrade keys do not match the "
16806                                + "previously installed version");
16807                        return;
16808                    }
16809                } else {
16810                    try {
16811                        verifySignaturesLP(signatureCheckPs, pkg);
16812                    } catch (PackageManagerException e) {
16813                        res.setError(e.error, e.getMessage());
16814                        return;
16815                    }
16816                }
16817
16818                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16819                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16820                    systemApp = (ps.pkg.applicationInfo.flags &
16821                            ApplicationInfo.FLAG_SYSTEM) != 0;
16822                }
16823                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16824            }
16825
16826            int N = pkg.permissions.size();
16827            for (int i = N-1; i >= 0; i--) {
16828                PackageParser.Permission perm = pkg.permissions.get(i);
16829                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16830
16831                // Don't allow anyone but the platform to define ephemeral permissions.
16832                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
16833                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16834                    Slog.w(TAG, "Package " + pkg.packageName
16835                            + " attempting to delcare ephemeral permission "
16836                            + perm.info.name + "; Removing ephemeral.");
16837                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
16838                }
16839                // Check whether the newly-scanned package wants to define an already-defined perm
16840                if (bp != null) {
16841                    // If the defining package is signed with our cert, it's okay.  This
16842                    // also includes the "updating the same package" case, of course.
16843                    // "updating same package" could also involve key-rotation.
16844                    final boolean sigsOk;
16845                    if (bp.sourcePackage.equals(pkg.packageName)
16846                            && (bp.packageSetting instanceof PackageSetting)
16847                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16848                                    scanFlags))) {
16849                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16850                    } else {
16851                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16852                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16853                    }
16854                    if (!sigsOk) {
16855                        // If the owning package is the system itself, we log but allow
16856                        // install to proceed; we fail the install on all other permission
16857                        // redefinitions.
16858                        if (!bp.sourcePackage.equals("android")) {
16859                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16860                                    + pkg.packageName + " attempting to redeclare permission "
16861                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16862                            res.origPermission = perm.info.name;
16863                            res.origPackage = bp.sourcePackage;
16864                            return;
16865                        } else {
16866                            Slog.w(TAG, "Package " + pkg.packageName
16867                                    + " attempting to redeclare system permission "
16868                                    + perm.info.name + "; ignoring new declaration");
16869                            pkg.permissions.remove(i);
16870                        }
16871                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16872                        // Prevent apps to change protection level to dangerous from any other
16873                        // type as this would allow a privilege escalation where an app adds a
16874                        // normal/signature permission in other app's group and later redefines
16875                        // it as dangerous leading to the group auto-grant.
16876                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16877                                == PermissionInfo.PROTECTION_DANGEROUS) {
16878                            if (bp != null && !bp.isRuntime()) {
16879                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16880                                        + "non-runtime permission " + perm.info.name
16881                                        + " to runtime; keeping old protection level");
16882                                perm.info.protectionLevel = bp.protectionLevel;
16883                            }
16884                        }
16885                    }
16886                }
16887            }
16888        }
16889
16890        if (systemApp) {
16891            if (onExternal) {
16892                // Abort update; system app can't be replaced with app on sdcard
16893                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16894                        "Cannot install updates to system apps on sdcard");
16895                return;
16896            } else if (instantApp) {
16897                // Abort update; system app can't be replaced with an instant app
16898                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16899                        "Cannot update a system app with an instant app");
16900                return;
16901            }
16902        }
16903
16904        if (args.move != null) {
16905            // We did an in-place move, so dex is ready to roll
16906            scanFlags |= SCAN_NO_DEX;
16907            scanFlags |= SCAN_MOVE;
16908
16909            synchronized (mPackages) {
16910                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16911                if (ps == null) {
16912                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16913                            "Missing settings for moved package " + pkgName);
16914                }
16915
16916                // We moved the entire application as-is, so bring over the
16917                // previously derived ABI information.
16918                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16919                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16920            }
16921
16922        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16923            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16924            scanFlags |= SCAN_NO_DEX;
16925
16926            try {
16927                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16928                    args.abiOverride : pkg.cpuAbiOverride);
16929                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16930                        true /*extractLibs*/, mAppLib32InstallDir);
16931            } catch (PackageManagerException pme) {
16932                Slog.e(TAG, "Error deriving application ABI", pme);
16933                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16934                return;
16935            }
16936
16937            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16938            // Do not run PackageDexOptimizer through the local performDexOpt
16939            // method because `pkg` may not be in `mPackages` yet.
16940            //
16941            // Also, don't fail application installs if the dexopt step fails.
16942            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16943                    null /* instructionSets */, false /* checkProfiles */,
16944                    getCompilerFilterForReason(REASON_INSTALL),
16945                    getOrCreateCompilerPackageStats(pkg));
16946            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16947
16948            // Notify BackgroundDexOptJobService that the package has been changed.
16949            // If this is an update of a package which used to fail to compile,
16950            // BDOS will remove it from its blacklist.
16951            // TODO: Layering violation
16952            BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName);
16953        }
16954
16955        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16956            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16957            return;
16958        }
16959
16960        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16961
16962        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16963                "installPackageLI")) {
16964            if (replace) {
16965                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16966                    // Static libs have a synthetic package name containing the version
16967                    // and cannot be updated as an update would get a new package name,
16968                    // unless this is the exact same version code which is useful for
16969                    // development.
16970                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16971                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16972                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16973                                + "static-shared libs cannot be updated");
16974                        return;
16975                    }
16976                }
16977                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16978                        installerPackageName, res, args.installReason);
16979            } else {
16980                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16981                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16982            }
16983        }
16984        synchronized (mPackages) {
16985            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16986            if (ps != null) {
16987                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16988            }
16989
16990            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16991            for (int i = 0; i < childCount; i++) {
16992                PackageParser.Package childPkg = pkg.childPackages.get(i);
16993                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16994                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16995                if (childPs != null) {
16996                    childRes.newUsers = childPs.queryInstalledUsers(
16997                            sUserManager.getUserIds(), true);
16998                }
16999            }
17000
17001            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17002                updateSequenceNumberLP(pkgName, res.newUsers);
17003            }
17004        }
17005    }
17006
17007    private void startIntentFilterVerifications(int userId, boolean replacing,
17008            PackageParser.Package pkg) {
17009        if (mIntentFilterVerifierComponent == null) {
17010            Slog.w(TAG, "No IntentFilter verification will not be done as "
17011                    + "there is no IntentFilterVerifier available!");
17012            return;
17013        }
17014
17015        final int verifierUid = getPackageUid(
17016                mIntentFilterVerifierComponent.getPackageName(),
17017                MATCH_DEBUG_TRIAGED_MISSING,
17018                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17019
17020        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17021        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17022        mHandler.sendMessage(msg);
17023
17024        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17025        for (int i = 0; i < childCount; i++) {
17026            PackageParser.Package childPkg = pkg.childPackages.get(i);
17027            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17028            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17029            mHandler.sendMessage(msg);
17030        }
17031    }
17032
17033    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17034            PackageParser.Package pkg) {
17035        int size = pkg.activities.size();
17036        if (size == 0) {
17037            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17038                    "No activity, so no need to verify any IntentFilter!");
17039            return;
17040        }
17041
17042        final boolean hasDomainURLs = hasDomainURLs(pkg);
17043        if (!hasDomainURLs) {
17044            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17045                    "No domain URLs, so no need to verify any IntentFilter!");
17046            return;
17047        }
17048
17049        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17050                + " if any IntentFilter from the " + size
17051                + " Activities needs verification ...");
17052
17053        int count = 0;
17054        final String packageName = pkg.packageName;
17055
17056        synchronized (mPackages) {
17057            // If this is a new install and we see that we've already run verification for this
17058            // package, we have nothing to do: it means the state was restored from backup.
17059            if (!replacing) {
17060                IntentFilterVerificationInfo ivi =
17061                        mSettings.getIntentFilterVerificationLPr(packageName);
17062                if (ivi != null) {
17063                    if (DEBUG_DOMAIN_VERIFICATION) {
17064                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17065                                + ivi.getStatusString());
17066                    }
17067                    return;
17068                }
17069            }
17070
17071            // If any filters need to be verified, then all need to be.
17072            boolean needToVerify = false;
17073            for (PackageParser.Activity a : pkg.activities) {
17074                for (ActivityIntentInfo filter : a.intents) {
17075                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17076                        if (DEBUG_DOMAIN_VERIFICATION) {
17077                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17078                        }
17079                        needToVerify = true;
17080                        break;
17081                    }
17082                }
17083            }
17084
17085            if (needToVerify) {
17086                final int verificationId = mIntentFilterVerificationToken++;
17087                for (PackageParser.Activity a : pkg.activities) {
17088                    for (ActivityIntentInfo filter : a.intents) {
17089                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17090                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17091                                    "Verification needed for IntentFilter:" + filter.toString());
17092                            mIntentFilterVerifier.addOneIntentFilterVerification(
17093                                    verifierUid, userId, verificationId, filter, packageName);
17094                            count++;
17095                        }
17096                    }
17097                }
17098            }
17099        }
17100
17101        if (count > 0) {
17102            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17103                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17104                    +  " for userId:" + userId);
17105            mIntentFilterVerifier.startVerifications(userId);
17106        } else {
17107            if (DEBUG_DOMAIN_VERIFICATION) {
17108                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17109            }
17110        }
17111    }
17112
17113    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17114        final ComponentName cn  = filter.activity.getComponentName();
17115        final String packageName = cn.getPackageName();
17116
17117        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17118                packageName);
17119        if (ivi == null) {
17120            return true;
17121        }
17122        int status = ivi.getStatus();
17123        switch (status) {
17124            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17125            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17126                return true;
17127
17128            default:
17129                // Nothing to do
17130                return false;
17131        }
17132    }
17133
17134    private static boolean isMultiArch(ApplicationInfo info) {
17135        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17136    }
17137
17138    private static boolean isExternal(PackageParser.Package pkg) {
17139        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17140    }
17141
17142    private static boolean isExternal(PackageSetting ps) {
17143        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17144    }
17145
17146    private static boolean isSystemApp(PackageParser.Package pkg) {
17147        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17148    }
17149
17150    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17151        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17152    }
17153
17154    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17155        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17156    }
17157
17158    private static boolean isSystemApp(PackageSetting ps) {
17159        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17160    }
17161
17162    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17163        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17164    }
17165
17166    private int packageFlagsToInstallFlags(PackageSetting ps) {
17167        int installFlags = 0;
17168        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17169            // This existing package was an external ASEC install when we have
17170            // the external flag without a UUID
17171            installFlags |= PackageManager.INSTALL_EXTERNAL;
17172        }
17173        if (ps.isForwardLocked()) {
17174            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17175        }
17176        return installFlags;
17177    }
17178
17179    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17180        if (isExternal(pkg)) {
17181            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17182                return StorageManager.UUID_PRIMARY_PHYSICAL;
17183            } else {
17184                return pkg.volumeUuid;
17185            }
17186        } else {
17187            return StorageManager.UUID_PRIVATE_INTERNAL;
17188        }
17189    }
17190
17191    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17192        if (isExternal(pkg)) {
17193            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17194                return mSettings.getExternalVersion();
17195            } else {
17196                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17197            }
17198        } else {
17199            return mSettings.getInternalVersion();
17200        }
17201    }
17202
17203    private void deleteTempPackageFiles() {
17204        final FilenameFilter filter = new FilenameFilter() {
17205            public boolean accept(File dir, String name) {
17206                return name.startsWith("vmdl") && name.endsWith(".tmp");
17207            }
17208        };
17209        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17210            file.delete();
17211        }
17212    }
17213
17214    @Override
17215    public void deletePackageAsUser(String packageName, int versionCode,
17216            IPackageDeleteObserver observer, int userId, int flags) {
17217        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17218                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17219    }
17220
17221    @Override
17222    public void deletePackageVersioned(VersionedPackage versionedPackage,
17223            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17224        mContext.enforceCallingOrSelfPermission(
17225                android.Manifest.permission.DELETE_PACKAGES, null);
17226        Preconditions.checkNotNull(versionedPackage);
17227        Preconditions.checkNotNull(observer);
17228        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17229                PackageManager.VERSION_CODE_HIGHEST,
17230                Integer.MAX_VALUE, "versionCode must be >= -1");
17231
17232        final String packageName = versionedPackage.getPackageName();
17233        // TODO: We will change version code to long, so in the new API it is long
17234        final int versionCode = (int) versionedPackage.getVersionCode();
17235        final String internalPackageName;
17236        synchronized (mPackages) {
17237            // Normalize package name to handle renamed packages and static libs
17238            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17239                    // TODO: We will change version code to long, so in the new API it is long
17240                    (int) versionedPackage.getVersionCode());
17241        }
17242
17243        final int uid = Binder.getCallingUid();
17244        if (!isOrphaned(internalPackageName)
17245                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17246            try {
17247                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17248                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17249                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17250                observer.onUserActionRequired(intent);
17251            } catch (RemoteException re) {
17252            }
17253            return;
17254        }
17255        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17256        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17257        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17258            mContext.enforceCallingOrSelfPermission(
17259                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17260                    "deletePackage for user " + userId);
17261        }
17262
17263        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17264            try {
17265                observer.onPackageDeleted(packageName,
17266                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17267            } catch (RemoteException re) {
17268            }
17269            return;
17270        }
17271
17272        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17273            try {
17274                observer.onPackageDeleted(packageName,
17275                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17276            } catch (RemoteException re) {
17277            }
17278            return;
17279        }
17280
17281        if (DEBUG_REMOVE) {
17282            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17283                    + " deleteAllUsers: " + deleteAllUsers + " version="
17284                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17285                    ? "VERSION_CODE_HIGHEST" : versionCode));
17286        }
17287        // Queue up an async operation since the package deletion may take a little while.
17288        mHandler.post(new Runnable() {
17289            public void run() {
17290                mHandler.removeCallbacks(this);
17291                int returnCode;
17292                if (!deleteAllUsers) {
17293                    returnCode = deletePackageX(internalPackageName, versionCode,
17294                            userId, deleteFlags);
17295                } else {
17296                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17297                            internalPackageName, users);
17298                    // If nobody is blocking uninstall, proceed with delete for all users
17299                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17300                        returnCode = deletePackageX(internalPackageName, versionCode,
17301                                userId, deleteFlags);
17302                    } else {
17303                        // Otherwise uninstall individually for users with blockUninstalls=false
17304                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17305                        for (int userId : users) {
17306                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17307                                returnCode = deletePackageX(internalPackageName, versionCode,
17308                                        userId, userFlags);
17309                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17310                                    Slog.w(TAG, "Package delete failed for user " + userId
17311                                            + ", returnCode " + returnCode);
17312                                }
17313                            }
17314                        }
17315                        // The app has only been marked uninstalled for certain users.
17316                        // We still need to report that delete was blocked
17317                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17318                    }
17319                }
17320                try {
17321                    observer.onPackageDeleted(packageName, returnCode, null);
17322                } catch (RemoteException e) {
17323                    Log.i(TAG, "Observer no longer exists.");
17324                } //end catch
17325            } //end run
17326        });
17327    }
17328
17329    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17330        if (pkg.staticSharedLibName != null) {
17331            return pkg.manifestPackageName;
17332        }
17333        return pkg.packageName;
17334    }
17335
17336    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17337        // Handle renamed packages
17338        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17339        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17340
17341        // Is this a static library?
17342        SparseArray<SharedLibraryEntry> versionedLib =
17343                mStaticLibsByDeclaringPackage.get(packageName);
17344        if (versionedLib == null || versionedLib.size() <= 0) {
17345            return packageName;
17346        }
17347
17348        // Figure out which lib versions the caller can see
17349        SparseIntArray versionsCallerCanSee = null;
17350        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17351        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17352                && callingAppId != Process.ROOT_UID) {
17353            versionsCallerCanSee = new SparseIntArray();
17354            String libName = versionedLib.valueAt(0).info.getName();
17355            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17356            if (uidPackages != null) {
17357                for (String uidPackage : uidPackages) {
17358                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17359                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17360                    if (libIdx >= 0) {
17361                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17362                        versionsCallerCanSee.append(libVersion, libVersion);
17363                    }
17364                }
17365            }
17366        }
17367
17368        // Caller can see nothing - done
17369        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17370            return packageName;
17371        }
17372
17373        // Find the version the caller can see and the app version code
17374        SharedLibraryEntry highestVersion = null;
17375        final int versionCount = versionedLib.size();
17376        for (int i = 0; i < versionCount; i++) {
17377            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17378            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17379                    libEntry.info.getVersion()) < 0) {
17380                continue;
17381            }
17382            // TODO: We will change version code to long, so in the new API it is long
17383            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17384            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17385                if (libVersionCode == versionCode) {
17386                    return libEntry.apk;
17387                }
17388            } else if (highestVersion == null) {
17389                highestVersion = libEntry;
17390            } else if (libVersionCode  > highestVersion.info
17391                    .getDeclaringPackage().getVersionCode()) {
17392                highestVersion = libEntry;
17393            }
17394        }
17395
17396        if (highestVersion != null) {
17397            return highestVersion.apk;
17398        }
17399
17400        return packageName;
17401    }
17402
17403    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17404        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17405              || callingUid == Process.SYSTEM_UID) {
17406            return true;
17407        }
17408        final int callingUserId = UserHandle.getUserId(callingUid);
17409        // If the caller installed the pkgName, then allow it to silently uninstall.
17410        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17411            return true;
17412        }
17413
17414        // Allow package verifier to silently uninstall.
17415        if (mRequiredVerifierPackage != null &&
17416                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17417            return true;
17418        }
17419
17420        // Allow package uninstaller to silently uninstall.
17421        if (mRequiredUninstallerPackage != null &&
17422                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17423            return true;
17424        }
17425
17426        // Allow storage manager to silently uninstall.
17427        if (mStorageManagerPackage != null &&
17428                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17429            return true;
17430        }
17431        return false;
17432    }
17433
17434    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17435        int[] result = EMPTY_INT_ARRAY;
17436        for (int userId : userIds) {
17437            if (getBlockUninstallForUser(packageName, userId)) {
17438                result = ArrayUtils.appendInt(result, userId);
17439            }
17440        }
17441        return result;
17442    }
17443
17444    @Override
17445    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17446        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17447    }
17448
17449    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17450        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17451                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17452        try {
17453            if (dpm != null) {
17454                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17455                        /* callingUserOnly =*/ false);
17456                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17457                        : deviceOwnerComponentName.getPackageName();
17458                // Does the package contains the device owner?
17459                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17460                // this check is probably not needed, since DO should be registered as a device
17461                // admin on some user too. (Original bug for this: b/17657954)
17462                if (packageName.equals(deviceOwnerPackageName)) {
17463                    return true;
17464                }
17465                // Does it contain a device admin for any user?
17466                int[] users;
17467                if (userId == UserHandle.USER_ALL) {
17468                    users = sUserManager.getUserIds();
17469                } else {
17470                    users = new int[]{userId};
17471                }
17472                for (int i = 0; i < users.length; ++i) {
17473                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17474                        return true;
17475                    }
17476                }
17477            }
17478        } catch (RemoteException e) {
17479        }
17480        return false;
17481    }
17482
17483    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17484        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17485    }
17486
17487    /**
17488     *  This method is an internal method that could be get invoked either
17489     *  to delete an installed package or to clean up a failed installation.
17490     *  After deleting an installed package, a broadcast is sent to notify any
17491     *  listeners that the package has been removed. For cleaning up a failed
17492     *  installation, the broadcast is not necessary since the package's
17493     *  installation wouldn't have sent the initial broadcast either
17494     *  The key steps in deleting a package are
17495     *  deleting the package information in internal structures like mPackages,
17496     *  deleting the packages base directories through installd
17497     *  updating mSettings to reflect current status
17498     *  persisting settings for later use
17499     *  sending a broadcast if necessary
17500     */
17501    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17502        final PackageRemovedInfo info = new PackageRemovedInfo();
17503        final boolean res;
17504
17505        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17506                ? UserHandle.USER_ALL : userId;
17507
17508        if (isPackageDeviceAdmin(packageName, removeUser)) {
17509            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17510            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17511        }
17512
17513        PackageSetting uninstalledPs = null;
17514
17515        // for the uninstall-updates case and restricted profiles, remember the per-
17516        // user handle installed state
17517        int[] allUsers;
17518        synchronized (mPackages) {
17519            uninstalledPs = mSettings.mPackages.get(packageName);
17520            if (uninstalledPs == null) {
17521                Slog.w(TAG, "Not removing non-existent package " + packageName);
17522                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17523            }
17524
17525            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17526                    && uninstalledPs.versionCode != versionCode) {
17527                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17528                        + uninstalledPs.versionCode + " != " + versionCode);
17529                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17530            }
17531
17532            // Static shared libs can be declared by any package, so let us not
17533            // allow removing a package if it provides a lib others depend on.
17534            PackageParser.Package pkg = mPackages.get(packageName);
17535            if (pkg != null && pkg.staticSharedLibName != null) {
17536                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17537                        pkg.staticSharedLibVersion);
17538                if (libEntry != null) {
17539                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17540                            libEntry.info, 0, userId);
17541                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17542                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17543                                + " hosting lib " + libEntry.info.getName() + " version "
17544                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17545                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17546                    }
17547                }
17548            }
17549
17550            allUsers = sUserManager.getUserIds();
17551            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17552        }
17553
17554        final int freezeUser;
17555        if (isUpdatedSystemApp(uninstalledPs)
17556                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17557            // We're downgrading a system app, which will apply to all users, so
17558            // freeze them all during the downgrade
17559            freezeUser = UserHandle.USER_ALL;
17560        } else {
17561            freezeUser = removeUser;
17562        }
17563
17564        synchronized (mInstallLock) {
17565            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17566            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17567                    deleteFlags, "deletePackageX")) {
17568                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17569                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17570            }
17571            synchronized (mPackages) {
17572                if (res) {
17573                    mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg,
17574                            info.removedUsers);
17575                    updateSequenceNumberLP(packageName, info.removedUsers);
17576                }
17577            }
17578        }
17579
17580        if (res) {
17581            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17582            info.sendPackageRemovedBroadcasts(killApp);
17583            info.sendSystemPackageUpdatedBroadcasts();
17584            info.sendSystemPackageAppearedBroadcasts();
17585        }
17586        // Force a gc here.
17587        Runtime.getRuntime().gc();
17588        // Delete the resources here after sending the broadcast to let
17589        // other processes clean up before deleting resources.
17590        if (info.args != null) {
17591            synchronized (mInstallLock) {
17592                info.args.doPostDeleteLI(true);
17593            }
17594        }
17595
17596        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17597    }
17598
17599    class PackageRemovedInfo {
17600        String removedPackage;
17601        int uid = -1;
17602        int removedAppId = -1;
17603        int[] origUsers;
17604        int[] removedUsers = null;
17605        SparseArray<Integer> installReasons;
17606        boolean isRemovedPackageSystemUpdate = false;
17607        boolean isUpdate;
17608        boolean dataRemoved;
17609        boolean removedForAllUsers;
17610        boolean isStaticSharedLib;
17611        // Clean up resources deleted packages.
17612        InstallArgs args = null;
17613        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17614        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17615
17616        void sendPackageRemovedBroadcasts(boolean killApp) {
17617            sendPackageRemovedBroadcastInternal(killApp);
17618            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17619            for (int i = 0; i < childCount; i++) {
17620                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17621                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17622            }
17623        }
17624
17625        void sendSystemPackageUpdatedBroadcasts() {
17626            if (isRemovedPackageSystemUpdate) {
17627                sendSystemPackageUpdatedBroadcastsInternal();
17628                final int childCount = (removedChildPackages != null)
17629                        ? removedChildPackages.size() : 0;
17630                for (int i = 0; i < childCount; i++) {
17631                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17632                    if (childInfo.isRemovedPackageSystemUpdate) {
17633                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17634                    }
17635                }
17636            }
17637        }
17638
17639        void sendSystemPackageAppearedBroadcasts() {
17640            final int packageCount = (appearedChildPackages != null)
17641                    ? appearedChildPackages.size() : 0;
17642            for (int i = 0; i < packageCount; i++) {
17643                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17644                sendPackageAddedForNewUsers(installedInfo.name, true,
17645                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17646            }
17647        }
17648
17649        private void sendSystemPackageUpdatedBroadcastsInternal() {
17650            Bundle extras = new Bundle(2);
17651            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17652            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17653            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17654                    extras, 0, null, null, null);
17655            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17656                    extras, 0, null, null, null);
17657            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17658                    null, 0, removedPackage, null, null);
17659        }
17660
17661        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17662            // Don't send static shared library removal broadcasts as these
17663            // libs are visible only the the apps that depend on them an one
17664            // cannot remove the library if it has a dependency.
17665            if (isStaticSharedLib) {
17666                return;
17667            }
17668            Bundle extras = new Bundle(2);
17669            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17670            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17671            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17672            if (isUpdate || isRemovedPackageSystemUpdate) {
17673                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17674            }
17675            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17676            if (removedPackage != null) {
17677                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17678                        extras, 0, null, null, removedUsers);
17679                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17680                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17681                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17682                            null, null, removedUsers);
17683                }
17684            }
17685            if (removedAppId >= 0) {
17686                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17687                        removedUsers);
17688            }
17689        }
17690    }
17691
17692    /*
17693     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17694     * flag is not set, the data directory is removed as well.
17695     * make sure this flag is set for partially installed apps. If not its meaningless to
17696     * delete a partially installed application.
17697     */
17698    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17699            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17700        String packageName = ps.name;
17701        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17702        // Retrieve object to delete permissions for shared user later on
17703        final PackageParser.Package deletedPkg;
17704        final PackageSetting deletedPs;
17705        // reader
17706        synchronized (mPackages) {
17707            deletedPkg = mPackages.get(packageName);
17708            deletedPs = mSettings.mPackages.get(packageName);
17709            if (outInfo != null) {
17710                outInfo.removedPackage = packageName;
17711                outInfo.isStaticSharedLib = deletedPkg != null
17712                        && deletedPkg.staticSharedLibName != null;
17713                outInfo.removedUsers = deletedPs != null
17714                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17715                        : null;
17716            }
17717        }
17718
17719        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17720
17721        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17722            final PackageParser.Package resolvedPkg;
17723            if (deletedPkg != null) {
17724                resolvedPkg = deletedPkg;
17725            } else {
17726                // We don't have a parsed package when it lives on an ejected
17727                // adopted storage device, so fake something together
17728                resolvedPkg = new PackageParser.Package(ps.name);
17729                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17730            }
17731            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17732                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17733            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17734            if (outInfo != null) {
17735                outInfo.dataRemoved = true;
17736            }
17737            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17738        }
17739
17740        int removedAppId = -1;
17741
17742        // writer
17743        synchronized (mPackages) {
17744            boolean installedStateChanged = false;
17745            if (deletedPs != null) {
17746                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17747                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17748                    clearDefaultBrowserIfNeeded(packageName);
17749                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17750                    removedAppId = mSettings.removePackageLPw(packageName);
17751                    if (outInfo != null) {
17752                        outInfo.removedAppId = removedAppId;
17753                    }
17754                    updatePermissionsLPw(deletedPs.name, null, 0);
17755                    if (deletedPs.sharedUser != null) {
17756                        // Remove permissions associated with package. Since runtime
17757                        // permissions are per user we have to kill the removed package
17758                        // or packages running under the shared user of the removed
17759                        // package if revoking the permissions requested only by the removed
17760                        // package is successful and this causes a change in gids.
17761                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17762                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17763                                    userId);
17764                            if (userIdToKill == UserHandle.USER_ALL
17765                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17766                                // If gids changed for this user, kill all affected packages.
17767                                mHandler.post(new Runnable() {
17768                                    @Override
17769                                    public void run() {
17770                                        // This has to happen with no lock held.
17771                                        killApplication(deletedPs.name, deletedPs.appId,
17772                                                KILL_APP_REASON_GIDS_CHANGED);
17773                                    }
17774                                });
17775                                break;
17776                            }
17777                        }
17778                    }
17779                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17780                }
17781                // make sure to preserve per-user disabled state if this removal was just
17782                // a downgrade of a system app to the factory package
17783                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17784                    if (DEBUG_REMOVE) {
17785                        Slog.d(TAG, "Propagating install state across downgrade");
17786                    }
17787                    for (int userId : allUserHandles) {
17788                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17789                        if (DEBUG_REMOVE) {
17790                            Slog.d(TAG, "    user " + userId + " => " + installed);
17791                        }
17792                        if (installed != ps.getInstalled(userId)) {
17793                            installedStateChanged = true;
17794                        }
17795                        ps.setInstalled(installed, userId);
17796                    }
17797                }
17798            }
17799            // can downgrade to reader
17800            if (writeSettings) {
17801                // Save settings now
17802                mSettings.writeLPr();
17803            }
17804            if (installedStateChanged) {
17805                mSettings.writeKernelMappingLPr(ps);
17806            }
17807        }
17808        if (removedAppId != -1) {
17809            // A user ID was deleted here. Go through all users and remove it
17810            // from KeyStore.
17811            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17812        }
17813    }
17814
17815    static boolean locationIsPrivileged(File path) {
17816        try {
17817            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17818                    .getCanonicalPath();
17819            return path.getCanonicalPath().startsWith(privilegedAppDir);
17820        } catch (IOException e) {
17821            Slog.e(TAG, "Unable to access code path " + path);
17822        }
17823        return false;
17824    }
17825
17826    /*
17827     * Tries to delete system package.
17828     */
17829    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17830            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17831            boolean writeSettings) {
17832        if (deletedPs.parentPackageName != null) {
17833            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17834            return false;
17835        }
17836
17837        final boolean applyUserRestrictions
17838                = (allUserHandles != null) && (outInfo.origUsers != null);
17839        final PackageSetting disabledPs;
17840        // Confirm if the system package has been updated
17841        // An updated system app can be deleted. This will also have to restore
17842        // the system pkg from system partition
17843        // reader
17844        synchronized (mPackages) {
17845            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17846        }
17847
17848        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17849                + " disabledPs=" + disabledPs);
17850
17851        if (disabledPs == null) {
17852            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17853            return false;
17854        } else if (DEBUG_REMOVE) {
17855            Slog.d(TAG, "Deleting system pkg from data partition");
17856        }
17857
17858        if (DEBUG_REMOVE) {
17859            if (applyUserRestrictions) {
17860                Slog.d(TAG, "Remembering install states:");
17861                for (int userId : allUserHandles) {
17862                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17863                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17864                }
17865            }
17866        }
17867
17868        // Delete the updated package
17869        outInfo.isRemovedPackageSystemUpdate = true;
17870        if (outInfo.removedChildPackages != null) {
17871            final int childCount = (deletedPs.childPackageNames != null)
17872                    ? deletedPs.childPackageNames.size() : 0;
17873            for (int i = 0; i < childCount; i++) {
17874                String childPackageName = deletedPs.childPackageNames.get(i);
17875                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17876                        .contains(childPackageName)) {
17877                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17878                            childPackageName);
17879                    if (childInfo != null) {
17880                        childInfo.isRemovedPackageSystemUpdate = true;
17881                    }
17882                }
17883            }
17884        }
17885
17886        if (disabledPs.versionCode < deletedPs.versionCode) {
17887            // Delete data for downgrades
17888            flags &= ~PackageManager.DELETE_KEEP_DATA;
17889        } else {
17890            // Preserve data by setting flag
17891            flags |= PackageManager.DELETE_KEEP_DATA;
17892        }
17893
17894        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17895                outInfo, writeSettings, disabledPs.pkg);
17896        if (!ret) {
17897            return false;
17898        }
17899
17900        // writer
17901        synchronized (mPackages) {
17902            // Reinstate the old system package
17903            enableSystemPackageLPw(disabledPs.pkg);
17904            // Remove any native libraries from the upgraded package.
17905            removeNativeBinariesLI(deletedPs);
17906        }
17907
17908        // Install the system package
17909        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17910        int parseFlags = mDefParseFlags
17911                | PackageParser.PARSE_MUST_BE_APK
17912                | PackageParser.PARSE_IS_SYSTEM
17913                | PackageParser.PARSE_IS_SYSTEM_DIR;
17914        if (locationIsPrivileged(disabledPs.codePath)) {
17915            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17916        }
17917
17918        final PackageParser.Package newPkg;
17919        try {
17920            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17921                0 /* currentTime */, null);
17922        } catch (PackageManagerException e) {
17923            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17924                    + e.getMessage());
17925            return false;
17926        }
17927
17928        try {
17929            // update shared libraries for the newly re-installed system package
17930            updateSharedLibrariesLPr(newPkg, null);
17931        } catch (PackageManagerException e) {
17932            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17933        }
17934
17935        prepareAppDataAfterInstallLIF(newPkg);
17936
17937        // writer
17938        synchronized (mPackages) {
17939            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17940
17941            // Propagate the permissions state as we do not want to drop on the floor
17942            // runtime permissions. The update permissions method below will take
17943            // care of removing obsolete permissions and grant install permissions.
17944            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17945            updatePermissionsLPw(newPkg.packageName, newPkg,
17946                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17947
17948            if (applyUserRestrictions) {
17949                boolean installedStateChanged = false;
17950                if (DEBUG_REMOVE) {
17951                    Slog.d(TAG, "Propagating install state across reinstall");
17952                }
17953                for (int userId : allUserHandles) {
17954                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17955                    if (DEBUG_REMOVE) {
17956                        Slog.d(TAG, "    user " + userId + " => " + installed);
17957                    }
17958                    if (installed != ps.getInstalled(userId)) {
17959                        installedStateChanged = true;
17960                    }
17961                    ps.setInstalled(installed, userId);
17962
17963                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17964                }
17965                // Regardless of writeSettings we need to ensure that this restriction
17966                // state propagation is persisted
17967                mSettings.writeAllUsersPackageRestrictionsLPr();
17968                if (installedStateChanged) {
17969                    mSettings.writeKernelMappingLPr(ps);
17970                }
17971            }
17972            // can downgrade to reader here
17973            if (writeSettings) {
17974                mSettings.writeLPr();
17975            }
17976        }
17977        return true;
17978    }
17979
17980    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17981            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17982            PackageRemovedInfo outInfo, boolean writeSettings,
17983            PackageParser.Package replacingPackage) {
17984        synchronized (mPackages) {
17985            if (outInfo != null) {
17986                outInfo.uid = ps.appId;
17987            }
17988
17989            if (outInfo != null && outInfo.removedChildPackages != null) {
17990                final int childCount = (ps.childPackageNames != null)
17991                        ? ps.childPackageNames.size() : 0;
17992                for (int i = 0; i < childCount; i++) {
17993                    String childPackageName = ps.childPackageNames.get(i);
17994                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17995                    if (childPs == null) {
17996                        return false;
17997                    }
17998                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17999                            childPackageName);
18000                    if (childInfo != null) {
18001                        childInfo.uid = childPs.appId;
18002                    }
18003                }
18004            }
18005        }
18006
18007        // Delete package data from internal structures and also remove data if flag is set
18008        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18009
18010        // Delete the child packages data
18011        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18012        for (int i = 0; i < childCount; i++) {
18013            PackageSetting childPs;
18014            synchronized (mPackages) {
18015                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18016            }
18017            if (childPs != null) {
18018                PackageRemovedInfo childOutInfo = (outInfo != null
18019                        && outInfo.removedChildPackages != null)
18020                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18021                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18022                        && (replacingPackage != null
18023                        && !replacingPackage.hasChildPackage(childPs.name))
18024                        ? flags & ~DELETE_KEEP_DATA : flags;
18025                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18026                        deleteFlags, writeSettings);
18027            }
18028        }
18029
18030        // Delete application code and resources only for parent packages
18031        if (ps.parentPackageName == null) {
18032            if (deleteCodeAndResources && (outInfo != null)) {
18033                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18034                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18035                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18036            }
18037        }
18038
18039        return true;
18040    }
18041
18042    @Override
18043    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18044            int userId) {
18045        mContext.enforceCallingOrSelfPermission(
18046                android.Manifest.permission.DELETE_PACKAGES, null);
18047        synchronized (mPackages) {
18048            PackageSetting ps = mSettings.mPackages.get(packageName);
18049            if (ps == null) {
18050                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
18051                return false;
18052            }
18053            // Cannot block uninstall of static shared libs as they are
18054            // considered a part of the using app (emulating static linking).
18055            // Also static libs are installed always on internal storage.
18056            PackageParser.Package pkg = mPackages.get(packageName);
18057            if (pkg != null && pkg.staticSharedLibName != null) {
18058                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18059                        + " providing static shared library: " + pkg.staticSharedLibName);
18060                return false;
18061            }
18062            if (!ps.getInstalled(userId)) {
18063                // Can't block uninstall for an app that is not installed or enabled.
18064                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18065                return false;
18066            }
18067            ps.setBlockUninstall(blockUninstall, userId);
18068            mSettings.writePackageRestrictionsLPr(userId);
18069        }
18070        return true;
18071    }
18072
18073    @Override
18074    public boolean getBlockUninstallForUser(String packageName, int userId) {
18075        synchronized (mPackages) {
18076            PackageSetting ps = mSettings.mPackages.get(packageName);
18077            if (ps == null) {
18078                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18079                return false;
18080            }
18081            return ps.getBlockUninstall(userId);
18082        }
18083    }
18084
18085    @Override
18086    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18087        int callingUid = Binder.getCallingUid();
18088        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18089            throw new SecurityException(
18090                    "setRequiredForSystemUser can only be run by the system or root");
18091        }
18092        synchronized (mPackages) {
18093            PackageSetting ps = mSettings.mPackages.get(packageName);
18094            if (ps == null) {
18095                Log.w(TAG, "Package doesn't exist: " + packageName);
18096                return false;
18097            }
18098            if (systemUserApp) {
18099                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18100            } else {
18101                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18102            }
18103            mSettings.writeLPr();
18104        }
18105        return true;
18106    }
18107
18108    /*
18109     * This method handles package deletion in general
18110     */
18111    private boolean deletePackageLIF(String packageName, UserHandle user,
18112            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18113            PackageRemovedInfo outInfo, boolean writeSettings,
18114            PackageParser.Package replacingPackage) {
18115        if (packageName == null) {
18116            Slog.w(TAG, "Attempt to delete null packageName.");
18117            return false;
18118        }
18119
18120        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18121
18122        PackageSetting ps;
18123        synchronized (mPackages) {
18124            ps = mSettings.mPackages.get(packageName);
18125            if (ps == null) {
18126                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18127                return false;
18128            }
18129
18130            if (ps.parentPackageName != null && (!isSystemApp(ps)
18131                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18132                if (DEBUG_REMOVE) {
18133                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18134                            + ((user == null) ? UserHandle.USER_ALL : user));
18135                }
18136                final int removedUserId = (user != null) ? user.getIdentifier()
18137                        : UserHandle.USER_ALL;
18138                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18139                    return false;
18140                }
18141                markPackageUninstalledForUserLPw(ps, user);
18142                scheduleWritePackageRestrictionsLocked(user);
18143                return true;
18144            }
18145        }
18146
18147        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18148                && user.getIdentifier() != UserHandle.USER_ALL)) {
18149            // The caller is asking that the package only be deleted for a single
18150            // user.  To do this, we just mark its uninstalled state and delete
18151            // its data. If this is a system app, we only allow this to happen if
18152            // they have set the special DELETE_SYSTEM_APP which requests different
18153            // semantics than normal for uninstalling system apps.
18154            markPackageUninstalledForUserLPw(ps, user);
18155
18156            if (!isSystemApp(ps)) {
18157                // Do not uninstall the APK if an app should be cached
18158                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18159                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18160                    // Other user still have this package installed, so all
18161                    // we need to do is clear this user's data and save that
18162                    // it is uninstalled.
18163                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18164                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18165                        return false;
18166                    }
18167                    scheduleWritePackageRestrictionsLocked(user);
18168                    return true;
18169                } else {
18170                    // We need to set it back to 'installed' so the uninstall
18171                    // broadcasts will be sent correctly.
18172                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18173                    ps.setInstalled(true, user.getIdentifier());
18174                    mSettings.writeKernelMappingLPr(ps);
18175                }
18176            } else {
18177                // This is a system app, so we assume that the
18178                // other users still have this package installed, so all
18179                // we need to do is clear this user's data and save that
18180                // it is uninstalled.
18181                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18182                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18183                    return false;
18184                }
18185                scheduleWritePackageRestrictionsLocked(user);
18186                return true;
18187            }
18188        }
18189
18190        // If we are deleting a composite package for all users, keep track
18191        // of result for each child.
18192        if (ps.childPackageNames != null && outInfo != null) {
18193            synchronized (mPackages) {
18194                final int childCount = ps.childPackageNames.size();
18195                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18196                for (int i = 0; i < childCount; i++) {
18197                    String childPackageName = ps.childPackageNames.get(i);
18198                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18199                    childInfo.removedPackage = childPackageName;
18200                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18201                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18202                    if (childPs != null) {
18203                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18204                    }
18205                }
18206            }
18207        }
18208
18209        boolean ret = false;
18210        if (isSystemApp(ps)) {
18211            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18212            // When an updated system application is deleted we delete the existing resources
18213            // as well and fall back to existing code in system partition
18214            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18215        } else {
18216            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18217            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18218                    outInfo, writeSettings, replacingPackage);
18219        }
18220
18221        // Take a note whether we deleted the package for all users
18222        if (outInfo != null) {
18223            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18224            if (outInfo.removedChildPackages != null) {
18225                synchronized (mPackages) {
18226                    final int childCount = outInfo.removedChildPackages.size();
18227                    for (int i = 0; i < childCount; i++) {
18228                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18229                        if (childInfo != null) {
18230                            childInfo.removedForAllUsers = mPackages.get(
18231                                    childInfo.removedPackage) == null;
18232                        }
18233                    }
18234                }
18235            }
18236            // If we uninstalled an update to a system app there may be some
18237            // child packages that appeared as they are declared in the system
18238            // app but were not declared in the update.
18239            if (isSystemApp(ps)) {
18240                synchronized (mPackages) {
18241                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18242                    final int childCount = (updatedPs.childPackageNames != null)
18243                            ? updatedPs.childPackageNames.size() : 0;
18244                    for (int i = 0; i < childCount; i++) {
18245                        String childPackageName = updatedPs.childPackageNames.get(i);
18246                        if (outInfo.removedChildPackages == null
18247                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18248                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18249                            if (childPs == null) {
18250                                continue;
18251                            }
18252                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18253                            installRes.name = childPackageName;
18254                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18255                            installRes.pkg = mPackages.get(childPackageName);
18256                            installRes.uid = childPs.pkg.applicationInfo.uid;
18257                            if (outInfo.appearedChildPackages == null) {
18258                                outInfo.appearedChildPackages = new ArrayMap<>();
18259                            }
18260                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18261                        }
18262                    }
18263                }
18264            }
18265        }
18266
18267        return ret;
18268    }
18269
18270    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18271        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18272                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18273        for (int nextUserId : userIds) {
18274            if (DEBUG_REMOVE) {
18275                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18276            }
18277            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18278                    false /*installed*/,
18279                    true /*stopped*/,
18280                    true /*notLaunched*/,
18281                    false /*hidden*/,
18282                    false /*suspended*/,
18283                    false /*instantApp*/,
18284                    null /*lastDisableAppCaller*/,
18285                    null /*enabledComponents*/,
18286                    null /*disabledComponents*/,
18287                    false /*blockUninstall*/,
18288                    ps.readUserState(nextUserId).domainVerificationStatus,
18289                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18290        }
18291        mSettings.writeKernelMappingLPr(ps);
18292    }
18293
18294    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18295            PackageRemovedInfo outInfo) {
18296        final PackageParser.Package pkg;
18297        synchronized (mPackages) {
18298            pkg = mPackages.get(ps.name);
18299        }
18300
18301        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18302                : new int[] {userId};
18303        for (int nextUserId : userIds) {
18304            if (DEBUG_REMOVE) {
18305                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18306                        + nextUserId);
18307            }
18308
18309            destroyAppDataLIF(pkg, userId,
18310                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18311            destroyAppProfilesLIF(pkg, userId);
18312            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18313            schedulePackageCleaning(ps.name, nextUserId, false);
18314            synchronized (mPackages) {
18315                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18316                    scheduleWritePackageRestrictionsLocked(nextUserId);
18317                }
18318                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18319            }
18320        }
18321
18322        if (outInfo != null) {
18323            outInfo.removedPackage = ps.name;
18324            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18325            outInfo.removedAppId = ps.appId;
18326            outInfo.removedUsers = userIds;
18327        }
18328
18329        return true;
18330    }
18331
18332    private final class ClearStorageConnection implements ServiceConnection {
18333        IMediaContainerService mContainerService;
18334
18335        @Override
18336        public void onServiceConnected(ComponentName name, IBinder service) {
18337            synchronized (this) {
18338                mContainerService = IMediaContainerService.Stub
18339                        .asInterface(Binder.allowBlocking(service));
18340                notifyAll();
18341            }
18342        }
18343
18344        @Override
18345        public void onServiceDisconnected(ComponentName name) {
18346        }
18347    }
18348
18349    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18350        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18351
18352        final boolean mounted;
18353        if (Environment.isExternalStorageEmulated()) {
18354            mounted = true;
18355        } else {
18356            final String status = Environment.getExternalStorageState();
18357
18358            mounted = status.equals(Environment.MEDIA_MOUNTED)
18359                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18360        }
18361
18362        if (!mounted) {
18363            return;
18364        }
18365
18366        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18367        int[] users;
18368        if (userId == UserHandle.USER_ALL) {
18369            users = sUserManager.getUserIds();
18370        } else {
18371            users = new int[] { userId };
18372        }
18373        final ClearStorageConnection conn = new ClearStorageConnection();
18374        if (mContext.bindServiceAsUser(
18375                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18376            try {
18377                for (int curUser : users) {
18378                    long timeout = SystemClock.uptimeMillis() + 5000;
18379                    synchronized (conn) {
18380                        long now;
18381                        while (conn.mContainerService == null &&
18382                                (now = SystemClock.uptimeMillis()) < timeout) {
18383                            try {
18384                                conn.wait(timeout - now);
18385                            } catch (InterruptedException e) {
18386                            }
18387                        }
18388                    }
18389                    if (conn.mContainerService == null) {
18390                        return;
18391                    }
18392
18393                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18394                    clearDirectory(conn.mContainerService,
18395                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18396                    if (allData) {
18397                        clearDirectory(conn.mContainerService,
18398                                userEnv.buildExternalStorageAppDataDirs(packageName));
18399                        clearDirectory(conn.mContainerService,
18400                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18401                    }
18402                }
18403            } finally {
18404                mContext.unbindService(conn);
18405            }
18406        }
18407    }
18408
18409    @Override
18410    public void clearApplicationProfileData(String packageName) {
18411        enforceSystemOrRoot("Only the system can clear all profile data");
18412
18413        final PackageParser.Package pkg;
18414        synchronized (mPackages) {
18415            pkg = mPackages.get(packageName);
18416        }
18417
18418        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18419            synchronized (mInstallLock) {
18420                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18421                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
18422                        true /* removeBaseMarker */);
18423            }
18424        }
18425    }
18426
18427    @Override
18428    public void clearApplicationUserData(final String packageName,
18429            final IPackageDataObserver observer, final int userId) {
18430        mContext.enforceCallingOrSelfPermission(
18431                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18432
18433        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18434                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18435
18436        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18437            throw new SecurityException("Cannot clear data for a protected package: "
18438                    + packageName);
18439        }
18440        // Queue up an async operation since the package deletion may take a little while.
18441        mHandler.post(new Runnable() {
18442            public void run() {
18443                mHandler.removeCallbacks(this);
18444                final boolean succeeded;
18445                try (PackageFreezer freezer = freezePackage(packageName,
18446                        "clearApplicationUserData")) {
18447                    synchronized (mInstallLock) {
18448                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18449                    }
18450                    clearExternalStorageDataSync(packageName, userId, true);
18451                    synchronized (mPackages) {
18452                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18453                                packageName, userId);
18454                    }
18455                }
18456                if (succeeded) {
18457                    // invoke DeviceStorageMonitor's update method to clear any notifications
18458                    DeviceStorageMonitorInternal dsm = LocalServices
18459                            .getService(DeviceStorageMonitorInternal.class);
18460                    if (dsm != null) {
18461                        dsm.checkMemory();
18462                    }
18463                }
18464                if(observer != null) {
18465                    try {
18466                        observer.onRemoveCompleted(packageName, succeeded);
18467                    } catch (RemoteException e) {
18468                        Log.i(TAG, "Observer no longer exists.");
18469                    }
18470                } //end if observer
18471            } //end run
18472        });
18473    }
18474
18475    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18476        if (packageName == null) {
18477            Slog.w(TAG, "Attempt to delete null packageName.");
18478            return false;
18479        }
18480
18481        // Try finding details about the requested package
18482        PackageParser.Package pkg;
18483        synchronized (mPackages) {
18484            pkg = mPackages.get(packageName);
18485            if (pkg == null) {
18486                final PackageSetting ps = mSettings.mPackages.get(packageName);
18487                if (ps != null) {
18488                    pkg = ps.pkg;
18489                }
18490            }
18491
18492            if (pkg == null) {
18493                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18494                return false;
18495            }
18496
18497            PackageSetting ps = (PackageSetting) pkg.mExtras;
18498            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18499        }
18500
18501        clearAppDataLIF(pkg, userId,
18502                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18503
18504        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18505        removeKeystoreDataIfNeeded(userId, appId);
18506
18507        UserManagerInternal umInternal = getUserManagerInternal();
18508        final int flags;
18509        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18510            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18511        } else if (umInternal.isUserRunning(userId)) {
18512            flags = StorageManager.FLAG_STORAGE_DE;
18513        } else {
18514            flags = 0;
18515        }
18516        prepareAppDataContentsLIF(pkg, userId, flags);
18517
18518        return true;
18519    }
18520
18521    /**
18522     * Reverts user permission state changes (permissions and flags) in
18523     * all packages for a given user.
18524     *
18525     * @param userId The device user for which to do a reset.
18526     */
18527    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18528        final int packageCount = mPackages.size();
18529        for (int i = 0; i < packageCount; i++) {
18530            PackageParser.Package pkg = mPackages.valueAt(i);
18531            PackageSetting ps = (PackageSetting) pkg.mExtras;
18532            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18533        }
18534    }
18535
18536    private void resetNetworkPolicies(int userId) {
18537        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18538    }
18539
18540    /**
18541     * Reverts user permission state changes (permissions and flags).
18542     *
18543     * @param ps The package for which to reset.
18544     * @param userId The device user for which to do a reset.
18545     */
18546    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18547            final PackageSetting ps, final int userId) {
18548        if (ps.pkg == null) {
18549            return;
18550        }
18551
18552        // These are flags that can change base on user actions.
18553        final int userSettableMask = FLAG_PERMISSION_USER_SET
18554                | FLAG_PERMISSION_USER_FIXED
18555                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18556                | FLAG_PERMISSION_REVIEW_REQUIRED;
18557
18558        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18559                | FLAG_PERMISSION_POLICY_FIXED;
18560
18561        boolean writeInstallPermissions = false;
18562        boolean writeRuntimePermissions = false;
18563
18564        final int permissionCount = ps.pkg.requestedPermissions.size();
18565        for (int i = 0; i < permissionCount; i++) {
18566            String permission = ps.pkg.requestedPermissions.get(i);
18567
18568            BasePermission bp = mSettings.mPermissions.get(permission);
18569            if (bp == null) {
18570                continue;
18571            }
18572
18573            // If shared user we just reset the state to which only this app contributed.
18574            if (ps.sharedUser != null) {
18575                boolean used = false;
18576                final int packageCount = ps.sharedUser.packages.size();
18577                for (int j = 0; j < packageCount; j++) {
18578                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18579                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18580                            && pkg.pkg.requestedPermissions.contains(permission)) {
18581                        used = true;
18582                        break;
18583                    }
18584                }
18585                if (used) {
18586                    continue;
18587                }
18588            }
18589
18590            PermissionsState permissionsState = ps.getPermissionsState();
18591
18592            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18593
18594            // Always clear the user settable flags.
18595            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18596                    bp.name) != null;
18597            // If permission review is enabled and this is a legacy app, mark the
18598            // permission as requiring a review as this is the initial state.
18599            int flags = 0;
18600            if (mPermissionReviewRequired
18601                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18602                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18603            }
18604            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18605                if (hasInstallState) {
18606                    writeInstallPermissions = true;
18607                } else {
18608                    writeRuntimePermissions = true;
18609                }
18610            }
18611
18612            // Below is only runtime permission handling.
18613            if (!bp.isRuntime()) {
18614                continue;
18615            }
18616
18617            // Never clobber system or policy.
18618            if ((oldFlags & policyOrSystemFlags) != 0) {
18619                continue;
18620            }
18621
18622            // If this permission was granted by default, make sure it is.
18623            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18624                if (permissionsState.grantRuntimePermission(bp, userId)
18625                        != PERMISSION_OPERATION_FAILURE) {
18626                    writeRuntimePermissions = true;
18627                }
18628            // If permission review is enabled the permissions for a legacy apps
18629            // are represented as constantly granted runtime ones, so don't revoke.
18630            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18631                // Otherwise, reset the permission.
18632                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18633                switch (revokeResult) {
18634                    case PERMISSION_OPERATION_SUCCESS:
18635                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18636                        writeRuntimePermissions = true;
18637                        final int appId = ps.appId;
18638                        mHandler.post(new Runnable() {
18639                            @Override
18640                            public void run() {
18641                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18642                            }
18643                        });
18644                    } break;
18645                }
18646            }
18647        }
18648
18649        // Synchronously write as we are taking permissions away.
18650        if (writeRuntimePermissions) {
18651            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18652        }
18653
18654        // Synchronously write as we are taking permissions away.
18655        if (writeInstallPermissions) {
18656            mSettings.writeLPr();
18657        }
18658    }
18659
18660    /**
18661     * Remove entries from the keystore daemon. Will only remove it if the
18662     * {@code appId} is valid.
18663     */
18664    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18665        if (appId < 0) {
18666            return;
18667        }
18668
18669        final KeyStore keyStore = KeyStore.getInstance();
18670        if (keyStore != null) {
18671            if (userId == UserHandle.USER_ALL) {
18672                for (final int individual : sUserManager.getUserIds()) {
18673                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18674                }
18675            } else {
18676                keyStore.clearUid(UserHandle.getUid(userId, appId));
18677            }
18678        } else {
18679            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18680        }
18681    }
18682
18683    @Override
18684    public void deleteApplicationCacheFiles(final String packageName,
18685            final IPackageDataObserver observer) {
18686        final int userId = UserHandle.getCallingUserId();
18687        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18688    }
18689
18690    @Override
18691    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18692            final IPackageDataObserver observer) {
18693        mContext.enforceCallingOrSelfPermission(
18694                android.Manifest.permission.DELETE_CACHE_FILES, null);
18695        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18696                /* requireFullPermission= */ true, /* checkShell= */ false,
18697                "delete application cache files");
18698
18699        final PackageParser.Package pkg;
18700        synchronized (mPackages) {
18701            pkg = mPackages.get(packageName);
18702        }
18703
18704        // Queue up an async operation since the package deletion may take a little while.
18705        mHandler.post(new Runnable() {
18706            public void run() {
18707                synchronized (mInstallLock) {
18708                    final int flags = StorageManager.FLAG_STORAGE_DE
18709                            | StorageManager.FLAG_STORAGE_CE;
18710                    // We're only clearing cache files, so we don't care if the
18711                    // app is unfrozen and still able to run
18712                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18713                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18714                }
18715                clearExternalStorageDataSync(packageName, userId, false);
18716                if (observer != null) {
18717                    try {
18718                        observer.onRemoveCompleted(packageName, true);
18719                    } catch (RemoteException e) {
18720                        Log.i(TAG, "Observer no longer exists.");
18721                    }
18722                }
18723            }
18724        });
18725    }
18726
18727    @Override
18728    public void getPackageSizeInfo(final String packageName, int userHandle,
18729            final IPackageStatsObserver observer) {
18730        Slog.w(TAG, "Shame on you for calling a hidden API. Shame!");
18731        try {
18732            observer.onGetStatsCompleted(null, false);
18733        } catch (Throwable ignored) {
18734        }
18735    }
18736
18737    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18738        final PackageSetting ps;
18739        synchronized (mPackages) {
18740            ps = mSettings.mPackages.get(packageName);
18741            if (ps == null) {
18742                Slog.w(TAG, "Failed to find settings for " + packageName);
18743                return false;
18744            }
18745        }
18746
18747        final String[] packageNames = { packageName };
18748        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18749        final String[] codePaths = { ps.codePathString };
18750
18751        try {
18752            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18753                    ps.appId, ceDataInodes, codePaths, stats);
18754
18755            // For now, ignore code size of packages on system partition
18756            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18757                stats.codeSize = 0;
18758            }
18759
18760            // External clients expect these to be tracked separately
18761            stats.dataSize -= stats.cacheSize;
18762
18763        } catch (InstallerException e) {
18764            Slog.w(TAG, String.valueOf(e));
18765            return false;
18766        }
18767
18768        return true;
18769    }
18770
18771    private int getUidTargetSdkVersionLockedLPr(int uid) {
18772        Object obj = mSettings.getUserIdLPr(uid);
18773        if (obj instanceof SharedUserSetting) {
18774            final SharedUserSetting sus = (SharedUserSetting) obj;
18775            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18776            final Iterator<PackageSetting> it = sus.packages.iterator();
18777            while (it.hasNext()) {
18778                final PackageSetting ps = it.next();
18779                if (ps.pkg != null) {
18780                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18781                    if (v < vers) vers = v;
18782                }
18783            }
18784            return vers;
18785        } else if (obj instanceof PackageSetting) {
18786            final PackageSetting ps = (PackageSetting) obj;
18787            if (ps.pkg != null) {
18788                return ps.pkg.applicationInfo.targetSdkVersion;
18789            }
18790        }
18791        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18792    }
18793
18794    @Override
18795    public void addPreferredActivity(IntentFilter filter, int match,
18796            ComponentName[] set, ComponentName activity, int userId) {
18797        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18798                "Adding preferred");
18799    }
18800
18801    private void addPreferredActivityInternal(IntentFilter filter, int match,
18802            ComponentName[] set, ComponentName activity, boolean always, int userId,
18803            String opname) {
18804        // writer
18805        int callingUid = Binder.getCallingUid();
18806        enforceCrossUserPermission(callingUid, userId,
18807                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18808        if (filter.countActions() == 0) {
18809            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18810            return;
18811        }
18812        synchronized (mPackages) {
18813            if (mContext.checkCallingOrSelfPermission(
18814                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18815                    != PackageManager.PERMISSION_GRANTED) {
18816                if (getUidTargetSdkVersionLockedLPr(callingUid)
18817                        < Build.VERSION_CODES.FROYO) {
18818                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18819                            + callingUid);
18820                    return;
18821                }
18822                mContext.enforceCallingOrSelfPermission(
18823                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18824            }
18825
18826            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18827            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18828                    + userId + ":");
18829            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18830            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18831            scheduleWritePackageRestrictionsLocked(userId);
18832            postPreferredActivityChangedBroadcast(userId);
18833        }
18834    }
18835
18836    private void postPreferredActivityChangedBroadcast(int userId) {
18837        mHandler.post(() -> {
18838            final IActivityManager am = ActivityManager.getService();
18839            if (am == null) {
18840                return;
18841            }
18842
18843            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18844            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18845            try {
18846                am.broadcastIntent(null, intent, null, null,
18847                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18848                        null, false, false, userId);
18849            } catch (RemoteException e) {
18850            }
18851        });
18852    }
18853
18854    @Override
18855    public void replacePreferredActivity(IntentFilter filter, int match,
18856            ComponentName[] set, ComponentName activity, int userId) {
18857        if (filter.countActions() != 1) {
18858            throw new IllegalArgumentException(
18859                    "replacePreferredActivity expects filter to have only 1 action.");
18860        }
18861        if (filter.countDataAuthorities() != 0
18862                || filter.countDataPaths() != 0
18863                || filter.countDataSchemes() > 1
18864                || filter.countDataTypes() != 0) {
18865            throw new IllegalArgumentException(
18866                    "replacePreferredActivity expects filter to have no data authorities, " +
18867                    "paths, or types; and at most one scheme.");
18868        }
18869
18870        final int callingUid = Binder.getCallingUid();
18871        enforceCrossUserPermission(callingUid, userId,
18872                true /* requireFullPermission */, false /* checkShell */,
18873                "replace preferred activity");
18874        synchronized (mPackages) {
18875            if (mContext.checkCallingOrSelfPermission(
18876                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18877                    != PackageManager.PERMISSION_GRANTED) {
18878                if (getUidTargetSdkVersionLockedLPr(callingUid)
18879                        < Build.VERSION_CODES.FROYO) {
18880                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18881                            + Binder.getCallingUid());
18882                    return;
18883                }
18884                mContext.enforceCallingOrSelfPermission(
18885                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18886            }
18887
18888            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18889            if (pir != null) {
18890                // Get all of the existing entries that exactly match this filter.
18891                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18892                if (existing != null && existing.size() == 1) {
18893                    PreferredActivity cur = existing.get(0);
18894                    if (DEBUG_PREFERRED) {
18895                        Slog.i(TAG, "Checking replace of preferred:");
18896                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18897                        if (!cur.mPref.mAlways) {
18898                            Slog.i(TAG, "  -- CUR; not mAlways!");
18899                        } else {
18900                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18901                            Slog.i(TAG, "  -- CUR: mSet="
18902                                    + Arrays.toString(cur.mPref.mSetComponents));
18903                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18904                            Slog.i(TAG, "  -- NEW: mMatch="
18905                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18906                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18907                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18908                        }
18909                    }
18910                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18911                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18912                            && cur.mPref.sameSet(set)) {
18913                        // Setting the preferred activity to what it happens to be already
18914                        if (DEBUG_PREFERRED) {
18915                            Slog.i(TAG, "Replacing with same preferred activity "
18916                                    + cur.mPref.mShortComponent + " for user "
18917                                    + userId + ":");
18918                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18919                        }
18920                        return;
18921                    }
18922                }
18923
18924                if (existing != null) {
18925                    if (DEBUG_PREFERRED) {
18926                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18927                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18928                    }
18929                    for (int i = 0; i < existing.size(); i++) {
18930                        PreferredActivity pa = existing.get(i);
18931                        if (DEBUG_PREFERRED) {
18932                            Slog.i(TAG, "Removing existing preferred activity "
18933                                    + pa.mPref.mComponent + ":");
18934                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18935                        }
18936                        pir.removeFilter(pa);
18937                    }
18938                }
18939            }
18940            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18941                    "Replacing preferred");
18942        }
18943    }
18944
18945    @Override
18946    public void clearPackagePreferredActivities(String packageName) {
18947        final int uid = Binder.getCallingUid();
18948        // writer
18949        synchronized (mPackages) {
18950            PackageParser.Package pkg = mPackages.get(packageName);
18951            if (pkg == null || pkg.applicationInfo.uid != uid) {
18952                if (mContext.checkCallingOrSelfPermission(
18953                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18954                        != PackageManager.PERMISSION_GRANTED) {
18955                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18956                            < Build.VERSION_CODES.FROYO) {
18957                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18958                                + Binder.getCallingUid());
18959                        return;
18960                    }
18961                    mContext.enforceCallingOrSelfPermission(
18962                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18963                }
18964            }
18965
18966            int user = UserHandle.getCallingUserId();
18967            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18968                scheduleWritePackageRestrictionsLocked(user);
18969            }
18970        }
18971    }
18972
18973    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18974    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18975        ArrayList<PreferredActivity> removed = null;
18976        boolean changed = false;
18977        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18978            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18979            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18980            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18981                continue;
18982            }
18983            Iterator<PreferredActivity> it = pir.filterIterator();
18984            while (it.hasNext()) {
18985                PreferredActivity pa = it.next();
18986                // Mark entry for removal only if it matches the package name
18987                // and the entry is of type "always".
18988                if (packageName == null ||
18989                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18990                                && pa.mPref.mAlways)) {
18991                    if (removed == null) {
18992                        removed = new ArrayList<PreferredActivity>();
18993                    }
18994                    removed.add(pa);
18995                }
18996            }
18997            if (removed != null) {
18998                for (int j=0; j<removed.size(); j++) {
18999                    PreferredActivity pa = removed.get(j);
19000                    pir.removeFilter(pa);
19001                }
19002                changed = true;
19003            }
19004        }
19005        if (changed) {
19006            postPreferredActivityChangedBroadcast(userId);
19007        }
19008        return changed;
19009    }
19010
19011    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19012    private void clearIntentFilterVerificationsLPw(int userId) {
19013        final int packageCount = mPackages.size();
19014        for (int i = 0; i < packageCount; i++) {
19015            PackageParser.Package pkg = mPackages.valueAt(i);
19016            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19017        }
19018    }
19019
19020    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19021    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19022        if (userId == UserHandle.USER_ALL) {
19023            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19024                    sUserManager.getUserIds())) {
19025                for (int oneUserId : sUserManager.getUserIds()) {
19026                    scheduleWritePackageRestrictionsLocked(oneUserId);
19027                }
19028            }
19029        } else {
19030            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19031                scheduleWritePackageRestrictionsLocked(userId);
19032            }
19033        }
19034    }
19035
19036    void clearDefaultBrowserIfNeeded(String packageName) {
19037        for (int oneUserId : sUserManager.getUserIds()) {
19038            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
19039            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
19040            if (packageName.equals(defaultBrowserPackageName)) {
19041                setDefaultBrowserPackageName(null, oneUserId);
19042            }
19043        }
19044    }
19045
19046    @Override
19047    public void resetApplicationPreferences(int userId) {
19048        mContext.enforceCallingOrSelfPermission(
19049                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19050        final long identity = Binder.clearCallingIdentity();
19051        // writer
19052        try {
19053            synchronized (mPackages) {
19054                clearPackagePreferredActivitiesLPw(null, userId);
19055                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19056                // TODO: We have to reset the default SMS and Phone. This requires
19057                // significant refactoring to keep all default apps in the package
19058                // manager (cleaner but more work) or have the services provide
19059                // callbacks to the package manager to request a default app reset.
19060                applyFactoryDefaultBrowserLPw(userId);
19061                clearIntentFilterVerificationsLPw(userId);
19062                primeDomainVerificationsLPw(userId);
19063                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19064                scheduleWritePackageRestrictionsLocked(userId);
19065            }
19066            resetNetworkPolicies(userId);
19067        } finally {
19068            Binder.restoreCallingIdentity(identity);
19069        }
19070    }
19071
19072    @Override
19073    public int getPreferredActivities(List<IntentFilter> outFilters,
19074            List<ComponentName> outActivities, String packageName) {
19075
19076        int num = 0;
19077        final int userId = UserHandle.getCallingUserId();
19078        // reader
19079        synchronized (mPackages) {
19080            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19081            if (pir != null) {
19082                final Iterator<PreferredActivity> it = pir.filterIterator();
19083                while (it.hasNext()) {
19084                    final PreferredActivity pa = it.next();
19085                    if (packageName == null
19086                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19087                                    && pa.mPref.mAlways)) {
19088                        if (outFilters != null) {
19089                            outFilters.add(new IntentFilter(pa));
19090                        }
19091                        if (outActivities != null) {
19092                            outActivities.add(pa.mPref.mComponent);
19093                        }
19094                    }
19095                }
19096            }
19097        }
19098
19099        return num;
19100    }
19101
19102    @Override
19103    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19104            int userId) {
19105        int callingUid = Binder.getCallingUid();
19106        if (callingUid != Process.SYSTEM_UID) {
19107            throw new SecurityException(
19108                    "addPersistentPreferredActivity can only be run by the system");
19109        }
19110        if (filter.countActions() == 0) {
19111            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19112            return;
19113        }
19114        synchronized (mPackages) {
19115            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19116                    ":");
19117            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19118            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19119                    new PersistentPreferredActivity(filter, activity));
19120            scheduleWritePackageRestrictionsLocked(userId);
19121            postPreferredActivityChangedBroadcast(userId);
19122        }
19123    }
19124
19125    @Override
19126    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19127        int callingUid = Binder.getCallingUid();
19128        if (callingUid != Process.SYSTEM_UID) {
19129            throw new SecurityException(
19130                    "clearPackagePersistentPreferredActivities can only be run by the system");
19131        }
19132        ArrayList<PersistentPreferredActivity> removed = null;
19133        boolean changed = false;
19134        synchronized (mPackages) {
19135            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19136                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19137                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19138                        .valueAt(i);
19139                if (userId != thisUserId) {
19140                    continue;
19141                }
19142                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19143                while (it.hasNext()) {
19144                    PersistentPreferredActivity ppa = it.next();
19145                    // Mark entry for removal only if it matches the package name.
19146                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19147                        if (removed == null) {
19148                            removed = new ArrayList<PersistentPreferredActivity>();
19149                        }
19150                        removed.add(ppa);
19151                    }
19152                }
19153                if (removed != null) {
19154                    for (int j=0; j<removed.size(); j++) {
19155                        PersistentPreferredActivity ppa = removed.get(j);
19156                        ppir.removeFilter(ppa);
19157                    }
19158                    changed = true;
19159                }
19160            }
19161
19162            if (changed) {
19163                scheduleWritePackageRestrictionsLocked(userId);
19164                postPreferredActivityChangedBroadcast(userId);
19165            }
19166        }
19167    }
19168
19169    /**
19170     * Common machinery for picking apart a restored XML blob and passing
19171     * it to a caller-supplied functor to be applied to the running system.
19172     */
19173    private void restoreFromXml(XmlPullParser parser, int userId,
19174            String expectedStartTag, BlobXmlRestorer functor)
19175            throws IOException, XmlPullParserException {
19176        int type;
19177        while ((type = parser.next()) != XmlPullParser.START_TAG
19178                && type != XmlPullParser.END_DOCUMENT) {
19179        }
19180        if (type != XmlPullParser.START_TAG) {
19181            // oops didn't find a start tag?!
19182            if (DEBUG_BACKUP) {
19183                Slog.e(TAG, "Didn't find start tag during restore");
19184            }
19185            return;
19186        }
19187Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19188        // this is supposed to be TAG_PREFERRED_BACKUP
19189        if (!expectedStartTag.equals(parser.getName())) {
19190            if (DEBUG_BACKUP) {
19191                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19192            }
19193            return;
19194        }
19195
19196        // skip interfering stuff, then we're aligned with the backing implementation
19197        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19198Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19199        functor.apply(parser, userId);
19200    }
19201
19202    private interface BlobXmlRestorer {
19203        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19204    }
19205
19206    /**
19207     * Non-Binder method, support for the backup/restore mechanism: write the
19208     * full set of preferred activities in its canonical XML format.  Returns the
19209     * XML output as a byte array, or null if there is none.
19210     */
19211    @Override
19212    public byte[] getPreferredActivityBackup(int userId) {
19213        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19214            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19215        }
19216
19217        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19218        try {
19219            final XmlSerializer serializer = new FastXmlSerializer();
19220            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19221            serializer.startDocument(null, true);
19222            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19223
19224            synchronized (mPackages) {
19225                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19226            }
19227
19228            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19229            serializer.endDocument();
19230            serializer.flush();
19231        } catch (Exception e) {
19232            if (DEBUG_BACKUP) {
19233                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19234            }
19235            return null;
19236        }
19237
19238        return dataStream.toByteArray();
19239    }
19240
19241    @Override
19242    public void restorePreferredActivities(byte[] backup, int userId) {
19243        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19244            throw new SecurityException("Only the system may call restorePreferredActivities()");
19245        }
19246
19247        try {
19248            final XmlPullParser parser = Xml.newPullParser();
19249            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19250            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19251                    new BlobXmlRestorer() {
19252                        @Override
19253                        public void apply(XmlPullParser parser, int userId)
19254                                throws XmlPullParserException, IOException {
19255                            synchronized (mPackages) {
19256                                mSettings.readPreferredActivitiesLPw(parser, userId);
19257                            }
19258                        }
19259                    } );
19260        } catch (Exception e) {
19261            if (DEBUG_BACKUP) {
19262                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19263            }
19264        }
19265    }
19266
19267    /**
19268     * Non-Binder method, support for the backup/restore mechanism: write the
19269     * default browser (etc) settings in its canonical XML format.  Returns the default
19270     * browser XML representation as a byte array, or null if there is none.
19271     */
19272    @Override
19273    public byte[] getDefaultAppsBackup(int userId) {
19274        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19275            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19276        }
19277
19278        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19279        try {
19280            final XmlSerializer serializer = new FastXmlSerializer();
19281            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19282            serializer.startDocument(null, true);
19283            serializer.startTag(null, TAG_DEFAULT_APPS);
19284
19285            synchronized (mPackages) {
19286                mSettings.writeDefaultAppsLPr(serializer, userId);
19287            }
19288
19289            serializer.endTag(null, TAG_DEFAULT_APPS);
19290            serializer.endDocument();
19291            serializer.flush();
19292        } catch (Exception e) {
19293            if (DEBUG_BACKUP) {
19294                Slog.e(TAG, "Unable to write default apps for backup", e);
19295            }
19296            return null;
19297        }
19298
19299        return dataStream.toByteArray();
19300    }
19301
19302    @Override
19303    public void restoreDefaultApps(byte[] backup, int userId) {
19304        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19305            throw new SecurityException("Only the system may call restoreDefaultApps()");
19306        }
19307
19308        try {
19309            final XmlPullParser parser = Xml.newPullParser();
19310            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19311            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19312                    new BlobXmlRestorer() {
19313                        @Override
19314                        public void apply(XmlPullParser parser, int userId)
19315                                throws XmlPullParserException, IOException {
19316                            synchronized (mPackages) {
19317                                mSettings.readDefaultAppsLPw(parser, userId);
19318                            }
19319                        }
19320                    } );
19321        } catch (Exception e) {
19322            if (DEBUG_BACKUP) {
19323                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19324            }
19325        }
19326    }
19327
19328    @Override
19329    public byte[] getIntentFilterVerificationBackup(int userId) {
19330        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19331            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19332        }
19333
19334        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19335        try {
19336            final XmlSerializer serializer = new FastXmlSerializer();
19337            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19338            serializer.startDocument(null, true);
19339            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19340
19341            synchronized (mPackages) {
19342                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19343            }
19344
19345            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19346            serializer.endDocument();
19347            serializer.flush();
19348        } catch (Exception e) {
19349            if (DEBUG_BACKUP) {
19350                Slog.e(TAG, "Unable to write default apps for backup", e);
19351            }
19352            return null;
19353        }
19354
19355        return dataStream.toByteArray();
19356    }
19357
19358    @Override
19359    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19360        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19361            throw new SecurityException("Only the system may call restorePreferredActivities()");
19362        }
19363
19364        try {
19365            final XmlPullParser parser = Xml.newPullParser();
19366            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19367            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19368                    new BlobXmlRestorer() {
19369                        @Override
19370                        public void apply(XmlPullParser parser, int userId)
19371                                throws XmlPullParserException, IOException {
19372                            synchronized (mPackages) {
19373                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19374                                mSettings.writeLPr();
19375                            }
19376                        }
19377                    } );
19378        } catch (Exception e) {
19379            if (DEBUG_BACKUP) {
19380                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19381            }
19382        }
19383    }
19384
19385    @Override
19386    public byte[] getPermissionGrantBackup(int userId) {
19387        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19388            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19389        }
19390
19391        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19392        try {
19393            final XmlSerializer serializer = new FastXmlSerializer();
19394            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19395            serializer.startDocument(null, true);
19396            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19397
19398            synchronized (mPackages) {
19399                serializeRuntimePermissionGrantsLPr(serializer, userId);
19400            }
19401
19402            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19403            serializer.endDocument();
19404            serializer.flush();
19405        } catch (Exception e) {
19406            if (DEBUG_BACKUP) {
19407                Slog.e(TAG, "Unable to write default apps for backup", e);
19408            }
19409            return null;
19410        }
19411
19412        return dataStream.toByteArray();
19413    }
19414
19415    @Override
19416    public void restorePermissionGrants(byte[] backup, int userId) {
19417        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19418            throw new SecurityException("Only the system may call restorePermissionGrants()");
19419        }
19420
19421        try {
19422            final XmlPullParser parser = Xml.newPullParser();
19423            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19424            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19425                    new BlobXmlRestorer() {
19426                        @Override
19427                        public void apply(XmlPullParser parser, int userId)
19428                                throws XmlPullParserException, IOException {
19429                            synchronized (mPackages) {
19430                                processRestoredPermissionGrantsLPr(parser, userId);
19431                            }
19432                        }
19433                    } );
19434        } catch (Exception e) {
19435            if (DEBUG_BACKUP) {
19436                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19437            }
19438        }
19439    }
19440
19441    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19442            throws IOException {
19443        serializer.startTag(null, TAG_ALL_GRANTS);
19444
19445        final int N = mSettings.mPackages.size();
19446        for (int i = 0; i < N; i++) {
19447            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19448            boolean pkgGrantsKnown = false;
19449
19450            PermissionsState packagePerms = ps.getPermissionsState();
19451
19452            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19453                final int grantFlags = state.getFlags();
19454                // only look at grants that are not system/policy fixed
19455                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19456                    final boolean isGranted = state.isGranted();
19457                    // And only back up the user-twiddled state bits
19458                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19459                        final String packageName = mSettings.mPackages.keyAt(i);
19460                        if (!pkgGrantsKnown) {
19461                            serializer.startTag(null, TAG_GRANT);
19462                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19463                            pkgGrantsKnown = true;
19464                        }
19465
19466                        final boolean userSet =
19467                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19468                        final boolean userFixed =
19469                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19470                        final boolean revoke =
19471                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19472
19473                        serializer.startTag(null, TAG_PERMISSION);
19474                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19475                        if (isGranted) {
19476                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19477                        }
19478                        if (userSet) {
19479                            serializer.attribute(null, ATTR_USER_SET, "true");
19480                        }
19481                        if (userFixed) {
19482                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19483                        }
19484                        if (revoke) {
19485                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19486                        }
19487                        serializer.endTag(null, TAG_PERMISSION);
19488                    }
19489                }
19490            }
19491
19492            if (pkgGrantsKnown) {
19493                serializer.endTag(null, TAG_GRANT);
19494            }
19495        }
19496
19497        serializer.endTag(null, TAG_ALL_GRANTS);
19498    }
19499
19500    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19501            throws XmlPullParserException, IOException {
19502        String pkgName = null;
19503        int outerDepth = parser.getDepth();
19504        int type;
19505        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19506                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19507            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19508                continue;
19509            }
19510
19511            final String tagName = parser.getName();
19512            if (tagName.equals(TAG_GRANT)) {
19513                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19514                if (DEBUG_BACKUP) {
19515                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19516                }
19517            } else if (tagName.equals(TAG_PERMISSION)) {
19518
19519                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19520                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19521
19522                int newFlagSet = 0;
19523                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19524                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19525                }
19526                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19527                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19528                }
19529                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19530                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19531                }
19532                if (DEBUG_BACKUP) {
19533                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19534                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19535                }
19536                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19537                if (ps != null) {
19538                    // Already installed so we apply the grant immediately
19539                    if (DEBUG_BACKUP) {
19540                        Slog.v(TAG, "        + already installed; applying");
19541                    }
19542                    PermissionsState perms = ps.getPermissionsState();
19543                    BasePermission bp = mSettings.mPermissions.get(permName);
19544                    if (bp != null) {
19545                        if (isGranted) {
19546                            perms.grantRuntimePermission(bp, userId);
19547                        }
19548                        if (newFlagSet != 0) {
19549                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19550                        }
19551                    }
19552                } else {
19553                    // Need to wait for post-restore install to apply the grant
19554                    if (DEBUG_BACKUP) {
19555                        Slog.v(TAG, "        - not yet installed; saving for later");
19556                    }
19557                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19558                            isGranted, newFlagSet, userId);
19559                }
19560            } else {
19561                PackageManagerService.reportSettingsProblem(Log.WARN,
19562                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19563                XmlUtils.skipCurrentTag(parser);
19564            }
19565        }
19566
19567        scheduleWriteSettingsLocked();
19568        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19569    }
19570
19571    @Override
19572    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19573            int sourceUserId, int targetUserId, int flags) {
19574        mContext.enforceCallingOrSelfPermission(
19575                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19576        int callingUid = Binder.getCallingUid();
19577        enforceOwnerRights(ownerPackage, callingUid);
19578        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19579        if (intentFilter.countActions() == 0) {
19580            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19581            return;
19582        }
19583        synchronized (mPackages) {
19584            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19585                    ownerPackage, targetUserId, flags);
19586            CrossProfileIntentResolver resolver =
19587                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19588            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19589            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19590            if (existing != null) {
19591                int size = existing.size();
19592                for (int i = 0; i < size; i++) {
19593                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19594                        return;
19595                    }
19596                }
19597            }
19598            resolver.addFilter(newFilter);
19599            scheduleWritePackageRestrictionsLocked(sourceUserId);
19600        }
19601    }
19602
19603    @Override
19604    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19605        mContext.enforceCallingOrSelfPermission(
19606                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19607        int callingUid = Binder.getCallingUid();
19608        enforceOwnerRights(ownerPackage, callingUid);
19609        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19610        synchronized (mPackages) {
19611            CrossProfileIntentResolver resolver =
19612                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19613            ArraySet<CrossProfileIntentFilter> set =
19614                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19615            for (CrossProfileIntentFilter filter : set) {
19616                if (filter.getOwnerPackage().equals(ownerPackage)) {
19617                    resolver.removeFilter(filter);
19618                }
19619            }
19620            scheduleWritePackageRestrictionsLocked(sourceUserId);
19621        }
19622    }
19623
19624    // Enforcing that callingUid is owning pkg on userId
19625    private void enforceOwnerRights(String pkg, int callingUid) {
19626        // The system owns everything.
19627        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19628            return;
19629        }
19630        int callingUserId = UserHandle.getUserId(callingUid);
19631        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19632        if (pi == null) {
19633            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19634                    + callingUserId);
19635        }
19636        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19637            throw new SecurityException("Calling uid " + callingUid
19638                    + " does not own package " + pkg);
19639        }
19640    }
19641
19642    @Override
19643    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19644        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19645    }
19646
19647    private Intent getHomeIntent() {
19648        Intent intent = new Intent(Intent.ACTION_MAIN);
19649        intent.addCategory(Intent.CATEGORY_HOME);
19650        intent.addCategory(Intent.CATEGORY_DEFAULT);
19651        return intent;
19652    }
19653
19654    private IntentFilter getHomeFilter() {
19655        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19656        filter.addCategory(Intent.CATEGORY_HOME);
19657        filter.addCategory(Intent.CATEGORY_DEFAULT);
19658        return filter;
19659    }
19660
19661    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19662            int userId) {
19663        Intent intent  = getHomeIntent();
19664        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19665                PackageManager.GET_META_DATA, userId);
19666        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19667                true, false, false, userId);
19668
19669        allHomeCandidates.clear();
19670        if (list != null) {
19671            for (ResolveInfo ri : list) {
19672                allHomeCandidates.add(ri);
19673            }
19674        }
19675        return (preferred == null || preferred.activityInfo == null)
19676                ? null
19677                : new ComponentName(preferred.activityInfo.packageName,
19678                        preferred.activityInfo.name);
19679    }
19680
19681    @Override
19682    public void setHomeActivity(ComponentName comp, int userId) {
19683        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19684        getHomeActivitiesAsUser(homeActivities, userId);
19685
19686        boolean found = false;
19687
19688        final int size = homeActivities.size();
19689        final ComponentName[] set = new ComponentName[size];
19690        for (int i = 0; i < size; i++) {
19691            final ResolveInfo candidate = homeActivities.get(i);
19692            final ActivityInfo info = candidate.activityInfo;
19693            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19694            set[i] = activityName;
19695            if (!found && activityName.equals(comp)) {
19696                found = true;
19697            }
19698        }
19699        if (!found) {
19700            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19701                    + userId);
19702        }
19703        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19704                set, comp, userId);
19705    }
19706
19707    private @Nullable String getSetupWizardPackageName() {
19708        final Intent intent = new Intent(Intent.ACTION_MAIN);
19709        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19710
19711        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19712                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19713                        | MATCH_DISABLED_COMPONENTS,
19714                UserHandle.myUserId());
19715        if (matches.size() == 1) {
19716            return matches.get(0).getComponentInfo().packageName;
19717        } else {
19718            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19719                    + ": matches=" + matches);
19720            return null;
19721        }
19722    }
19723
19724    private @Nullable String getStorageManagerPackageName() {
19725        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19726
19727        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19728                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19729                        | MATCH_DISABLED_COMPONENTS,
19730                UserHandle.myUserId());
19731        if (matches.size() == 1) {
19732            return matches.get(0).getComponentInfo().packageName;
19733        } else {
19734            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19735                    + matches.size() + ": matches=" + matches);
19736            return null;
19737        }
19738    }
19739
19740    @Override
19741    public void setApplicationEnabledSetting(String appPackageName,
19742            int newState, int flags, int userId, String callingPackage) {
19743        if (!sUserManager.exists(userId)) return;
19744        if (callingPackage == null) {
19745            callingPackage = Integer.toString(Binder.getCallingUid());
19746        }
19747        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19748    }
19749
19750    @Override
19751    public void setComponentEnabledSetting(ComponentName componentName,
19752            int newState, int flags, int userId) {
19753        if (!sUserManager.exists(userId)) return;
19754        setEnabledSetting(componentName.getPackageName(),
19755                componentName.getClassName(), newState, flags, userId, null);
19756    }
19757
19758    private void setEnabledSetting(final String packageName, String className, int newState,
19759            final int flags, int userId, String callingPackage) {
19760        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19761              || newState == COMPONENT_ENABLED_STATE_ENABLED
19762              || newState == COMPONENT_ENABLED_STATE_DISABLED
19763              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19764              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19765            throw new IllegalArgumentException("Invalid new component state: "
19766                    + newState);
19767        }
19768        PackageSetting pkgSetting;
19769        final int uid = Binder.getCallingUid();
19770        final int permission;
19771        if (uid == Process.SYSTEM_UID) {
19772            permission = PackageManager.PERMISSION_GRANTED;
19773        } else {
19774            permission = mContext.checkCallingOrSelfPermission(
19775                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19776        }
19777        enforceCrossUserPermission(uid, userId,
19778                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19779        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19780        boolean sendNow = false;
19781        boolean isApp = (className == null);
19782        String componentName = isApp ? packageName : className;
19783        int packageUid = -1;
19784        ArrayList<String> components;
19785
19786        // writer
19787        synchronized (mPackages) {
19788            pkgSetting = mSettings.mPackages.get(packageName);
19789            if (pkgSetting == null) {
19790                if (className == null) {
19791                    throw new IllegalArgumentException("Unknown package: " + packageName);
19792                }
19793                throw new IllegalArgumentException(
19794                        "Unknown component: " + packageName + "/" + className);
19795            }
19796        }
19797
19798        // Limit who can change which apps
19799        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19800            // Don't allow apps that don't have permission to modify other apps
19801            if (!allowedByPermission) {
19802                throw new SecurityException(
19803                        "Permission Denial: attempt to change component state from pid="
19804                        + Binder.getCallingPid()
19805                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19806            }
19807            // Don't allow changing protected packages.
19808            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19809                throw new SecurityException("Cannot disable a protected package: " + packageName);
19810            }
19811        }
19812
19813        synchronized (mPackages) {
19814            if (uid == Process.SHELL_UID
19815                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19816                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19817                // unless it is a test package.
19818                int oldState = pkgSetting.getEnabled(userId);
19819                if (className == null
19820                    &&
19821                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19822                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19823                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19824                    &&
19825                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19826                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19827                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19828                    // ok
19829                } else {
19830                    throw new SecurityException(
19831                            "Shell cannot change component state for " + packageName + "/"
19832                            + className + " to " + newState);
19833                }
19834            }
19835            if (className == null) {
19836                // We're dealing with an application/package level state change
19837                if (pkgSetting.getEnabled(userId) == newState) {
19838                    // Nothing to do
19839                    return;
19840                }
19841                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19842                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19843                    // Don't care about who enables an app.
19844                    callingPackage = null;
19845                }
19846                pkgSetting.setEnabled(newState, userId, callingPackage);
19847                // pkgSetting.pkg.mSetEnabled = newState;
19848            } else {
19849                // We're dealing with a component level state change
19850                // First, verify that this is a valid class name.
19851                PackageParser.Package pkg = pkgSetting.pkg;
19852                if (pkg == null || !pkg.hasComponentClassName(className)) {
19853                    if (pkg != null &&
19854                            pkg.applicationInfo.targetSdkVersion >=
19855                                    Build.VERSION_CODES.JELLY_BEAN) {
19856                        throw new IllegalArgumentException("Component class " + className
19857                                + " does not exist in " + packageName);
19858                    } else {
19859                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19860                                + className + " does not exist in " + packageName);
19861                    }
19862                }
19863                switch (newState) {
19864                case COMPONENT_ENABLED_STATE_ENABLED:
19865                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19866                        return;
19867                    }
19868                    break;
19869                case COMPONENT_ENABLED_STATE_DISABLED:
19870                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19871                        return;
19872                    }
19873                    break;
19874                case COMPONENT_ENABLED_STATE_DEFAULT:
19875                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19876                        return;
19877                    }
19878                    break;
19879                default:
19880                    Slog.e(TAG, "Invalid new component state: " + newState);
19881                    return;
19882                }
19883            }
19884            scheduleWritePackageRestrictionsLocked(userId);
19885            updateSequenceNumberLP(packageName, new int[] { userId });
19886            components = mPendingBroadcasts.get(userId, packageName);
19887            final boolean newPackage = components == null;
19888            if (newPackage) {
19889                components = new ArrayList<String>();
19890            }
19891            if (!components.contains(componentName)) {
19892                components.add(componentName);
19893            }
19894            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19895                sendNow = true;
19896                // Purge entry from pending broadcast list if another one exists already
19897                // since we are sending one right away.
19898                mPendingBroadcasts.remove(userId, packageName);
19899            } else {
19900                if (newPackage) {
19901                    mPendingBroadcasts.put(userId, packageName, components);
19902                }
19903                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19904                    // Schedule a message
19905                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19906                }
19907            }
19908        }
19909
19910        long callingId = Binder.clearCallingIdentity();
19911        try {
19912            if (sendNow) {
19913                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19914                sendPackageChangedBroadcast(packageName,
19915                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19916            }
19917        } finally {
19918            Binder.restoreCallingIdentity(callingId);
19919        }
19920    }
19921
19922    @Override
19923    public void flushPackageRestrictionsAsUser(int userId) {
19924        if (!sUserManager.exists(userId)) {
19925            return;
19926        }
19927        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19928                false /* checkShell */, "flushPackageRestrictions");
19929        synchronized (mPackages) {
19930            mSettings.writePackageRestrictionsLPr(userId);
19931            mDirtyUsers.remove(userId);
19932            if (mDirtyUsers.isEmpty()) {
19933                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19934            }
19935        }
19936    }
19937
19938    private void sendPackageChangedBroadcast(String packageName,
19939            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19940        if (DEBUG_INSTALL)
19941            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19942                    + componentNames);
19943        Bundle extras = new Bundle(4);
19944        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19945        String nameList[] = new String[componentNames.size()];
19946        componentNames.toArray(nameList);
19947        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19948        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19949        extras.putInt(Intent.EXTRA_UID, packageUid);
19950        // If this is not reporting a change of the overall package, then only send it
19951        // to registered receivers.  We don't want to launch a swath of apps for every
19952        // little component state change.
19953        final int flags = !componentNames.contains(packageName)
19954                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19955        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19956                new int[] {UserHandle.getUserId(packageUid)});
19957    }
19958
19959    @Override
19960    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19961        if (!sUserManager.exists(userId)) return;
19962        final int uid = Binder.getCallingUid();
19963        final int permission = mContext.checkCallingOrSelfPermission(
19964                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19965        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19966        enforceCrossUserPermission(uid, userId,
19967                true /* requireFullPermission */, true /* checkShell */, "stop package");
19968        // writer
19969        synchronized (mPackages) {
19970            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19971                    allowedByPermission, uid, userId)) {
19972                scheduleWritePackageRestrictionsLocked(userId);
19973            }
19974        }
19975    }
19976
19977    @Override
19978    public String getInstallerPackageName(String packageName) {
19979        // reader
19980        synchronized (mPackages) {
19981            return mSettings.getInstallerPackageNameLPr(packageName);
19982        }
19983    }
19984
19985    public boolean isOrphaned(String packageName) {
19986        // reader
19987        synchronized (mPackages) {
19988            return mSettings.isOrphaned(packageName);
19989        }
19990    }
19991
19992    @Override
19993    public int getApplicationEnabledSetting(String packageName, int userId) {
19994        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19995        int uid = Binder.getCallingUid();
19996        enforceCrossUserPermission(uid, userId,
19997                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19998        // reader
19999        synchronized (mPackages) {
20000            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20001        }
20002    }
20003
20004    @Override
20005    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20006        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20007        int uid = Binder.getCallingUid();
20008        enforceCrossUserPermission(uid, userId,
20009                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20010        // reader
20011        synchronized (mPackages) {
20012            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20013        }
20014    }
20015
20016    @Override
20017    public void enterSafeMode() {
20018        enforceSystemOrRoot("Only the system can request entering safe mode");
20019
20020        if (!mSystemReady) {
20021            mSafeMode = true;
20022        }
20023    }
20024
20025    @Override
20026    public void systemReady() {
20027        mSystemReady = true;
20028
20029        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20030        // disabled after already being started.
20031        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20032                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20033
20034        // Read the compatibilty setting when the system is ready.
20035        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20036                mContext.getContentResolver(),
20037                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20038        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20039        if (DEBUG_SETTINGS) {
20040            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20041        }
20042
20043        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20044
20045        synchronized (mPackages) {
20046            // Verify that all of the preferred activity components actually
20047            // exist.  It is possible for applications to be updated and at
20048            // that point remove a previously declared activity component that
20049            // had been set as a preferred activity.  We try to clean this up
20050            // the next time we encounter that preferred activity, but it is
20051            // possible for the user flow to never be able to return to that
20052            // situation so here we do a sanity check to make sure we haven't
20053            // left any junk around.
20054            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20055            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20056                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20057                removed.clear();
20058                for (PreferredActivity pa : pir.filterSet()) {
20059                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20060                        removed.add(pa);
20061                    }
20062                }
20063                if (removed.size() > 0) {
20064                    for (int r=0; r<removed.size(); r++) {
20065                        PreferredActivity pa = removed.get(r);
20066                        Slog.w(TAG, "Removing dangling preferred activity: "
20067                                + pa.mPref.mComponent);
20068                        pir.removeFilter(pa);
20069                    }
20070                    mSettings.writePackageRestrictionsLPr(
20071                            mSettings.mPreferredActivities.keyAt(i));
20072                }
20073            }
20074
20075            for (int userId : UserManagerService.getInstance().getUserIds()) {
20076                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20077                    grantPermissionsUserIds = ArrayUtils.appendInt(
20078                            grantPermissionsUserIds, userId);
20079                }
20080            }
20081        }
20082        sUserManager.systemReady();
20083
20084        // If we upgraded grant all default permissions before kicking off.
20085        for (int userId : grantPermissionsUserIds) {
20086            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20087        }
20088
20089        // If we did not grant default permissions, we preload from this the
20090        // default permission exceptions lazily to ensure we don't hit the
20091        // disk on a new user creation.
20092        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20093            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20094        }
20095
20096        // Kick off any messages waiting for system ready
20097        if (mPostSystemReadyMessages != null) {
20098            for (Message msg : mPostSystemReadyMessages) {
20099                msg.sendToTarget();
20100            }
20101            mPostSystemReadyMessages = null;
20102        }
20103
20104        // Watch for external volumes that come and go over time
20105        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20106        storage.registerListener(mStorageListener);
20107
20108        mInstallerService.systemReady();
20109        mPackageDexOptimizer.systemReady();
20110
20111        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20112                StorageManagerInternal.class);
20113        StorageManagerInternal.addExternalStoragePolicy(
20114                new StorageManagerInternal.ExternalStorageMountPolicy() {
20115            @Override
20116            public int getMountMode(int uid, String packageName) {
20117                if (Process.isIsolated(uid)) {
20118                    return Zygote.MOUNT_EXTERNAL_NONE;
20119                }
20120                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20121                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20122                }
20123                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20124                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20125                }
20126                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20127                    return Zygote.MOUNT_EXTERNAL_READ;
20128                }
20129                return Zygote.MOUNT_EXTERNAL_WRITE;
20130            }
20131
20132            @Override
20133            public boolean hasExternalStorage(int uid, String packageName) {
20134                return true;
20135            }
20136        });
20137
20138        // Now that we're mostly running, clean up stale users and apps
20139        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20140        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20141
20142        if (mPrivappPermissionsViolations != null) {
20143            Slog.wtf(TAG,"Signature|privileged permissions not in "
20144                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20145            mPrivappPermissionsViolations = null;
20146        }
20147    }
20148
20149    public void waitForAppDataPrepared() {
20150        if (mPrepareAppDataFuture == null) {
20151            return;
20152        }
20153        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20154        mPrepareAppDataFuture = null;
20155    }
20156
20157    @Override
20158    public boolean isSafeMode() {
20159        return mSafeMode;
20160    }
20161
20162    @Override
20163    public boolean hasSystemUidErrors() {
20164        return mHasSystemUidErrors;
20165    }
20166
20167    static String arrayToString(int[] array) {
20168        StringBuffer buf = new StringBuffer(128);
20169        buf.append('[');
20170        if (array != null) {
20171            for (int i=0; i<array.length; i++) {
20172                if (i > 0) buf.append(", ");
20173                buf.append(array[i]);
20174            }
20175        }
20176        buf.append(']');
20177        return buf.toString();
20178    }
20179
20180    static class DumpState {
20181        public static final int DUMP_LIBS = 1 << 0;
20182        public static final int DUMP_FEATURES = 1 << 1;
20183        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20184        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20185        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20186        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20187        public static final int DUMP_PERMISSIONS = 1 << 6;
20188        public static final int DUMP_PACKAGES = 1 << 7;
20189        public static final int DUMP_SHARED_USERS = 1 << 8;
20190        public static final int DUMP_MESSAGES = 1 << 9;
20191        public static final int DUMP_PROVIDERS = 1 << 10;
20192        public static final int DUMP_VERIFIERS = 1 << 11;
20193        public static final int DUMP_PREFERRED = 1 << 12;
20194        public static final int DUMP_PREFERRED_XML = 1 << 13;
20195        public static final int DUMP_KEYSETS = 1 << 14;
20196        public static final int DUMP_VERSION = 1 << 15;
20197        public static final int DUMP_INSTALLS = 1 << 16;
20198        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20199        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20200        public static final int DUMP_FROZEN = 1 << 19;
20201        public static final int DUMP_DEXOPT = 1 << 20;
20202        public static final int DUMP_COMPILER_STATS = 1 << 21;
20203        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20204
20205        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20206
20207        private int mTypes;
20208
20209        private int mOptions;
20210
20211        private boolean mTitlePrinted;
20212
20213        private SharedUserSetting mSharedUser;
20214
20215        public boolean isDumping(int type) {
20216            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20217                return true;
20218            }
20219
20220            return (mTypes & type) != 0;
20221        }
20222
20223        public void setDump(int type) {
20224            mTypes |= type;
20225        }
20226
20227        public boolean isOptionEnabled(int option) {
20228            return (mOptions & option) != 0;
20229        }
20230
20231        public void setOptionEnabled(int option) {
20232            mOptions |= option;
20233        }
20234
20235        public boolean onTitlePrinted() {
20236            final boolean printed = mTitlePrinted;
20237            mTitlePrinted = true;
20238            return printed;
20239        }
20240
20241        public boolean getTitlePrinted() {
20242            return mTitlePrinted;
20243        }
20244
20245        public void setTitlePrinted(boolean enabled) {
20246            mTitlePrinted = enabled;
20247        }
20248
20249        public SharedUserSetting getSharedUser() {
20250            return mSharedUser;
20251        }
20252
20253        public void setSharedUser(SharedUserSetting user) {
20254            mSharedUser = user;
20255        }
20256    }
20257
20258    @Override
20259    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20260            FileDescriptor err, String[] args, ShellCallback callback,
20261            ResultReceiver resultReceiver) {
20262        (new PackageManagerShellCommand(this)).exec(
20263                this, in, out, err, args, callback, resultReceiver);
20264    }
20265
20266    @Override
20267    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20268        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20269                != PackageManager.PERMISSION_GRANTED) {
20270            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20271                    + Binder.getCallingPid()
20272                    + ", uid=" + Binder.getCallingUid()
20273                    + " without permission "
20274                    + android.Manifest.permission.DUMP);
20275            return;
20276        }
20277
20278        DumpState dumpState = new DumpState();
20279        boolean fullPreferred = false;
20280        boolean checkin = false;
20281
20282        String packageName = null;
20283        ArraySet<String> permissionNames = null;
20284
20285        int opti = 0;
20286        while (opti < args.length) {
20287            String opt = args[opti];
20288            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20289                break;
20290            }
20291            opti++;
20292
20293            if ("-a".equals(opt)) {
20294                // Right now we only know how to print all.
20295            } else if ("-h".equals(opt)) {
20296                pw.println("Package manager dump options:");
20297                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20298                pw.println("    --checkin: dump for a checkin");
20299                pw.println("    -f: print details of intent filters");
20300                pw.println("    -h: print this help");
20301                pw.println("  cmd may be one of:");
20302                pw.println("    l[ibraries]: list known shared libraries");
20303                pw.println("    f[eatures]: list device features");
20304                pw.println("    k[eysets]: print known keysets");
20305                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20306                pw.println("    perm[issions]: dump permissions");
20307                pw.println("    permission [name ...]: dump declaration and use of given permission");
20308                pw.println("    pref[erred]: print preferred package settings");
20309                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20310                pw.println("    prov[iders]: dump content providers");
20311                pw.println("    p[ackages]: dump installed packages");
20312                pw.println("    s[hared-users]: dump shared user IDs");
20313                pw.println("    m[essages]: print collected runtime messages");
20314                pw.println("    v[erifiers]: print package verifier info");
20315                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20316                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20317                pw.println("    version: print database version info");
20318                pw.println("    write: write current settings now");
20319                pw.println("    installs: details about install sessions");
20320                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20321                pw.println("    dexopt: dump dexopt state");
20322                pw.println("    compiler-stats: dump compiler statistics");
20323                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20324                pw.println("    <package.name>: info about given package");
20325                return;
20326            } else if ("--checkin".equals(opt)) {
20327                checkin = true;
20328            } else if ("-f".equals(opt)) {
20329                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20330            } else if ("--proto".equals(opt)) {
20331                dumpProto(fd);
20332                return;
20333            } else {
20334                pw.println("Unknown argument: " + opt + "; use -h for help");
20335            }
20336        }
20337
20338        // Is the caller requesting to dump a particular piece of data?
20339        if (opti < args.length) {
20340            String cmd = args[opti];
20341            opti++;
20342            // Is this a package name?
20343            if ("android".equals(cmd) || cmd.contains(".")) {
20344                packageName = cmd;
20345                // When dumping a single package, we always dump all of its
20346                // filter information since the amount of data will be reasonable.
20347                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20348            } else if ("check-permission".equals(cmd)) {
20349                if (opti >= args.length) {
20350                    pw.println("Error: check-permission missing permission argument");
20351                    return;
20352                }
20353                String perm = args[opti];
20354                opti++;
20355                if (opti >= args.length) {
20356                    pw.println("Error: check-permission missing package argument");
20357                    return;
20358                }
20359
20360                String pkg = args[opti];
20361                opti++;
20362                int user = UserHandle.getUserId(Binder.getCallingUid());
20363                if (opti < args.length) {
20364                    try {
20365                        user = Integer.parseInt(args[opti]);
20366                    } catch (NumberFormatException e) {
20367                        pw.println("Error: check-permission user argument is not a number: "
20368                                + args[opti]);
20369                        return;
20370                    }
20371                }
20372
20373                // Normalize package name to handle renamed packages and static libs
20374                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20375
20376                pw.println(checkPermission(perm, pkg, user));
20377                return;
20378            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20379                dumpState.setDump(DumpState.DUMP_LIBS);
20380            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20381                dumpState.setDump(DumpState.DUMP_FEATURES);
20382            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20383                if (opti >= args.length) {
20384                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20385                            | DumpState.DUMP_SERVICE_RESOLVERS
20386                            | DumpState.DUMP_RECEIVER_RESOLVERS
20387                            | DumpState.DUMP_CONTENT_RESOLVERS);
20388                } else {
20389                    while (opti < args.length) {
20390                        String name = args[opti];
20391                        if ("a".equals(name) || "activity".equals(name)) {
20392                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20393                        } else if ("s".equals(name) || "service".equals(name)) {
20394                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20395                        } else if ("r".equals(name) || "receiver".equals(name)) {
20396                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20397                        } else if ("c".equals(name) || "content".equals(name)) {
20398                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20399                        } else {
20400                            pw.println("Error: unknown resolver table type: " + name);
20401                            return;
20402                        }
20403                        opti++;
20404                    }
20405                }
20406            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20407                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20408            } else if ("permission".equals(cmd)) {
20409                if (opti >= args.length) {
20410                    pw.println("Error: permission requires permission name");
20411                    return;
20412                }
20413                permissionNames = new ArraySet<>();
20414                while (opti < args.length) {
20415                    permissionNames.add(args[opti]);
20416                    opti++;
20417                }
20418                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20419                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20420            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20421                dumpState.setDump(DumpState.DUMP_PREFERRED);
20422            } else if ("preferred-xml".equals(cmd)) {
20423                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20424                if (opti < args.length && "--full".equals(args[opti])) {
20425                    fullPreferred = true;
20426                    opti++;
20427                }
20428            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20429                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20430            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20431                dumpState.setDump(DumpState.DUMP_PACKAGES);
20432            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20433                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20434            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20435                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20436            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20437                dumpState.setDump(DumpState.DUMP_MESSAGES);
20438            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20439                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20440            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20441                    || "intent-filter-verifiers".equals(cmd)) {
20442                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20443            } else if ("version".equals(cmd)) {
20444                dumpState.setDump(DumpState.DUMP_VERSION);
20445            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20446                dumpState.setDump(DumpState.DUMP_KEYSETS);
20447            } else if ("installs".equals(cmd)) {
20448                dumpState.setDump(DumpState.DUMP_INSTALLS);
20449            } else if ("frozen".equals(cmd)) {
20450                dumpState.setDump(DumpState.DUMP_FROZEN);
20451            } else if ("dexopt".equals(cmd)) {
20452                dumpState.setDump(DumpState.DUMP_DEXOPT);
20453            } else if ("compiler-stats".equals(cmd)) {
20454                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20455            } else if ("enabled-overlays".equals(cmd)) {
20456                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20457            } else if ("write".equals(cmd)) {
20458                synchronized (mPackages) {
20459                    mSettings.writeLPr();
20460                    pw.println("Settings written.");
20461                    return;
20462                }
20463            }
20464        }
20465
20466        if (checkin) {
20467            pw.println("vers,1");
20468        }
20469
20470        // reader
20471        synchronized (mPackages) {
20472            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20473                if (!checkin) {
20474                    if (dumpState.onTitlePrinted())
20475                        pw.println();
20476                    pw.println("Database versions:");
20477                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20478                }
20479            }
20480
20481            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20482                if (!checkin) {
20483                    if (dumpState.onTitlePrinted())
20484                        pw.println();
20485                    pw.println("Verifiers:");
20486                    pw.print("  Required: ");
20487                    pw.print(mRequiredVerifierPackage);
20488                    pw.print(" (uid=");
20489                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20490                            UserHandle.USER_SYSTEM));
20491                    pw.println(")");
20492                } else if (mRequiredVerifierPackage != null) {
20493                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20494                    pw.print(",");
20495                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20496                            UserHandle.USER_SYSTEM));
20497                }
20498            }
20499
20500            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20501                    packageName == null) {
20502                if (mIntentFilterVerifierComponent != null) {
20503                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20504                    if (!checkin) {
20505                        if (dumpState.onTitlePrinted())
20506                            pw.println();
20507                        pw.println("Intent Filter Verifier:");
20508                        pw.print("  Using: ");
20509                        pw.print(verifierPackageName);
20510                        pw.print(" (uid=");
20511                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20512                                UserHandle.USER_SYSTEM));
20513                        pw.println(")");
20514                    } else if (verifierPackageName != null) {
20515                        pw.print("ifv,"); pw.print(verifierPackageName);
20516                        pw.print(",");
20517                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20518                                UserHandle.USER_SYSTEM));
20519                    }
20520                } else {
20521                    pw.println();
20522                    pw.println("No Intent Filter Verifier available!");
20523                }
20524            }
20525
20526            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20527                boolean printedHeader = false;
20528                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20529                while (it.hasNext()) {
20530                    String libName = it.next();
20531                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20532                    if (versionedLib == null) {
20533                        continue;
20534                    }
20535                    final int versionCount = versionedLib.size();
20536                    for (int i = 0; i < versionCount; i++) {
20537                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20538                        if (!checkin) {
20539                            if (!printedHeader) {
20540                                if (dumpState.onTitlePrinted())
20541                                    pw.println();
20542                                pw.println("Libraries:");
20543                                printedHeader = true;
20544                            }
20545                            pw.print("  ");
20546                        } else {
20547                            pw.print("lib,");
20548                        }
20549                        pw.print(libEntry.info.getName());
20550                        if (libEntry.info.isStatic()) {
20551                            pw.print(" version=" + libEntry.info.getVersion());
20552                        }
20553                        if (!checkin) {
20554                            pw.print(" -> ");
20555                        }
20556                        if (libEntry.path != null) {
20557                            pw.print(" (jar) ");
20558                            pw.print(libEntry.path);
20559                        } else {
20560                            pw.print(" (apk) ");
20561                            pw.print(libEntry.apk);
20562                        }
20563                        pw.println();
20564                    }
20565                }
20566            }
20567
20568            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20569                if (dumpState.onTitlePrinted())
20570                    pw.println();
20571                if (!checkin) {
20572                    pw.println("Features:");
20573                }
20574
20575                synchronized (mAvailableFeatures) {
20576                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20577                        if (checkin) {
20578                            pw.print("feat,");
20579                            pw.print(feat.name);
20580                            pw.print(",");
20581                            pw.println(feat.version);
20582                        } else {
20583                            pw.print("  ");
20584                            pw.print(feat.name);
20585                            if (feat.version > 0) {
20586                                pw.print(" version=");
20587                                pw.print(feat.version);
20588                            }
20589                            pw.println();
20590                        }
20591                    }
20592                }
20593            }
20594
20595            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20596                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20597                        : "Activity Resolver Table:", "  ", packageName,
20598                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20599                    dumpState.setTitlePrinted(true);
20600                }
20601            }
20602            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20603                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20604                        : "Receiver Resolver Table:", "  ", packageName,
20605                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20606                    dumpState.setTitlePrinted(true);
20607                }
20608            }
20609            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20610                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20611                        : "Service Resolver Table:", "  ", packageName,
20612                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20613                    dumpState.setTitlePrinted(true);
20614                }
20615            }
20616            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20617                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20618                        : "Provider Resolver Table:", "  ", packageName,
20619                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20620                    dumpState.setTitlePrinted(true);
20621                }
20622            }
20623
20624            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20625                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20626                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20627                    int user = mSettings.mPreferredActivities.keyAt(i);
20628                    if (pir.dump(pw,
20629                            dumpState.getTitlePrinted()
20630                                ? "\nPreferred Activities User " + user + ":"
20631                                : "Preferred Activities User " + user + ":", "  ",
20632                            packageName, true, false)) {
20633                        dumpState.setTitlePrinted(true);
20634                    }
20635                }
20636            }
20637
20638            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20639                pw.flush();
20640                FileOutputStream fout = new FileOutputStream(fd);
20641                BufferedOutputStream str = new BufferedOutputStream(fout);
20642                XmlSerializer serializer = new FastXmlSerializer();
20643                try {
20644                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20645                    serializer.startDocument(null, true);
20646                    serializer.setFeature(
20647                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20648                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20649                    serializer.endDocument();
20650                    serializer.flush();
20651                } catch (IllegalArgumentException e) {
20652                    pw.println("Failed writing: " + e);
20653                } catch (IllegalStateException e) {
20654                    pw.println("Failed writing: " + e);
20655                } catch (IOException e) {
20656                    pw.println("Failed writing: " + e);
20657                }
20658            }
20659
20660            if (!checkin
20661                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20662                    && packageName == null) {
20663                pw.println();
20664                int count = mSettings.mPackages.size();
20665                if (count == 0) {
20666                    pw.println("No applications!");
20667                    pw.println();
20668                } else {
20669                    final String prefix = "  ";
20670                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20671                    if (allPackageSettings.size() == 0) {
20672                        pw.println("No domain preferred apps!");
20673                        pw.println();
20674                    } else {
20675                        pw.println("App verification status:");
20676                        pw.println();
20677                        count = 0;
20678                        for (PackageSetting ps : allPackageSettings) {
20679                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20680                            if (ivi == null || ivi.getPackageName() == null) continue;
20681                            pw.println(prefix + "Package: " + ivi.getPackageName());
20682                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20683                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20684                            pw.println();
20685                            count++;
20686                        }
20687                        if (count == 0) {
20688                            pw.println(prefix + "No app verification established.");
20689                            pw.println();
20690                        }
20691                        for (int userId : sUserManager.getUserIds()) {
20692                            pw.println("App linkages for user " + userId + ":");
20693                            pw.println();
20694                            count = 0;
20695                            for (PackageSetting ps : allPackageSettings) {
20696                                final long status = ps.getDomainVerificationStatusForUser(userId);
20697                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20698                                        && !DEBUG_DOMAIN_VERIFICATION) {
20699                                    continue;
20700                                }
20701                                pw.println(prefix + "Package: " + ps.name);
20702                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20703                                String statusStr = IntentFilterVerificationInfo.
20704                                        getStatusStringFromValue(status);
20705                                pw.println(prefix + "Status:  " + statusStr);
20706                                pw.println();
20707                                count++;
20708                            }
20709                            if (count == 0) {
20710                                pw.println(prefix + "No configured app linkages.");
20711                                pw.println();
20712                            }
20713                        }
20714                    }
20715                }
20716            }
20717
20718            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20719                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20720                if (packageName == null && permissionNames == null) {
20721                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20722                        if (iperm == 0) {
20723                            if (dumpState.onTitlePrinted())
20724                                pw.println();
20725                            pw.println("AppOp Permissions:");
20726                        }
20727                        pw.print("  AppOp Permission ");
20728                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20729                        pw.println(":");
20730                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20731                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20732                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20733                        }
20734                    }
20735                }
20736            }
20737
20738            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20739                boolean printedSomething = false;
20740                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20741                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20742                        continue;
20743                    }
20744                    if (!printedSomething) {
20745                        if (dumpState.onTitlePrinted())
20746                            pw.println();
20747                        pw.println("Registered ContentProviders:");
20748                        printedSomething = true;
20749                    }
20750                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20751                    pw.print("    "); pw.println(p.toString());
20752                }
20753                printedSomething = false;
20754                for (Map.Entry<String, PackageParser.Provider> entry :
20755                        mProvidersByAuthority.entrySet()) {
20756                    PackageParser.Provider p = entry.getValue();
20757                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20758                        continue;
20759                    }
20760                    if (!printedSomething) {
20761                        if (dumpState.onTitlePrinted())
20762                            pw.println();
20763                        pw.println("ContentProvider Authorities:");
20764                        printedSomething = true;
20765                    }
20766                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20767                    pw.print("    "); pw.println(p.toString());
20768                    if (p.info != null && p.info.applicationInfo != null) {
20769                        final String appInfo = p.info.applicationInfo.toString();
20770                        pw.print("      applicationInfo="); pw.println(appInfo);
20771                    }
20772                }
20773            }
20774
20775            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20776                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20777            }
20778
20779            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20780                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20781            }
20782
20783            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20784                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20785            }
20786
20787            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20788                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20789            }
20790
20791            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20792                // XXX should handle packageName != null by dumping only install data that
20793                // the given package is involved with.
20794                if (dumpState.onTitlePrinted()) pw.println();
20795                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20796            }
20797
20798            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20799                // XXX should handle packageName != null by dumping only install data that
20800                // the given package is involved with.
20801                if (dumpState.onTitlePrinted()) pw.println();
20802
20803                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20804                ipw.println();
20805                ipw.println("Frozen packages:");
20806                ipw.increaseIndent();
20807                if (mFrozenPackages.size() == 0) {
20808                    ipw.println("(none)");
20809                } else {
20810                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20811                        ipw.println(mFrozenPackages.valueAt(i));
20812                    }
20813                }
20814                ipw.decreaseIndent();
20815            }
20816
20817            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20818                if (dumpState.onTitlePrinted()) pw.println();
20819                dumpDexoptStateLPr(pw, packageName);
20820            }
20821
20822            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20823                if (dumpState.onTitlePrinted()) pw.println();
20824                dumpCompilerStatsLPr(pw, packageName);
20825            }
20826
20827            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
20828                if (dumpState.onTitlePrinted()) pw.println();
20829                dumpEnabledOverlaysLPr(pw);
20830            }
20831
20832            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20833                if (dumpState.onTitlePrinted()) pw.println();
20834                mSettings.dumpReadMessagesLPr(pw, dumpState);
20835
20836                pw.println();
20837                pw.println("Package warning messages:");
20838                BufferedReader in = null;
20839                String line = null;
20840                try {
20841                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20842                    while ((line = in.readLine()) != null) {
20843                        if (line.contains("ignored: updated version")) continue;
20844                        pw.println(line);
20845                    }
20846                } catch (IOException ignored) {
20847                } finally {
20848                    IoUtils.closeQuietly(in);
20849                }
20850            }
20851
20852            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20853                BufferedReader in = null;
20854                String line = null;
20855                try {
20856                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20857                    while ((line = in.readLine()) != null) {
20858                        if (line.contains("ignored: updated version")) continue;
20859                        pw.print("msg,");
20860                        pw.println(line);
20861                    }
20862                } catch (IOException ignored) {
20863                } finally {
20864                    IoUtils.closeQuietly(in);
20865                }
20866            }
20867        }
20868    }
20869
20870    private void dumpProto(FileDescriptor fd) {
20871        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20872
20873        synchronized (mPackages) {
20874            final long requiredVerifierPackageToken =
20875                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20876            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20877            proto.write(
20878                    PackageServiceDumpProto.PackageShortProto.UID,
20879                    getPackageUid(
20880                            mRequiredVerifierPackage,
20881                            MATCH_DEBUG_TRIAGED_MISSING,
20882                            UserHandle.USER_SYSTEM));
20883            proto.end(requiredVerifierPackageToken);
20884
20885            if (mIntentFilterVerifierComponent != null) {
20886                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20887                final long verifierPackageToken =
20888                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20889                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20890                proto.write(
20891                        PackageServiceDumpProto.PackageShortProto.UID,
20892                        getPackageUid(
20893                                verifierPackageName,
20894                                MATCH_DEBUG_TRIAGED_MISSING,
20895                                UserHandle.USER_SYSTEM));
20896                proto.end(verifierPackageToken);
20897            }
20898
20899            dumpSharedLibrariesProto(proto);
20900            dumpFeaturesProto(proto);
20901            mSettings.dumpPackagesProto(proto);
20902            mSettings.dumpSharedUsersProto(proto);
20903            dumpMessagesProto(proto);
20904        }
20905        proto.flush();
20906    }
20907
20908    private void dumpMessagesProto(ProtoOutputStream proto) {
20909        BufferedReader in = null;
20910        String line = null;
20911        try {
20912            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20913            while ((line = in.readLine()) != null) {
20914                if (line.contains("ignored: updated version")) continue;
20915                proto.write(PackageServiceDumpProto.MESSAGES, line);
20916            }
20917        } catch (IOException ignored) {
20918        } finally {
20919            IoUtils.closeQuietly(in);
20920        }
20921    }
20922
20923    private void dumpFeaturesProto(ProtoOutputStream proto) {
20924        synchronized (mAvailableFeatures) {
20925            final int count = mAvailableFeatures.size();
20926            for (int i = 0; i < count; i++) {
20927                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
20928                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
20929                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
20930                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
20931                proto.end(featureToken);
20932            }
20933        }
20934    }
20935
20936    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
20937        final int count = mSharedLibraries.size();
20938        for (int i = 0; i < count; i++) {
20939            final String libName = mSharedLibraries.keyAt(i);
20940            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20941            if (versionedLib == null) {
20942                continue;
20943            }
20944            final int versionCount = versionedLib.size();
20945            for (int j = 0; j < versionCount; j++) {
20946                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
20947                final long sharedLibraryToken =
20948                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
20949                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
20950                final boolean isJar = (libEntry.path != null);
20951                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
20952                if (isJar) {
20953                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
20954                } else {
20955                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
20956                }
20957                proto.end(sharedLibraryToken);
20958            }
20959        }
20960    }
20961
20962    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20963        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20964        ipw.println();
20965        ipw.println("Dexopt state:");
20966        ipw.increaseIndent();
20967        Collection<PackageParser.Package> packages = null;
20968        if (packageName != null) {
20969            PackageParser.Package targetPackage = mPackages.get(packageName);
20970            if (targetPackage != null) {
20971                packages = Collections.singletonList(targetPackage);
20972            } else {
20973                ipw.println("Unable to find package: " + packageName);
20974                return;
20975            }
20976        } else {
20977            packages = mPackages.values();
20978        }
20979
20980        for (PackageParser.Package pkg : packages) {
20981            ipw.println("[" + pkg.packageName + "]");
20982            ipw.increaseIndent();
20983            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20984            ipw.decreaseIndent();
20985        }
20986    }
20987
20988    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20989        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20990        ipw.println();
20991        ipw.println("Compiler stats:");
20992        ipw.increaseIndent();
20993        Collection<PackageParser.Package> packages = null;
20994        if (packageName != null) {
20995            PackageParser.Package targetPackage = mPackages.get(packageName);
20996            if (targetPackage != null) {
20997                packages = Collections.singletonList(targetPackage);
20998            } else {
20999                ipw.println("Unable to find package: " + packageName);
21000                return;
21001            }
21002        } else {
21003            packages = mPackages.values();
21004        }
21005
21006        for (PackageParser.Package pkg : packages) {
21007            ipw.println("[" + pkg.packageName + "]");
21008            ipw.increaseIndent();
21009
21010            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21011            if (stats == null) {
21012                ipw.println("(No recorded stats)");
21013            } else {
21014                stats.dump(ipw);
21015            }
21016            ipw.decreaseIndent();
21017        }
21018    }
21019
21020    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
21021        pw.println("Enabled overlay paths:");
21022        final int N = mEnabledOverlayPaths.size();
21023        for (int i = 0; i < N; i++) {
21024            final int userId = mEnabledOverlayPaths.keyAt(i);
21025            pw.println(String.format("    User %d:", userId));
21026            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
21027                mEnabledOverlayPaths.valueAt(i);
21028            final int M = userSpecificOverlays.size();
21029            for (int j = 0; j < M; j++) {
21030                final String targetPackageName = userSpecificOverlays.keyAt(j);
21031                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
21032                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
21033            }
21034        }
21035    }
21036
21037    private String dumpDomainString(String packageName) {
21038        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21039                .getList();
21040        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21041
21042        ArraySet<String> result = new ArraySet<>();
21043        if (iviList.size() > 0) {
21044            for (IntentFilterVerificationInfo ivi : iviList) {
21045                for (String host : ivi.getDomains()) {
21046                    result.add(host);
21047                }
21048            }
21049        }
21050        if (filters != null && filters.size() > 0) {
21051            for (IntentFilter filter : filters) {
21052                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21053                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21054                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21055                    result.addAll(filter.getHostsList());
21056                }
21057            }
21058        }
21059
21060        StringBuilder sb = new StringBuilder(result.size() * 16);
21061        for (String domain : result) {
21062            if (sb.length() > 0) sb.append(" ");
21063            sb.append(domain);
21064        }
21065        return sb.toString();
21066    }
21067
21068    // ------- apps on sdcard specific code -------
21069    static final boolean DEBUG_SD_INSTALL = false;
21070
21071    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21072
21073    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21074
21075    private boolean mMediaMounted = false;
21076
21077    static String getEncryptKey() {
21078        try {
21079            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21080                    SD_ENCRYPTION_KEYSTORE_NAME);
21081            if (sdEncKey == null) {
21082                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21083                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21084                if (sdEncKey == null) {
21085                    Slog.e(TAG, "Failed to create encryption keys");
21086                    return null;
21087                }
21088            }
21089            return sdEncKey;
21090        } catch (NoSuchAlgorithmException nsae) {
21091            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21092            return null;
21093        } catch (IOException ioe) {
21094            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21095            return null;
21096        }
21097    }
21098
21099    /*
21100     * Update media status on PackageManager.
21101     */
21102    @Override
21103    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21104        int callingUid = Binder.getCallingUid();
21105        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21106            throw new SecurityException("Media status can only be updated by the system");
21107        }
21108        // reader; this apparently protects mMediaMounted, but should probably
21109        // be a different lock in that case.
21110        synchronized (mPackages) {
21111            Log.i(TAG, "Updating external media status from "
21112                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21113                    + (mediaStatus ? "mounted" : "unmounted"));
21114            if (DEBUG_SD_INSTALL)
21115                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21116                        + ", mMediaMounted=" + mMediaMounted);
21117            if (mediaStatus == mMediaMounted) {
21118                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21119                        : 0, -1);
21120                mHandler.sendMessage(msg);
21121                return;
21122            }
21123            mMediaMounted = mediaStatus;
21124        }
21125        // Queue up an async operation since the package installation may take a
21126        // little while.
21127        mHandler.post(new Runnable() {
21128            public void run() {
21129                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21130            }
21131        });
21132    }
21133
21134    /**
21135     * Called by StorageManagerService when the initial ASECs to scan are available.
21136     * Should block until all the ASEC containers are finished being scanned.
21137     */
21138    public void scanAvailableAsecs() {
21139        updateExternalMediaStatusInner(true, false, false);
21140    }
21141
21142    /*
21143     * Collect information of applications on external media, map them against
21144     * existing containers and update information based on current mount status.
21145     * Please note that we always have to report status if reportStatus has been
21146     * set to true especially when unloading packages.
21147     */
21148    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21149            boolean externalStorage) {
21150        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21151        int[] uidArr = EmptyArray.INT;
21152
21153        final String[] list = PackageHelper.getSecureContainerList();
21154        if (ArrayUtils.isEmpty(list)) {
21155            Log.i(TAG, "No secure containers found");
21156        } else {
21157            // Process list of secure containers and categorize them
21158            // as active or stale based on their package internal state.
21159
21160            // reader
21161            synchronized (mPackages) {
21162                for (String cid : list) {
21163                    // Leave stages untouched for now; installer service owns them
21164                    if (PackageInstallerService.isStageName(cid)) continue;
21165
21166                    if (DEBUG_SD_INSTALL)
21167                        Log.i(TAG, "Processing container " + cid);
21168                    String pkgName = getAsecPackageName(cid);
21169                    if (pkgName == null) {
21170                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21171                        continue;
21172                    }
21173                    if (DEBUG_SD_INSTALL)
21174                        Log.i(TAG, "Looking for pkg : " + pkgName);
21175
21176                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21177                    if (ps == null) {
21178                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21179                        continue;
21180                    }
21181
21182                    /*
21183                     * Skip packages that are not external if we're unmounting
21184                     * external storage.
21185                     */
21186                    if (externalStorage && !isMounted && !isExternal(ps)) {
21187                        continue;
21188                    }
21189
21190                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21191                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21192                    // The package status is changed only if the code path
21193                    // matches between settings and the container id.
21194                    if (ps.codePathString != null
21195                            && ps.codePathString.startsWith(args.getCodePath())) {
21196                        if (DEBUG_SD_INSTALL) {
21197                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21198                                    + " at code path: " + ps.codePathString);
21199                        }
21200
21201                        // We do have a valid package installed on sdcard
21202                        processCids.put(args, ps.codePathString);
21203                        final int uid = ps.appId;
21204                        if (uid != -1) {
21205                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21206                        }
21207                    } else {
21208                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21209                                + ps.codePathString);
21210                    }
21211                }
21212            }
21213
21214            Arrays.sort(uidArr);
21215        }
21216
21217        // Process packages with valid entries.
21218        if (isMounted) {
21219            if (DEBUG_SD_INSTALL)
21220                Log.i(TAG, "Loading packages");
21221            loadMediaPackages(processCids, uidArr, externalStorage);
21222            startCleaningPackages();
21223            mInstallerService.onSecureContainersAvailable();
21224        } else {
21225            if (DEBUG_SD_INSTALL)
21226                Log.i(TAG, "Unloading packages");
21227            unloadMediaPackages(processCids, uidArr, reportStatus);
21228        }
21229    }
21230
21231    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21232            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21233        final int size = infos.size();
21234        final String[] packageNames = new String[size];
21235        final int[] packageUids = new int[size];
21236        for (int i = 0; i < size; i++) {
21237            final ApplicationInfo info = infos.get(i);
21238            packageNames[i] = info.packageName;
21239            packageUids[i] = info.uid;
21240        }
21241        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21242                finishedReceiver);
21243    }
21244
21245    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21246            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21247        sendResourcesChangedBroadcast(mediaStatus, replacing,
21248                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21249    }
21250
21251    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21252            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21253        int size = pkgList.length;
21254        if (size > 0) {
21255            // Send broadcasts here
21256            Bundle extras = new Bundle();
21257            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21258            if (uidArr != null) {
21259                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21260            }
21261            if (replacing) {
21262                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21263            }
21264            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21265                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21266            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21267        }
21268    }
21269
21270   /*
21271     * Look at potentially valid container ids from processCids If package
21272     * information doesn't match the one on record or package scanning fails,
21273     * the cid is added to list of removeCids. We currently don't delete stale
21274     * containers.
21275     */
21276    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21277            boolean externalStorage) {
21278        ArrayList<String> pkgList = new ArrayList<String>();
21279        Set<AsecInstallArgs> keys = processCids.keySet();
21280
21281        for (AsecInstallArgs args : keys) {
21282            String codePath = processCids.get(args);
21283            if (DEBUG_SD_INSTALL)
21284                Log.i(TAG, "Loading container : " + args.cid);
21285            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21286            try {
21287                // Make sure there are no container errors first.
21288                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21289                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21290                            + " when installing from sdcard");
21291                    continue;
21292                }
21293                // Check code path here.
21294                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21295                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21296                            + " does not match one in settings " + codePath);
21297                    continue;
21298                }
21299                // Parse package
21300                int parseFlags = mDefParseFlags;
21301                if (args.isExternalAsec()) {
21302                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21303                }
21304                if (args.isFwdLocked()) {
21305                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21306                }
21307
21308                synchronized (mInstallLock) {
21309                    PackageParser.Package pkg = null;
21310                    try {
21311                        // Sadly we don't know the package name yet to freeze it
21312                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21313                                SCAN_IGNORE_FROZEN, 0, null);
21314                    } catch (PackageManagerException e) {
21315                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21316                    }
21317                    // Scan the package
21318                    if (pkg != null) {
21319                        /*
21320                         * TODO why is the lock being held? doPostInstall is
21321                         * called in other places without the lock. This needs
21322                         * to be straightened out.
21323                         */
21324                        // writer
21325                        synchronized (mPackages) {
21326                            retCode = PackageManager.INSTALL_SUCCEEDED;
21327                            pkgList.add(pkg.packageName);
21328                            // Post process args
21329                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21330                                    pkg.applicationInfo.uid);
21331                        }
21332                    } else {
21333                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21334                    }
21335                }
21336
21337            } finally {
21338                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21339                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21340                }
21341            }
21342        }
21343        // writer
21344        synchronized (mPackages) {
21345            // If the platform SDK has changed since the last time we booted,
21346            // we need to re-grant app permission to catch any new ones that
21347            // appear. This is really a hack, and means that apps can in some
21348            // cases get permissions that the user didn't initially explicitly
21349            // allow... it would be nice to have some better way to handle
21350            // this situation.
21351            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21352                    : mSettings.getInternalVersion();
21353            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21354                    : StorageManager.UUID_PRIVATE_INTERNAL;
21355
21356            int updateFlags = UPDATE_PERMISSIONS_ALL;
21357            if (ver.sdkVersion != mSdkVersion) {
21358                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21359                        + mSdkVersion + "; regranting permissions for external");
21360                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21361            }
21362            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21363
21364            // Yay, everything is now upgraded
21365            ver.forceCurrent();
21366
21367            // can downgrade to reader
21368            // Persist settings
21369            mSettings.writeLPr();
21370        }
21371        // Send a broadcast to let everyone know we are done processing
21372        if (pkgList.size() > 0) {
21373            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21374        }
21375    }
21376
21377   /*
21378     * Utility method to unload a list of specified containers
21379     */
21380    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21381        // Just unmount all valid containers.
21382        for (AsecInstallArgs arg : cidArgs) {
21383            synchronized (mInstallLock) {
21384                arg.doPostDeleteLI(false);
21385           }
21386       }
21387   }
21388
21389    /*
21390     * Unload packages mounted on external media. This involves deleting package
21391     * data from internal structures, sending broadcasts about disabled packages,
21392     * gc'ing to free up references, unmounting all secure containers
21393     * corresponding to packages on external media, and posting a
21394     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21395     * that we always have to post this message if status has been requested no
21396     * matter what.
21397     */
21398    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21399            final boolean reportStatus) {
21400        if (DEBUG_SD_INSTALL)
21401            Log.i(TAG, "unloading media packages");
21402        ArrayList<String> pkgList = new ArrayList<String>();
21403        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21404        final Set<AsecInstallArgs> keys = processCids.keySet();
21405        for (AsecInstallArgs args : keys) {
21406            String pkgName = args.getPackageName();
21407            if (DEBUG_SD_INSTALL)
21408                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21409            // Delete package internally
21410            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21411            synchronized (mInstallLock) {
21412                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21413                final boolean res;
21414                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21415                        "unloadMediaPackages")) {
21416                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21417                            null);
21418                }
21419                if (res) {
21420                    pkgList.add(pkgName);
21421                } else {
21422                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21423                    failedList.add(args);
21424                }
21425            }
21426        }
21427
21428        // reader
21429        synchronized (mPackages) {
21430            // We didn't update the settings after removing each package;
21431            // write them now for all packages.
21432            mSettings.writeLPr();
21433        }
21434
21435        // We have to absolutely send UPDATED_MEDIA_STATUS only
21436        // after confirming that all the receivers processed the ordered
21437        // broadcast when packages get disabled, force a gc to clean things up.
21438        // and unload all the containers.
21439        if (pkgList.size() > 0) {
21440            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21441                    new IIntentReceiver.Stub() {
21442                public void performReceive(Intent intent, int resultCode, String data,
21443                        Bundle extras, boolean ordered, boolean sticky,
21444                        int sendingUser) throws RemoteException {
21445                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21446                            reportStatus ? 1 : 0, 1, keys);
21447                    mHandler.sendMessage(msg);
21448                }
21449            });
21450        } else {
21451            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21452                    keys);
21453            mHandler.sendMessage(msg);
21454        }
21455    }
21456
21457    private void loadPrivatePackages(final VolumeInfo vol) {
21458        mHandler.post(new Runnable() {
21459            @Override
21460            public void run() {
21461                loadPrivatePackagesInner(vol);
21462            }
21463        });
21464    }
21465
21466    private void loadPrivatePackagesInner(VolumeInfo vol) {
21467        final String volumeUuid = vol.fsUuid;
21468        if (TextUtils.isEmpty(volumeUuid)) {
21469            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21470            return;
21471        }
21472
21473        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21474        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21475        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21476
21477        final VersionInfo ver;
21478        final List<PackageSetting> packages;
21479        synchronized (mPackages) {
21480            ver = mSettings.findOrCreateVersion(volumeUuid);
21481            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21482        }
21483
21484        for (PackageSetting ps : packages) {
21485            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21486            synchronized (mInstallLock) {
21487                final PackageParser.Package pkg;
21488                try {
21489                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21490                    loaded.add(pkg.applicationInfo);
21491
21492                } catch (PackageManagerException e) {
21493                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21494                }
21495
21496                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21497                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21498                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21499                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21500                }
21501            }
21502        }
21503
21504        // Reconcile app data for all started/unlocked users
21505        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21506        final UserManager um = mContext.getSystemService(UserManager.class);
21507        UserManagerInternal umInternal = getUserManagerInternal();
21508        for (UserInfo user : um.getUsers()) {
21509            final int flags;
21510            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21511                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21512            } else if (umInternal.isUserRunning(user.id)) {
21513                flags = StorageManager.FLAG_STORAGE_DE;
21514            } else {
21515                continue;
21516            }
21517
21518            try {
21519                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21520                synchronized (mInstallLock) {
21521                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21522                }
21523            } catch (IllegalStateException e) {
21524                // Device was probably ejected, and we'll process that event momentarily
21525                Slog.w(TAG, "Failed to prepare storage: " + e);
21526            }
21527        }
21528
21529        synchronized (mPackages) {
21530            int updateFlags = UPDATE_PERMISSIONS_ALL;
21531            if (ver.sdkVersion != mSdkVersion) {
21532                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21533                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21534                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21535            }
21536            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21537
21538            // Yay, everything is now upgraded
21539            ver.forceCurrent();
21540
21541            mSettings.writeLPr();
21542        }
21543
21544        for (PackageFreezer freezer : freezers) {
21545            freezer.close();
21546        }
21547
21548        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21549        sendResourcesChangedBroadcast(true, false, loaded, null);
21550    }
21551
21552    private void unloadPrivatePackages(final VolumeInfo vol) {
21553        mHandler.post(new Runnable() {
21554            @Override
21555            public void run() {
21556                unloadPrivatePackagesInner(vol);
21557            }
21558        });
21559    }
21560
21561    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21562        final String volumeUuid = vol.fsUuid;
21563        if (TextUtils.isEmpty(volumeUuid)) {
21564            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21565            return;
21566        }
21567
21568        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21569        synchronized (mInstallLock) {
21570        synchronized (mPackages) {
21571            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21572            for (PackageSetting ps : packages) {
21573                if (ps.pkg == null) continue;
21574
21575                final ApplicationInfo info = ps.pkg.applicationInfo;
21576                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21577                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21578
21579                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21580                        "unloadPrivatePackagesInner")) {
21581                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21582                            false, null)) {
21583                        unloaded.add(info);
21584                    } else {
21585                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21586                    }
21587                }
21588
21589                // Try very hard to release any references to this package
21590                // so we don't risk the system server being killed due to
21591                // open FDs
21592                AttributeCache.instance().removePackage(ps.name);
21593            }
21594
21595            mSettings.writeLPr();
21596        }
21597        }
21598
21599        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21600        sendResourcesChangedBroadcast(false, false, unloaded, null);
21601
21602        // Try very hard to release any references to this path so we don't risk
21603        // the system server being killed due to open FDs
21604        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21605
21606        for (int i = 0; i < 3; i++) {
21607            System.gc();
21608            System.runFinalization();
21609        }
21610    }
21611
21612    private void assertPackageKnown(String volumeUuid, String packageName)
21613            throws PackageManagerException {
21614        synchronized (mPackages) {
21615            // Normalize package name to handle renamed packages
21616            packageName = normalizePackageNameLPr(packageName);
21617
21618            final PackageSetting ps = mSettings.mPackages.get(packageName);
21619            if (ps == null) {
21620                throw new PackageManagerException("Package " + packageName + " is unknown");
21621            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21622                throw new PackageManagerException(
21623                        "Package " + packageName + " found on unknown volume " + volumeUuid
21624                                + "; expected volume " + ps.volumeUuid);
21625            }
21626        }
21627    }
21628
21629    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21630            throws PackageManagerException {
21631        synchronized (mPackages) {
21632            // Normalize package name to handle renamed packages
21633            packageName = normalizePackageNameLPr(packageName);
21634
21635            final PackageSetting ps = mSettings.mPackages.get(packageName);
21636            if (ps == null) {
21637                throw new PackageManagerException("Package " + packageName + " is unknown");
21638            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21639                throw new PackageManagerException(
21640                        "Package " + packageName + " found on unknown volume " + volumeUuid
21641                                + "; expected volume " + ps.volumeUuid);
21642            } else if (!ps.getInstalled(userId)) {
21643                throw new PackageManagerException(
21644                        "Package " + packageName + " not installed for user " + userId);
21645            }
21646        }
21647    }
21648
21649    private List<String> collectAbsoluteCodePaths() {
21650        synchronized (mPackages) {
21651            List<String> codePaths = new ArrayList<>();
21652            final int packageCount = mSettings.mPackages.size();
21653            for (int i = 0; i < packageCount; i++) {
21654                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21655                codePaths.add(ps.codePath.getAbsolutePath());
21656            }
21657            return codePaths;
21658        }
21659    }
21660
21661    /**
21662     * Examine all apps present on given mounted volume, and destroy apps that
21663     * aren't expected, either due to uninstallation or reinstallation on
21664     * another volume.
21665     */
21666    private void reconcileApps(String volumeUuid) {
21667        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21668        List<File> filesToDelete = null;
21669
21670        final File[] files = FileUtils.listFilesOrEmpty(
21671                Environment.getDataAppDirectory(volumeUuid));
21672        for (File file : files) {
21673            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21674                    && !PackageInstallerService.isStageName(file.getName());
21675            if (!isPackage) {
21676                // Ignore entries which are not packages
21677                continue;
21678            }
21679
21680            String absolutePath = file.getAbsolutePath();
21681
21682            boolean pathValid = false;
21683            final int absoluteCodePathCount = absoluteCodePaths.size();
21684            for (int i = 0; i < absoluteCodePathCount; i++) {
21685                String absoluteCodePath = absoluteCodePaths.get(i);
21686                if (absolutePath.startsWith(absoluteCodePath)) {
21687                    pathValid = true;
21688                    break;
21689                }
21690            }
21691
21692            if (!pathValid) {
21693                if (filesToDelete == null) {
21694                    filesToDelete = new ArrayList<>();
21695                }
21696                filesToDelete.add(file);
21697            }
21698        }
21699
21700        if (filesToDelete != null) {
21701            final int fileToDeleteCount = filesToDelete.size();
21702            for (int i = 0; i < fileToDeleteCount; i++) {
21703                File fileToDelete = filesToDelete.get(i);
21704                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21705                synchronized (mInstallLock) {
21706                    removeCodePathLI(fileToDelete);
21707                }
21708            }
21709        }
21710    }
21711
21712    /**
21713     * Reconcile all app data for the given user.
21714     * <p>
21715     * Verifies that directories exist and that ownership and labeling is
21716     * correct for all installed apps on all mounted volumes.
21717     */
21718    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21719        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21720        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21721            final String volumeUuid = vol.getFsUuid();
21722            synchronized (mInstallLock) {
21723                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21724            }
21725        }
21726    }
21727
21728    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21729            boolean migrateAppData) {
21730        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21731    }
21732
21733    /**
21734     * Reconcile all app data on given mounted volume.
21735     * <p>
21736     * Destroys app data that isn't expected, either due to uninstallation or
21737     * reinstallation on another volume.
21738     * <p>
21739     * Verifies that directories exist and that ownership and labeling is
21740     * correct for all installed apps.
21741     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21742     */
21743    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21744            boolean migrateAppData, boolean onlyCoreApps) {
21745        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21746                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21747        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21748
21749        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21750        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21751
21752        // First look for stale data that doesn't belong, and check if things
21753        // have changed since we did our last restorecon
21754        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21755            if (StorageManager.isFileEncryptedNativeOrEmulated()
21756                    && !StorageManager.isUserKeyUnlocked(userId)) {
21757                throw new RuntimeException(
21758                        "Yikes, someone asked us to reconcile CE storage while " + userId
21759                                + " was still locked; this would have caused massive data loss!");
21760            }
21761
21762            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21763            for (File file : files) {
21764                final String packageName = file.getName();
21765                try {
21766                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21767                } catch (PackageManagerException e) {
21768                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21769                    try {
21770                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21771                                StorageManager.FLAG_STORAGE_CE, 0);
21772                    } catch (InstallerException e2) {
21773                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21774                    }
21775                }
21776            }
21777        }
21778        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21779            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21780            for (File file : files) {
21781                final String packageName = file.getName();
21782                try {
21783                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21784                } catch (PackageManagerException e) {
21785                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21786                    try {
21787                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21788                                StorageManager.FLAG_STORAGE_DE, 0);
21789                    } catch (InstallerException e2) {
21790                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21791                    }
21792                }
21793            }
21794        }
21795
21796        // Ensure that data directories are ready to roll for all packages
21797        // installed for this volume and user
21798        final List<PackageSetting> packages;
21799        synchronized (mPackages) {
21800            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21801        }
21802        int preparedCount = 0;
21803        for (PackageSetting ps : packages) {
21804            final String packageName = ps.name;
21805            if (ps.pkg == null) {
21806                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21807                // TODO: might be due to legacy ASEC apps; we should circle back
21808                // and reconcile again once they're scanned
21809                continue;
21810            }
21811            // Skip non-core apps if requested
21812            if (onlyCoreApps && !ps.pkg.coreApp) {
21813                result.add(packageName);
21814                continue;
21815            }
21816
21817            if (ps.getInstalled(userId)) {
21818                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21819                preparedCount++;
21820            }
21821        }
21822
21823        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21824        return result;
21825    }
21826
21827    /**
21828     * Prepare app data for the given app just after it was installed or
21829     * upgraded. This method carefully only touches users that it's installed
21830     * for, and it forces a restorecon to handle any seinfo changes.
21831     * <p>
21832     * Verifies that directories exist and that ownership and labeling is
21833     * correct for all installed apps. If there is an ownership mismatch, it
21834     * will try recovering system apps by wiping data; third-party app data is
21835     * left intact.
21836     * <p>
21837     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21838     */
21839    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21840        final PackageSetting ps;
21841        synchronized (mPackages) {
21842            ps = mSettings.mPackages.get(pkg.packageName);
21843            mSettings.writeKernelMappingLPr(ps);
21844        }
21845
21846        final UserManager um = mContext.getSystemService(UserManager.class);
21847        UserManagerInternal umInternal = getUserManagerInternal();
21848        for (UserInfo user : um.getUsers()) {
21849            final int flags;
21850            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21851                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21852            } else if (umInternal.isUserRunning(user.id)) {
21853                flags = StorageManager.FLAG_STORAGE_DE;
21854            } else {
21855                continue;
21856            }
21857
21858            if (ps.getInstalled(user.id)) {
21859                // TODO: when user data is locked, mark that we're still dirty
21860                prepareAppDataLIF(pkg, user.id, flags);
21861            }
21862        }
21863    }
21864
21865    /**
21866     * Prepare app data for the given app.
21867     * <p>
21868     * Verifies that directories exist and that ownership and labeling is
21869     * correct for all installed apps. If there is an ownership mismatch, this
21870     * will try recovering system apps by wiping data; third-party app data is
21871     * left intact.
21872     */
21873    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21874        if (pkg == null) {
21875            Slog.wtf(TAG, "Package was null!", new Throwable());
21876            return;
21877        }
21878        prepareAppDataLeafLIF(pkg, userId, flags);
21879        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21880        for (int i = 0; i < childCount; i++) {
21881            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21882        }
21883    }
21884
21885    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21886            boolean maybeMigrateAppData) {
21887        prepareAppDataLIF(pkg, userId, flags);
21888
21889        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21890            // We may have just shuffled around app data directories, so
21891            // prepare them one more time
21892            prepareAppDataLIF(pkg, userId, flags);
21893        }
21894    }
21895
21896    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21897        if (DEBUG_APP_DATA) {
21898            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21899                    + Integer.toHexString(flags));
21900        }
21901
21902        final String volumeUuid = pkg.volumeUuid;
21903        final String packageName = pkg.packageName;
21904        final ApplicationInfo app = pkg.applicationInfo;
21905        final int appId = UserHandle.getAppId(app.uid);
21906
21907        Preconditions.checkNotNull(app.seInfo);
21908
21909        long ceDataInode = -1;
21910        try {
21911            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21912                    appId, app.seInfo, app.targetSdkVersion);
21913        } catch (InstallerException e) {
21914            if (app.isSystemApp()) {
21915                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21916                        + ", but trying to recover: " + e);
21917                destroyAppDataLeafLIF(pkg, userId, flags);
21918                try {
21919                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21920                            appId, app.seInfo, app.targetSdkVersion);
21921                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21922                } catch (InstallerException e2) {
21923                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21924                }
21925            } else {
21926                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21927            }
21928        }
21929
21930        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21931            // TODO: mark this structure as dirty so we persist it!
21932            synchronized (mPackages) {
21933                final PackageSetting ps = mSettings.mPackages.get(packageName);
21934                if (ps != null) {
21935                    ps.setCeDataInode(ceDataInode, userId);
21936                }
21937            }
21938        }
21939
21940        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21941    }
21942
21943    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21944        if (pkg == null) {
21945            Slog.wtf(TAG, "Package was null!", new Throwable());
21946            return;
21947        }
21948        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21949        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21950        for (int i = 0; i < childCount; i++) {
21951            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21952        }
21953    }
21954
21955    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21956        final String volumeUuid = pkg.volumeUuid;
21957        final String packageName = pkg.packageName;
21958        final ApplicationInfo app = pkg.applicationInfo;
21959
21960        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21961            // Create a native library symlink only if we have native libraries
21962            // and if the native libraries are 32 bit libraries. We do not provide
21963            // this symlink for 64 bit libraries.
21964            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21965                final String nativeLibPath = app.nativeLibraryDir;
21966                try {
21967                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21968                            nativeLibPath, userId);
21969                } catch (InstallerException e) {
21970                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21971                }
21972            }
21973        }
21974    }
21975
21976    /**
21977     * For system apps on non-FBE devices, this method migrates any existing
21978     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21979     * requested by the app.
21980     */
21981    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21982        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21983                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21984            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21985                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21986            try {
21987                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21988                        storageTarget);
21989            } catch (InstallerException e) {
21990                logCriticalInfo(Log.WARN,
21991                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21992            }
21993            return true;
21994        } else {
21995            return false;
21996        }
21997    }
21998
21999    public PackageFreezer freezePackage(String packageName, String killReason) {
22000        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22001    }
22002
22003    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22004        return new PackageFreezer(packageName, userId, killReason);
22005    }
22006
22007    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22008            String killReason) {
22009        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22010    }
22011
22012    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22013            String killReason) {
22014        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22015            return new PackageFreezer();
22016        } else {
22017            return freezePackage(packageName, userId, killReason);
22018        }
22019    }
22020
22021    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22022            String killReason) {
22023        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22024    }
22025
22026    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22027            String killReason) {
22028        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22029            return new PackageFreezer();
22030        } else {
22031            return freezePackage(packageName, userId, killReason);
22032        }
22033    }
22034
22035    /**
22036     * Class that freezes and kills the given package upon creation, and
22037     * unfreezes it upon closing. This is typically used when doing surgery on
22038     * app code/data to prevent the app from running while you're working.
22039     */
22040    private class PackageFreezer implements AutoCloseable {
22041        private final String mPackageName;
22042        private final PackageFreezer[] mChildren;
22043
22044        private final boolean mWeFroze;
22045
22046        private final AtomicBoolean mClosed = new AtomicBoolean();
22047        private final CloseGuard mCloseGuard = CloseGuard.get();
22048
22049        /**
22050         * Create and return a stub freezer that doesn't actually do anything,
22051         * typically used when someone requested
22052         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22053         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22054         */
22055        public PackageFreezer() {
22056            mPackageName = null;
22057            mChildren = null;
22058            mWeFroze = false;
22059            mCloseGuard.open("close");
22060        }
22061
22062        public PackageFreezer(String packageName, int userId, String killReason) {
22063            synchronized (mPackages) {
22064                mPackageName = packageName;
22065                mWeFroze = mFrozenPackages.add(mPackageName);
22066
22067                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22068                if (ps != null) {
22069                    killApplication(ps.name, ps.appId, userId, killReason);
22070                }
22071
22072                final PackageParser.Package p = mPackages.get(packageName);
22073                if (p != null && p.childPackages != null) {
22074                    final int N = p.childPackages.size();
22075                    mChildren = new PackageFreezer[N];
22076                    for (int i = 0; i < N; i++) {
22077                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22078                                userId, killReason);
22079                    }
22080                } else {
22081                    mChildren = null;
22082                }
22083            }
22084            mCloseGuard.open("close");
22085        }
22086
22087        @Override
22088        protected void finalize() throws Throwable {
22089            try {
22090                mCloseGuard.warnIfOpen();
22091                close();
22092            } finally {
22093                super.finalize();
22094            }
22095        }
22096
22097        @Override
22098        public void close() {
22099            mCloseGuard.close();
22100            if (mClosed.compareAndSet(false, true)) {
22101                synchronized (mPackages) {
22102                    if (mWeFroze) {
22103                        mFrozenPackages.remove(mPackageName);
22104                    }
22105
22106                    if (mChildren != null) {
22107                        for (PackageFreezer freezer : mChildren) {
22108                            freezer.close();
22109                        }
22110                    }
22111                }
22112            }
22113        }
22114    }
22115
22116    /**
22117     * Verify that given package is currently frozen.
22118     */
22119    private void checkPackageFrozen(String packageName) {
22120        synchronized (mPackages) {
22121            if (!mFrozenPackages.contains(packageName)) {
22122                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22123            }
22124        }
22125    }
22126
22127    @Override
22128    public int movePackage(final String packageName, final String volumeUuid) {
22129        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22130
22131        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22132        final int moveId = mNextMoveId.getAndIncrement();
22133        mHandler.post(new Runnable() {
22134            @Override
22135            public void run() {
22136                try {
22137                    movePackageInternal(packageName, volumeUuid, moveId, user);
22138                } catch (PackageManagerException e) {
22139                    Slog.w(TAG, "Failed to move " + packageName, e);
22140                    mMoveCallbacks.notifyStatusChanged(moveId,
22141                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22142                }
22143            }
22144        });
22145        return moveId;
22146    }
22147
22148    private void movePackageInternal(final String packageName, final String volumeUuid,
22149            final int moveId, UserHandle user) throws PackageManagerException {
22150        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22151        final PackageManager pm = mContext.getPackageManager();
22152
22153        final boolean currentAsec;
22154        final String currentVolumeUuid;
22155        final File codeFile;
22156        final String installerPackageName;
22157        final String packageAbiOverride;
22158        final int appId;
22159        final String seinfo;
22160        final String label;
22161        final int targetSdkVersion;
22162        final PackageFreezer freezer;
22163        final int[] installedUserIds;
22164
22165        // reader
22166        synchronized (mPackages) {
22167            final PackageParser.Package pkg = mPackages.get(packageName);
22168            final PackageSetting ps = mSettings.mPackages.get(packageName);
22169            if (pkg == null || ps == null) {
22170                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22171            }
22172
22173            if (pkg.applicationInfo.isSystemApp()) {
22174                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22175                        "Cannot move system application");
22176            }
22177
22178            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22179            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22180                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22181            if (isInternalStorage && !allow3rdPartyOnInternal) {
22182                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22183                        "3rd party apps are not allowed on internal storage");
22184            }
22185
22186            if (pkg.applicationInfo.isExternalAsec()) {
22187                currentAsec = true;
22188                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22189            } else if (pkg.applicationInfo.isForwardLocked()) {
22190                currentAsec = true;
22191                currentVolumeUuid = "forward_locked";
22192            } else {
22193                currentAsec = false;
22194                currentVolumeUuid = ps.volumeUuid;
22195
22196                final File probe = new File(pkg.codePath);
22197                final File probeOat = new File(probe, "oat");
22198                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22199                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22200                            "Move only supported for modern cluster style installs");
22201                }
22202            }
22203
22204            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22205                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22206                        "Package already moved to " + volumeUuid);
22207            }
22208            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22209                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22210                        "Device admin cannot be moved");
22211            }
22212
22213            if (mFrozenPackages.contains(packageName)) {
22214                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22215                        "Failed to move already frozen package");
22216            }
22217
22218            codeFile = new File(pkg.codePath);
22219            installerPackageName = ps.installerPackageName;
22220            packageAbiOverride = ps.cpuAbiOverrideString;
22221            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22222            seinfo = pkg.applicationInfo.seInfo;
22223            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22224            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22225            freezer = freezePackage(packageName, "movePackageInternal");
22226            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22227        }
22228
22229        final Bundle extras = new Bundle();
22230        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22231        extras.putString(Intent.EXTRA_TITLE, label);
22232        mMoveCallbacks.notifyCreated(moveId, extras);
22233
22234        int installFlags;
22235        final boolean moveCompleteApp;
22236        final File measurePath;
22237
22238        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22239            installFlags = INSTALL_INTERNAL;
22240            moveCompleteApp = !currentAsec;
22241            measurePath = Environment.getDataAppDirectory(volumeUuid);
22242        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22243            installFlags = INSTALL_EXTERNAL;
22244            moveCompleteApp = false;
22245            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22246        } else {
22247            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22248            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22249                    || !volume.isMountedWritable()) {
22250                freezer.close();
22251                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22252                        "Move location not mounted private volume");
22253            }
22254
22255            Preconditions.checkState(!currentAsec);
22256
22257            installFlags = INSTALL_INTERNAL;
22258            moveCompleteApp = true;
22259            measurePath = Environment.getDataAppDirectory(volumeUuid);
22260        }
22261
22262        final PackageStats stats = new PackageStats(null, -1);
22263        synchronized (mInstaller) {
22264            for (int userId : installedUserIds) {
22265                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22266                    freezer.close();
22267                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22268                            "Failed to measure package size");
22269                }
22270            }
22271        }
22272
22273        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22274                + stats.dataSize);
22275
22276        final long startFreeBytes = measurePath.getFreeSpace();
22277        final long sizeBytes;
22278        if (moveCompleteApp) {
22279            sizeBytes = stats.codeSize + stats.dataSize;
22280        } else {
22281            sizeBytes = stats.codeSize;
22282        }
22283
22284        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22285            freezer.close();
22286            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22287                    "Not enough free space to move");
22288        }
22289
22290        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22291
22292        final CountDownLatch installedLatch = new CountDownLatch(1);
22293        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22294            @Override
22295            public void onUserActionRequired(Intent intent) throws RemoteException {
22296                throw new IllegalStateException();
22297            }
22298
22299            @Override
22300            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22301                    Bundle extras) throws RemoteException {
22302                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22303                        + PackageManager.installStatusToString(returnCode, msg));
22304
22305                installedLatch.countDown();
22306                freezer.close();
22307
22308                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22309                switch (status) {
22310                    case PackageInstaller.STATUS_SUCCESS:
22311                        mMoveCallbacks.notifyStatusChanged(moveId,
22312                                PackageManager.MOVE_SUCCEEDED);
22313                        break;
22314                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22315                        mMoveCallbacks.notifyStatusChanged(moveId,
22316                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22317                        break;
22318                    default:
22319                        mMoveCallbacks.notifyStatusChanged(moveId,
22320                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22321                        break;
22322                }
22323            }
22324        };
22325
22326        final MoveInfo move;
22327        if (moveCompleteApp) {
22328            // Kick off a thread to report progress estimates
22329            new Thread() {
22330                @Override
22331                public void run() {
22332                    while (true) {
22333                        try {
22334                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22335                                break;
22336                            }
22337                        } catch (InterruptedException ignored) {
22338                        }
22339
22340                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22341                        final int progress = 10 + (int) MathUtils.constrain(
22342                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22343                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22344                    }
22345                }
22346            }.start();
22347
22348            final String dataAppName = codeFile.getName();
22349            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22350                    dataAppName, appId, seinfo, targetSdkVersion);
22351        } else {
22352            move = null;
22353        }
22354
22355        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22356
22357        final Message msg = mHandler.obtainMessage(INIT_COPY);
22358        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22359        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22360                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22361                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22362                PackageManager.INSTALL_REASON_UNKNOWN);
22363        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22364        msg.obj = params;
22365
22366        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22367                System.identityHashCode(msg.obj));
22368        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22369                System.identityHashCode(msg.obj));
22370
22371        mHandler.sendMessage(msg);
22372    }
22373
22374    @Override
22375    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22376        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22377
22378        final int realMoveId = mNextMoveId.getAndIncrement();
22379        final Bundle extras = new Bundle();
22380        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22381        mMoveCallbacks.notifyCreated(realMoveId, extras);
22382
22383        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22384            @Override
22385            public void onCreated(int moveId, Bundle extras) {
22386                // Ignored
22387            }
22388
22389            @Override
22390            public void onStatusChanged(int moveId, int status, long estMillis) {
22391                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22392            }
22393        };
22394
22395        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22396        storage.setPrimaryStorageUuid(volumeUuid, callback);
22397        return realMoveId;
22398    }
22399
22400    @Override
22401    public int getMoveStatus(int moveId) {
22402        mContext.enforceCallingOrSelfPermission(
22403                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22404        return mMoveCallbacks.mLastStatus.get(moveId);
22405    }
22406
22407    @Override
22408    public void registerMoveCallback(IPackageMoveObserver callback) {
22409        mContext.enforceCallingOrSelfPermission(
22410                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22411        mMoveCallbacks.register(callback);
22412    }
22413
22414    @Override
22415    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22416        mContext.enforceCallingOrSelfPermission(
22417                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22418        mMoveCallbacks.unregister(callback);
22419    }
22420
22421    @Override
22422    public boolean setInstallLocation(int loc) {
22423        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22424                null);
22425        if (getInstallLocation() == loc) {
22426            return true;
22427        }
22428        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22429                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22430            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22431                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22432            return true;
22433        }
22434        return false;
22435   }
22436
22437    @Override
22438    public int getInstallLocation() {
22439        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22440                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22441                PackageHelper.APP_INSTALL_AUTO);
22442    }
22443
22444    /** Called by UserManagerService */
22445    void cleanUpUser(UserManagerService userManager, int userHandle) {
22446        synchronized (mPackages) {
22447            mDirtyUsers.remove(userHandle);
22448            mUserNeedsBadging.delete(userHandle);
22449            mSettings.removeUserLPw(userHandle);
22450            mPendingBroadcasts.remove(userHandle);
22451            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22452            removeUnusedPackagesLPw(userManager, userHandle);
22453        }
22454    }
22455
22456    /**
22457     * We're removing userHandle and would like to remove any downloaded packages
22458     * that are no longer in use by any other user.
22459     * @param userHandle the user being removed
22460     */
22461    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22462        final boolean DEBUG_CLEAN_APKS = false;
22463        int [] users = userManager.getUserIds();
22464        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22465        while (psit.hasNext()) {
22466            PackageSetting ps = psit.next();
22467            if (ps.pkg == null) {
22468                continue;
22469            }
22470            final String packageName = ps.pkg.packageName;
22471            // Skip over if system app
22472            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22473                continue;
22474            }
22475            if (DEBUG_CLEAN_APKS) {
22476                Slog.i(TAG, "Checking package " + packageName);
22477            }
22478            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22479            if (keep) {
22480                if (DEBUG_CLEAN_APKS) {
22481                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22482                }
22483            } else {
22484                for (int i = 0; i < users.length; i++) {
22485                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22486                        keep = true;
22487                        if (DEBUG_CLEAN_APKS) {
22488                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22489                                    + users[i]);
22490                        }
22491                        break;
22492                    }
22493                }
22494            }
22495            if (!keep) {
22496                if (DEBUG_CLEAN_APKS) {
22497                    Slog.i(TAG, "  Removing package " + packageName);
22498                }
22499                mHandler.post(new Runnable() {
22500                    public void run() {
22501                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22502                                userHandle, 0);
22503                    } //end run
22504                });
22505            }
22506        }
22507    }
22508
22509    /** Called by UserManagerService */
22510    void createNewUser(int userId, String[] disallowedPackages) {
22511        synchronized (mInstallLock) {
22512            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22513        }
22514        synchronized (mPackages) {
22515            scheduleWritePackageRestrictionsLocked(userId);
22516            scheduleWritePackageListLocked(userId);
22517            applyFactoryDefaultBrowserLPw(userId);
22518            primeDomainVerificationsLPw(userId);
22519        }
22520    }
22521
22522    void onNewUserCreated(final int userId) {
22523        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22524        // If permission review for legacy apps is required, we represent
22525        // dagerous permissions for such apps as always granted runtime
22526        // permissions to keep per user flag state whether review is needed.
22527        // Hence, if a new user is added we have to propagate dangerous
22528        // permission grants for these legacy apps.
22529        if (mPermissionReviewRequired) {
22530            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22531                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22532        }
22533    }
22534
22535    @Override
22536    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22537        mContext.enforceCallingOrSelfPermission(
22538                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22539                "Only package verification agents can read the verifier device identity");
22540
22541        synchronized (mPackages) {
22542            return mSettings.getVerifierDeviceIdentityLPw();
22543        }
22544    }
22545
22546    @Override
22547    public void setPermissionEnforced(String permission, boolean enforced) {
22548        // TODO: Now that we no longer change GID for storage, this should to away.
22549        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22550                "setPermissionEnforced");
22551        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22552            synchronized (mPackages) {
22553                if (mSettings.mReadExternalStorageEnforced == null
22554                        || mSettings.mReadExternalStorageEnforced != enforced) {
22555                    mSettings.mReadExternalStorageEnforced = enforced;
22556                    mSettings.writeLPr();
22557                }
22558            }
22559            // kill any non-foreground processes so we restart them and
22560            // grant/revoke the GID.
22561            final IActivityManager am = ActivityManager.getService();
22562            if (am != null) {
22563                final long token = Binder.clearCallingIdentity();
22564                try {
22565                    am.killProcessesBelowForeground("setPermissionEnforcement");
22566                } catch (RemoteException e) {
22567                } finally {
22568                    Binder.restoreCallingIdentity(token);
22569                }
22570            }
22571        } else {
22572            throw new IllegalArgumentException("No selective enforcement for " + permission);
22573        }
22574    }
22575
22576    @Override
22577    @Deprecated
22578    public boolean isPermissionEnforced(String permission) {
22579        return true;
22580    }
22581
22582    @Override
22583    public boolean isStorageLow() {
22584        final long token = Binder.clearCallingIdentity();
22585        try {
22586            final DeviceStorageMonitorInternal
22587                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22588            if (dsm != null) {
22589                return dsm.isMemoryLow();
22590            } else {
22591                return false;
22592            }
22593        } finally {
22594            Binder.restoreCallingIdentity(token);
22595        }
22596    }
22597
22598    @Override
22599    public IPackageInstaller getPackageInstaller() {
22600        return mInstallerService;
22601    }
22602
22603    private boolean userNeedsBadging(int userId) {
22604        int index = mUserNeedsBadging.indexOfKey(userId);
22605        if (index < 0) {
22606            final UserInfo userInfo;
22607            final long token = Binder.clearCallingIdentity();
22608            try {
22609                userInfo = sUserManager.getUserInfo(userId);
22610            } finally {
22611                Binder.restoreCallingIdentity(token);
22612            }
22613            final boolean b;
22614            if (userInfo != null && userInfo.isManagedProfile()) {
22615                b = true;
22616            } else {
22617                b = false;
22618            }
22619            mUserNeedsBadging.put(userId, b);
22620            return b;
22621        }
22622        return mUserNeedsBadging.valueAt(index);
22623    }
22624
22625    @Override
22626    public KeySet getKeySetByAlias(String packageName, String alias) {
22627        if (packageName == null || alias == null) {
22628            return null;
22629        }
22630        synchronized(mPackages) {
22631            final PackageParser.Package pkg = mPackages.get(packageName);
22632            if (pkg == null) {
22633                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22634                throw new IllegalArgumentException("Unknown package: " + packageName);
22635            }
22636            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22637            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22638        }
22639    }
22640
22641    @Override
22642    public KeySet getSigningKeySet(String packageName) {
22643        if (packageName == null) {
22644            return null;
22645        }
22646        synchronized(mPackages) {
22647            final PackageParser.Package pkg = mPackages.get(packageName);
22648            if (pkg == null) {
22649                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22650                throw new IllegalArgumentException("Unknown package: " + packageName);
22651            }
22652            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22653                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22654                throw new SecurityException("May not access signing KeySet of other apps.");
22655            }
22656            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22657            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22658        }
22659    }
22660
22661    @Override
22662    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22663        if (packageName == null || ks == null) {
22664            return false;
22665        }
22666        synchronized(mPackages) {
22667            final PackageParser.Package pkg = mPackages.get(packageName);
22668            if (pkg == null) {
22669                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22670                throw new IllegalArgumentException("Unknown package: " + packageName);
22671            }
22672            IBinder ksh = ks.getToken();
22673            if (ksh instanceof KeySetHandle) {
22674                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22675                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22676            }
22677            return false;
22678        }
22679    }
22680
22681    @Override
22682    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22683        if (packageName == null || ks == null) {
22684            return false;
22685        }
22686        synchronized(mPackages) {
22687            final PackageParser.Package pkg = mPackages.get(packageName);
22688            if (pkg == null) {
22689                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22690                throw new IllegalArgumentException("Unknown package: " + packageName);
22691            }
22692            IBinder ksh = ks.getToken();
22693            if (ksh instanceof KeySetHandle) {
22694                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22695                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22696            }
22697            return false;
22698        }
22699    }
22700
22701    private void deletePackageIfUnusedLPr(final String packageName) {
22702        PackageSetting ps = mSettings.mPackages.get(packageName);
22703        if (ps == null) {
22704            return;
22705        }
22706        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22707            // TODO Implement atomic delete if package is unused
22708            // It is currently possible that the package will be deleted even if it is installed
22709            // after this method returns.
22710            mHandler.post(new Runnable() {
22711                public void run() {
22712                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22713                            0, PackageManager.DELETE_ALL_USERS);
22714                }
22715            });
22716        }
22717    }
22718
22719    /**
22720     * Check and throw if the given before/after packages would be considered a
22721     * downgrade.
22722     */
22723    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22724            throws PackageManagerException {
22725        if (after.versionCode < before.mVersionCode) {
22726            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22727                    "Update version code " + after.versionCode + " is older than current "
22728                    + before.mVersionCode);
22729        } else if (after.versionCode == before.mVersionCode) {
22730            if (after.baseRevisionCode < before.baseRevisionCode) {
22731                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22732                        "Update base revision code " + after.baseRevisionCode
22733                        + " is older than current " + before.baseRevisionCode);
22734            }
22735
22736            if (!ArrayUtils.isEmpty(after.splitNames)) {
22737                for (int i = 0; i < after.splitNames.length; i++) {
22738                    final String splitName = after.splitNames[i];
22739                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22740                    if (j != -1) {
22741                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22742                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22743                                    "Update split " + splitName + " revision code "
22744                                    + after.splitRevisionCodes[i] + " is older than current "
22745                                    + before.splitRevisionCodes[j]);
22746                        }
22747                    }
22748                }
22749            }
22750        }
22751    }
22752
22753    private static class MoveCallbacks extends Handler {
22754        private static final int MSG_CREATED = 1;
22755        private static final int MSG_STATUS_CHANGED = 2;
22756
22757        private final RemoteCallbackList<IPackageMoveObserver>
22758                mCallbacks = new RemoteCallbackList<>();
22759
22760        private final SparseIntArray mLastStatus = new SparseIntArray();
22761
22762        public MoveCallbacks(Looper looper) {
22763            super(looper);
22764        }
22765
22766        public void register(IPackageMoveObserver callback) {
22767            mCallbacks.register(callback);
22768        }
22769
22770        public void unregister(IPackageMoveObserver callback) {
22771            mCallbacks.unregister(callback);
22772        }
22773
22774        @Override
22775        public void handleMessage(Message msg) {
22776            final SomeArgs args = (SomeArgs) msg.obj;
22777            final int n = mCallbacks.beginBroadcast();
22778            for (int i = 0; i < n; i++) {
22779                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22780                try {
22781                    invokeCallback(callback, msg.what, args);
22782                } catch (RemoteException ignored) {
22783                }
22784            }
22785            mCallbacks.finishBroadcast();
22786            args.recycle();
22787        }
22788
22789        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22790                throws RemoteException {
22791            switch (what) {
22792                case MSG_CREATED: {
22793                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22794                    break;
22795                }
22796                case MSG_STATUS_CHANGED: {
22797                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22798                    break;
22799                }
22800            }
22801        }
22802
22803        private void notifyCreated(int moveId, Bundle extras) {
22804            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22805
22806            final SomeArgs args = SomeArgs.obtain();
22807            args.argi1 = moveId;
22808            args.arg2 = extras;
22809            obtainMessage(MSG_CREATED, args).sendToTarget();
22810        }
22811
22812        private void notifyStatusChanged(int moveId, int status) {
22813            notifyStatusChanged(moveId, status, -1);
22814        }
22815
22816        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22817            Slog.v(TAG, "Move " + moveId + " status " + status);
22818
22819            final SomeArgs args = SomeArgs.obtain();
22820            args.argi1 = moveId;
22821            args.argi2 = status;
22822            args.arg3 = estMillis;
22823            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22824
22825            synchronized (mLastStatus) {
22826                mLastStatus.put(moveId, status);
22827            }
22828        }
22829    }
22830
22831    private final static class OnPermissionChangeListeners extends Handler {
22832        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22833
22834        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22835                new RemoteCallbackList<>();
22836
22837        public OnPermissionChangeListeners(Looper looper) {
22838            super(looper);
22839        }
22840
22841        @Override
22842        public void handleMessage(Message msg) {
22843            switch (msg.what) {
22844                case MSG_ON_PERMISSIONS_CHANGED: {
22845                    final int uid = msg.arg1;
22846                    handleOnPermissionsChanged(uid);
22847                } break;
22848            }
22849        }
22850
22851        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22852            mPermissionListeners.register(listener);
22853
22854        }
22855
22856        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22857            mPermissionListeners.unregister(listener);
22858        }
22859
22860        public void onPermissionsChanged(int uid) {
22861            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22862                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22863            }
22864        }
22865
22866        private void handleOnPermissionsChanged(int uid) {
22867            final int count = mPermissionListeners.beginBroadcast();
22868            try {
22869                for (int i = 0; i < count; i++) {
22870                    IOnPermissionsChangeListener callback = mPermissionListeners
22871                            .getBroadcastItem(i);
22872                    try {
22873                        callback.onPermissionsChanged(uid);
22874                    } catch (RemoteException e) {
22875                        Log.e(TAG, "Permission listener is dead", e);
22876                    }
22877                }
22878            } finally {
22879                mPermissionListeners.finishBroadcast();
22880            }
22881        }
22882    }
22883
22884    private class PackageManagerInternalImpl extends PackageManagerInternal {
22885        @Override
22886        public void setLocationPackagesProvider(PackagesProvider provider) {
22887            synchronized (mPackages) {
22888                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22889            }
22890        }
22891
22892        @Override
22893        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22894            synchronized (mPackages) {
22895                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22896            }
22897        }
22898
22899        @Override
22900        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22901            synchronized (mPackages) {
22902                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22903            }
22904        }
22905
22906        @Override
22907        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22908            synchronized (mPackages) {
22909                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22910            }
22911        }
22912
22913        @Override
22914        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22915            synchronized (mPackages) {
22916                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22917            }
22918        }
22919
22920        @Override
22921        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22922            synchronized (mPackages) {
22923                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22924            }
22925        }
22926
22927        @Override
22928        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22929            synchronized (mPackages) {
22930                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22931                        packageName, userId);
22932            }
22933        }
22934
22935        @Override
22936        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22937            synchronized (mPackages) {
22938                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22939                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22940                        packageName, userId);
22941            }
22942        }
22943
22944        @Override
22945        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22946            synchronized (mPackages) {
22947                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22948                        packageName, userId);
22949            }
22950        }
22951
22952        @Override
22953        public void setKeepUninstalledPackages(final List<String> packageList) {
22954            Preconditions.checkNotNull(packageList);
22955            List<String> removedFromList = null;
22956            synchronized (mPackages) {
22957                if (mKeepUninstalledPackages != null) {
22958                    final int packagesCount = mKeepUninstalledPackages.size();
22959                    for (int i = 0; i < packagesCount; i++) {
22960                        String oldPackage = mKeepUninstalledPackages.get(i);
22961                        if (packageList != null && packageList.contains(oldPackage)) {
22962                            continue;
22963                        }
22964                        if (removedFromList == null) {
22965                            removedFromList = new ArrayList<>();
22966                        }
22967                        removedFromList.add(oldPackage);
22968                    }
22969                }
22970                mKeepUninstalledPackages = new ArrayList<>(packageList);
22971                if (removedFromList != null) {
22972                    final int removedCount = removedFromList.size();
22973                    for (int i = 0; i < removedCount; i++) {
22974                        deletePackageIfUnusedLPr(removedFromList.get(i));
22975                    }
22976                }
22977            }
22978        }
22979
22980        @Override
22981        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22982            synchronized (mPackages) {
22983                // If we do not support permission review, done.
22984                if (!mPermissionReviewRequired) {
22985                    return false;
22986                }
22987
22988                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22989                if (packageSetting == null) {
22990                    return false;
22991                }
22992
22993                // Permission review applies only to apps not supporting the new permission model.
22994                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22995                    return false;
22996                }
22997
22998                // Legacy apps have the permission and get user consent on launch.
22999                PermissionsState permissionsState = packageSetting.getPermissionsState();
23000                return permissionsState.isPermissionReviewRequired(userId);
23001            }
23002        }
23003
23004        @Override
23005        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
23006            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
23007        }
23008
23009        @Override
23010        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23011                int userId) {
23012            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23013        }
23014
23015        @Override
23016        public void setDeviceAndProfileOwnerPackages(
23017                int deviceOwnerUserId, String deviceOwnerPackage,
23018                SparseArray<String> profileOwnerPackages) {
23019            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23020                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23021        }
23022
23023        @Override
23024        public boolean isPackageDataProtected(int userId, String packageName) {
23025            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23026        }
23027
23028        @Override
23029        public boolean isPackageEphemeral(int userId, String packageName) {
23030            synchronized (mPackages) {
23031                final PackageSetting ps = mSettings.mPackages.get(packageName);
23032                return ps != null ? ps.getInstantApp(userId) : false;
23033            }
23034        }
23035
23036        @Override
23037        public boolean wasPackageEverLaunched(String packageName, int userId) {
23038            synchronized (mPackages) {
23039                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23040            }
23041        }
23042
23043        @Override
23044        public void grantRuntimePermission(String packageName, String name, int userId,
23045                boolean overridePolicy) {
23046            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23047                    overridePolicy);
23048        }
23049
23050        @Override
23051        public void revokeRuntimePermission(String packageName, String name, int userId,
23052                boolean overridePolicy) {
23053            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23054                    overridePolicy);
23055        }
23056
23057        @Override
23058        public String getNameForUid(int uid) {
23059            return PackageManagerService.this.getNameForUid(uid);
23060        }
23061
23062        @Override
23063        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23064                Intent origIntent, String resolvedType, String callingPackage, int userId) {
23065            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23066                    responseObj, origIntent, resolvedType, callingPackage, userId);
23067        }
23068
23069        @Override
23070        public void grantEphemeralAccess(int userId, Intent intent,
23071                int targetAppId, int ephemeralAppId) {
23072            synchronized (mPackages) {
23073                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23074                        targetAppId, ephemeralAppId);
23075            }
23076        }
23077
23078        @Override
23079        public void pruneInstantApps() {
23080            synchronized (mPackages) {
23081                mInstantAppRegistry.pruneInstantAppsLPw();
23082            }
23083        }
23084
23085        @Override
23086        public String getSetupWizardPackageName() {
23087            return mSetupWizardPackage;
23088        }
23089
23090        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23091            if (policy != null) {
23092                mExternalSourcesPolicy = policy;
23093            }
23094        }
23095
23096        @Override
23097        public boolean isPackagePersistent(String packageName) {
23098            synchronized (mPackages) {
23099                PackageParser.Package pkg = mPackages.get(packageName);
23100                return pkg != null
23101                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23102                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23103                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23104                        : false;
23105            }
23106        }
23107
23108        @Override
23109        public List<PackageInfo> getOverlayPackages(int userId) {
23110            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23111            synchronized (mPackages) {
23112                for (PackageParser.Package p : mPackages.values()) {
23113                    if (p.mOverlayTarget != null) {
23114                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23115                        if (pkg != null) {
23116                            overlayPackages.add(pkg);
23117                        }
23118                    }
23119                }
23120            }
23121            return overlayPackages;
23122        }
23123
23124        @Override
23125        public List<String> getTargetPackageNames(int userId) {
23126            List<String> targetPackages = new ArrayList<>();
23127            synchronized (mPackages) {
23128                for (PackageParser.Package p : mPackages.values()) {
23129                    if (p.mOverlayTarget == null) {
23130                        targetPackages.add(p.packageName);
23131                    }
23132                }
23133            }
23134            return targetPackages;
23135        }
23136
23137        @Override
23138        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23139                @Nullable List<String> overlayPackageNames) {
23140            synchronized (mPackages) {
23141                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23142                    Slog.e(TAG, "failed to find package " + targetPackageName);
23143                    return false;
23144                }
23145
23146                ArrayList<String> paths = null;
23147                if (overlayPackageNames != null) {
23148                    final int N = overlayPackageNames.size();
23149                    paths = new ArrayList<String>(N);
23150                    for (int i = 0; i < N; i++) {
23151                        final String packageName = overlayPackageNames.get(i);
23152                        final PackageParser.Package pkg = mPackages.get(packageName);
23153                        if (pkg == null) {
23154                            Slog.e(TAG, "failed to find package " + packageName);
23155                            return false;
23156                        }
23157                        paths.add(pkg.baseCodePath);
23158                    }
23159                }
23160
23161                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23162                    mEnabledOverlayPaths.get(userId);
23163                if (userSpecificOverlays == null) {
23164                    userSpecificOverlays = new ArrayMap<String, ArrayList<String>>();
23165                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23166                }
23167
23168                if (paths != null && paths.size() > 0) {
23169                    userSpecificOverlays.put(targetPackageName, paths);
23170                } else {
23171                    userSpecificOverlays.remove(targetPackageName);
23172                }
23173                return true;
23174            }
23175        }
23176
23177        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23178                int flags, int userId) {
23179            return resolveIntentInternal(
23180                    intent, resolvedType, flags, userId, true /*includeInstantApp*/);
23181        }
23182    }
23183
23184    @Override
23185    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23186        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23187        synchronized (mPackages) {
23188            final long identity = Binder.clearCallingIdentity();
23189            try {
23190                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23191                        packageNames, userId);
23192            } finally {
23193                Binder.restoreCallingIdentity(identity);
23194            }
23195        }
23196    }
23197
23198    @Override
23199    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23200        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23201        synchronized (mPackages) {
23202            final long identity = Binder.clearCallingIdentity();
23203            try {
23204                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23205                        packageNames, userId);
23206            } finally {
23207                Binder.restoreCallingIdentity(identity);
23208            }
23209        }
23210    }
23211
23212    private static void enforceSystemOrPhoneCaller(String tag) {
23213        int callingUid = Binder.getCallingUid();
23214        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23215            throw new SecurityException(
23216                    "Cannot call " + tag + " from UID " + callingUid);
23217        }
23218    }
23219
23220    boolean isHistoricalPackageUsageAvailable() {
23221        return mPackageUsage.isHistoricalPackageUsageAvailable();
23222    }
23223
23224    /**
23225     * Return a <b>copy</b> of the collection of packages known to the package manager.
23226     * @return A copy of the values of mPackages.
23227     */
23228    Collection<PackageParser.Package> getPackages() {
23229        synchronized (mPackages) {
23230            return new ArrayList<>(mPackages.values());
23231        }
23232    }
23233
23234    /**
23235     * Logs process start information (including base APK hash) to the security log.
23236     * @hide
23237     */
23238    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23239            String apkFile, int pid) {
23240        if (!SecurityLog.isLoggingEnabled()) {
23241            return;
23242        }
23243        Bundle data = new Bundle();
23244        data.putLong("startTimestamp", System.currentTimeMillis());
23245        data.putString("processName", processName);
23246        data.putInt("uid", uid);
23247        data.putString("seinfo", seinfo);
23248        data.putString("apkFile", apkFile);
23249        data.putInt("pid", pid);
23250        Message msg = mProcessLoggingHandler.obtainMessage(
23251                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23252        msg.setData(data);
23253        mProcessLoggingHandler.sendMessage(msg);
23254    }
23255
23256    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23257        return mCompilerStats.getPackageStats(pkgName);
23258    }
23259
23260    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23261        return getOrCreateCompilerPackageStats(pkg.packageName);
23262    }
23263
23264    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23265        return mCompilerStats.getOrCreatePackageStats(pkgName);
23266    }
23267
23268    public void deleteCompilerPackageStats(String pkgName) {
23269        mCompilerStats.deletePackageStats(pkgName);
23270    }
23271
23272    @Override
23273    public int getInstallReason(String packageName, int userId) {
23274        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23275                true /* requireFullPermission */, false /* checkShell */,
23276                "get install reason");
23277        synchronized (mPackages) {
23278            final PackageSetting ps = mSettings.mPackages.get(packageName);
23279            if (ps != null) {
23280                return ps.getInstallReason(userId);
23281            }
23282        }
23283        return PackageManager.INSTALL_REASON_UNKNOWN;
23284    }
23285
23286    @Override
23287    public boolean canRequestPackageInstalls(String packageName, int userId) {
23288        int callingUid = Binder.getCallingUid();
23289        int uid = getPackageUid(packageName, 0, userId);
23290        if (callingUid != uid && callingUid != Process.ROOT_UID
23291                && callingUid != Process.SYSTEM_UID) {
23292            throw new SecurityException(
23293                    "Caller uid " + callingUid + " does not own package " + packageName);
23294        }
23295        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23296        if (info == null) {
23297            return false;
23298        }
23299        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23300            throw new UnsupportedOperationException(
23301                    "Operation only supported on apps targeting Android O or higher");
23302        }
23303        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23304        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23305        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23306            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23307        }
23308        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23309            return false;
23310        }
23311        if (mExternalSourcesPolicy != null) {
23312            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23313            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23314                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23315            }
23316        }
23317        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23318    }
23319}
23320