PackageManagerService.java revision e9c0b24ccedcf486c253a7bc474939ee28af7bae
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.InstructionSets.getAppDexInstructionSets;
94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
96import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
97import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
104
105import android.Manifest;
106import android.annotation.NonNull;
107import android.annotation.Nullable;
108import android.app.ActivityManager;
109import android.app.AppOpsManager;
110import android.app.IActivityManager;
111import android.app.ResourcesManager;
112import android.app.admin.IDevicePolicyManager;
113import android.app.admin.SecurityLog;
114import android.app.backup.IBackupManager;
115import android.content.BroadcastReceiver;
116import android.content.ComponentName;
117import android.content.ContentResolver;
118import android.content.Context;
119import android.content.IIntentReceiver;
120import android.content.Intent;
121import android.content.IntentFilter;
122import android.content.IntentSender;
123import android.content.IntentSender.SendIntentException;
124import android.content.ServiceConnection;
125import android.content.pm.ActivityInfo;
126import android.content.pm.ApplicationInfo;
127import android.content.pm.AppsQueryHelper;
128import android.content.pm.ChangedPackages;
129import android.content.pm.ComponentInfo;
130import android.content.pm.InstantAppRequest;
131import android.content.pm.AuxiliaryResolveInfo;
132import android.content.pm.FallbackCategoryProvider;
133import android.content.pm.FeatureInfo;
134import android.content.pm.IOnPermissionsChangeListener;
135import android.content.pm.IPackageDataObserver;
136import android.content.pm.IPackageDeleteObserver;
137import android.content.pm.IPackageDeleteObserver2;
138import android.content.pm.IPackageInstallObserver2;
139import android.content.pm.IPackageInstaller;
140import android.content.pm.IPackageManager;
141import android.content.pm.IPackageMoveObserver;
142import android.content.pm.IPackageStatsObserver;
143import android.content.pm.InstantAppInfo;
144import android.content.pm.InstantAppResolveInfo;
145import android.content.pm.InstrumentationInfo;
146import android.content.pm.IntentFilterVerificationInfo;
147import android.content.pm.KeySet;
148import android.content.pm.PackageCleanItem;
149import android.content.pm.PackageInfo;
150import android.content.pm.PackageInfoLite;
151import android.content.pm.PackageInstaller;
152import android.content.pm.PackageManager;
153import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
154import android.content.pm.PackageManagerInternal;
155import android.content.pm.PackageParser;
156import android.content.pm.PackageParser.ActivityIntentInfo;
157import android.content.pm.PackageParser.PackageLite;
158import android.content.pm.PackageParser.PackageParserException;
159import android.content.pm.PackageStats;
160import android.content.pm.PackageUserState;
161import android.content.pm.ParceledListSlice;
162import android.content.pm.PermissionGroupInfo;
163import android.content.pm.PermissionInfo;
164import android.content.pm.ProviderInfo;
165import android.content.pm.ResolveInfo;
166import android.content.pm.ServiceInfo;
167import android.content.pm.SharedLibraryInfo;
168import android.content.pm.Signature;
169import android.content.pm.UserInfo;
170import android.content.pm.VerifierDeviceIdentity;
171import android.content.pm.VerifierInfo;
172import android.content.pm.VersionedPackage;
173import android.content.res.Resources;
174import android.database.ContentObserver;
175import android.graphics.Bitmap;
176import android.hardware.display.DisplayManager;
177import android.net.Uri;
178import android.os.Binder;
179import android.os.Build;
180import android.os.Bundle;
181import android.os.Debug;
182import android.os.Environment;
183import android.os.Environment.UserEnvironment;
184import android.os.FileUtils;
185import android.os.Handler;
186import android.os.IBinder;
187import android.os.Looper;
188import android.os.Message;
189import android.os.Parcel;
190import android.os.ParcelFileDescriptor;
191import android.os.PatternMatcher;
192import android.os.Process;
193import android.os.RemoteCallbackList;
194import android.os.RemoteException;
195import android.os.ResultReceiver;
196import android.os.SELinux;
197import android.os.ServiceManager;
198import android.os.ShellCallback;
199import android.os.SystemClock;
200import android.os.SystemProperties;
201import android.os.Trace;
202import android.os.UserHandle;
203import android.os.UserManager;
204import android.os.UserManagerInternal;
205import android.os.storage.IStorageManager;
206import android.os.storage.StorageEventListener;
207import android.os.storage.StorageManager;
208import android.os.storage.StorageManagerInternal;
209import android.os.storage.VolumeInfo;
210import android.os.storage.VolumeRecord;
211import android.provider.Settings.Global;
212import android.provider.Settings.Secure;
213import android.security.KeyStore;
214import android.security.SystemKeyStore;
215import android.service.pm.PackageServiceDumpProto;
216import android.system.ErrnoException;
217import android.system.Os;
218import android.text.TextUtils;
219import android.text.format.DateUtils;
220import android.util.ArrayMap;
221import android.util.ArraySet;
222import android.util.Base64;
223import android.util.BootTimingsTraceLog;
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.DumpUtils;
258import com.android.internal.util.FastPrintWriter;
259import com.android.internal.util.FastXmlSerializer;
260import com.android.internal.util.IndentingPrintWriter;
261import com.android.internal.util.Preconditions;
262import com.android.internal.util.XmlUtils;
263import com.android.server.AttributeCache;
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.LockGuard;
270import com.android.server.ServiceThread;
271import com.android.server.SystemConfig;
272import com.android.server.SystemServerInitThreadPool;
273import com.android.server.Watchdog;
274import com.android.server.net.NetworkPolicyManagerInternal;
275import com.android.server.pm.Installer.InstallerException;
276import com.android.server.pm.PermissionsState.PermissionState;
277import com.android.server.pm.Settings.DatabaseVersion;
278import com.android.server.pm.Settings.VersionInfo;
279import com.android.server.pm.dex.DexManager;
280import com.android.server.storage.DeviceStorageMonitorInternal;
281
282import dalvik.system.CloseGuard;
283import dalvik.system.DexFile;
284import dalvik.system.VMRuntime;
285
286import libcore.io.IoUtils;
287import libcore.util.EmptyArray;
288
289import org.xmlpull.v1.XmlPullParser;
290import org.xmlpull.v1.XmlPullParserException;
291import org.xmlpull.v1.XmlSerializer;
292
293import java.io.BufferedOutputStream;
294import java.io.BufferedReader;
295import java.io.ByteArrayInputStream;
296import java.io.ByteArrayOutputStream;
297import java.io.File;
298import java.io.FileDescriptor;
299import java.io.FileInputStream;
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        implements PackageSender {
369    static final String TAG = "PackageManager";
370    static final boolean DEBUG_SETTINGS = false;
371    static final boolean DEBUG_PREFERRED = false;
372    static final boolean DEBUG_UPGRADE = false;
373    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
374    private static final boolean DEBUG_BACKUP = false;
375    private static final boolean DEBUG_INSTALL = false;
376    private static final boolean DEBUG_REMOVE = false;
377    private static final boolean DEBUG_BROADCASTS = false;
378    private static final boolean DEBUG_SHOW_INFO = false;
379    private static final boolean DEBUG_PACKAGE_INFO = false;
380    private static final boolean DEBUG_INTENT_MATCHING = false;
381    private static final boolean DEBUG_PACKAGE_SCANNING = false;
382    private static final boolean DEBUG_VERIFY = false;
383    private static final boolean DEBUG_FILTERS = false;
384
385    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
386    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
387    // user, but by default initialize to this.
388    public static final boolean DEBUG_DEXOPT = false;
389
390    private static final boolean DEBUG_ABI_SELECTION = false;
391    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
392    private static final boolean DEBUG_TRIAGED_MISSING = false;
393    private static final boolean DEBUG_APP_DATA = false;
394
395    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
396    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
397
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", true);
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    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    /** Permission grant: not grant the permission. */
501    private static final int GRANT_DENIED = 1;
502
503    /** Permission grant: grant the permission as an install permission. */
504    private static final int GRANT_INSTALL = 2;
505
506    /** Permission grant: grant the permission as a runtime one. */
507    private static final int GRANT_RUNTIME = 3;
508
509    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
510    private static final int GRANT_UPGRADE = 4;
511
512    /** Canonical intent used to identify what counts as a "web browser" app */
513    private static final Intent sBrowserIntent;
514    static {
515        sBrowserIntent = new Intent();
516        sBrowserIntent.setAction(Intent.ACTION_VIEW);
517        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
518        sBrowserIntent.setData(Uri.parse("http:"));
519    }
520
521    /**
522     * The set of all protected actions [i.e. those actions for which a high priority
523     * intent filter is disallowed].
524     */
525    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
526    static {
527        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
528        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
529        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
530        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
531    }
532
533    // Compilation reasons.
534    public static final int REASON_FIRST_BOOT = 0;
535    public static final int REASON_BOOT = 1;
536    public static final int REASON_INSTALL = 2;
537    public static final int REASON_BACKGROUND_DEXOPT = 3;
538    public static final int REASON_AB_OTA = 4;
539
540    public static final int REASON_LAST = REASON_AB_OTA;
541
542    /** All dangerous permission names in the same order as the events in MetricsEvent */
543    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
544            Manifest.permission.READ_CALENDAR,
545            Manifest.permission.WRITE_CALENDAR,
546            Manifest.permission.CAMERA,
547            Manifest.permission.READ_CONTACTS,
548            Manifest.permission.WRITE_CONTACTS,
549            Manifest.permission.GET_ACCOUNTS,
550            Manifest.permission.ACCESS_FINE_LOCATION,
551            Manifest.permission.ACCESS_COARSE_LOCATION,
552            Manifest.permission.RECORD_AUDIO,
553            Manifest.permission.READ_PHONE_STATE,
554            Manifest.permission.CALL_PHONE,
555            Manifest.permission.READ_CALL_LOG,
556            Manifest.permission.WRITE_CALL_LOG,
557            Manifest.permission.ADD_VOICEMAIL,
558            Manifest.permission.USE_SIP,
559            Manifest.permission.PROCESS_OUTGOING_CALLS,
560            Manifest.permission.READ_CELL_BROADCASTS,
561            Manifest.permission.BODY_SENSORS,
562            Manifest.permission.SEND_SMS,
563            Manifest.permission.RECEIVE_SMS,
564            Manifest.permission.READ_SMS,
565            Manifest.permission.RECEIVE_WAP_PUSH,
566            Manifest.permission.RECEIVE_MMS,
567            Manifest.permission.READ_EXTERNAL_STORAGE,
568            Manifest.permission.WRITE_EXTERNAL_STORAGE,
569            Manifest.permission.READ_PHONE_NUMBERS,
570            Manifest.permission.ANSWER_PHONE_CALLS);
571
572
573    /**
574     * Version number for the package parser cache. Increment this whenever the format or
575     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
576     */
577    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
578
579    /**
580     * Whether the package parser cache is enabled.
581     */
582    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
583
584    final ServiceThread mHandlerThread;
585
586    final PackageHandler mHandler;
587
588    private final ProcessLoggingHandler mProcessLoggingHandler;
589
590    /**
591     * Messages for {@link #mHandler} that need to wait for system ready before
592     * being dispatched.
593     */
594    private ArrayList<Message> mPostSystemReadyMessages;
595
596    final int mSdkVersion = Build.VERSION.SDK_INT;
597
598    final Context mContext;
599    final boolean mFactoryTest;
600    final boolean mOnlyCore;
601    final DisplayMetrics mMetrics;
602    final int mDefParseFlags;
603    final String[] mSeparateProcesses;
604    final boolean mIsUpgrade;
605    final boolean mIsPreNUpgrade;
606    final boolean mIsPreNMR1Upgrade;
607
608    // Have we told the Activity Manager to whitelist the default container service by uid yet?
609    @GuardedBy("mPackages")
610    boolean mDefaultContainerWhitelisted = false;
611
612    @GuardedBy("mPackages")
613    private boolean mDexOptDialogShown;
614
615    /** The location for ASEC container files on internal storage. */
616    final String mAsecInternalPath;
617
618    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
619    // LOCK HELD.  Can be called with mInstallLock held.
620    @GuardedBy("mInstallLock")
621    final Installer mInstaller;
622
623    /** Directory where installed third-party apps stored */
624    final File mAppInstallDir;
625
626    /**
627     * Directory to which applications installed internally have their
628     * 32 bit native libraries copied.
629     */
630    private File mAppLib32InstallDir;
631
632    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
633    // apps.
634    final File mDrmAppPrivateInstallDir;
635
636    // ----------------------------------------------------------------
637
638    // Lock for state used when installing and doing other long running
639    // operations.  Methods that must be called with this lock held have
640    // the suffix "LI".
641    final Object mInstallLock = new Object();
642
643    // ----------------------------------------------------------------
644
645    // Keys are String (package name), values are Package.  This also serves
646    // as the lock for the global state.  Methods that must be called with
647    // this lock held have the prefix "LP".
648    @GuardedBy("mPackages")
649    final ArrayMap<String, PackageParser.Package> mPackages =
650            new ArrayMap<String, PackageParser.Package>();
651
652    final ArrayMap<String, Set<String>> mKnownCodebase =
653            new ArrayMap<String, Set<String>>();
654
655    // Keys are isolated uids and values are the uid of the application
656    // that created the isolated proccess.
657    @GuardedBy("mPackages")
658    final SparseIntArray mIsolatedOwners = new SparseIntArray();
659
660    // List of APK paths to load for each user and package. This data is never
661    // persisted by the package manager. Instead, the overlay manager will
662    // ensure the data is up-to-date in runtime.
663    @GuardedBy("mPackages")
664    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
665        new SparseArray<ArrayMap<String, ArrayList<String>>>();
666
667    /**
668     * Tracks new system packages [received in an OTA] that we expect to
669     * find updated user-installed versions. Keys are package name, values
670     * are package location.
671     */
672    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
673    /**
674     * Tracks high priority intent filters for protected actions. During boot, certain
675     * filter actions are protected and should never be allowed to have a high priority
676     * intent filter for them. However, there is one, and only one exception -- the
677     * setup wizard. It must be able to define a high priority intent filter for these
678     * actions to ensure there are no escapes from the wizard. We need to delay processing
679     * of these during boot as we need to look at all of the system packages in order
680     * to know which component is the setup wizard.
681     */
682    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
683    /**
684     * Whether or not processing protected filters should be deferred.
685     */
686    private boolean mDeferProtectedFilters = true;
687
688    /**
689     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
690     */
691    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
692    /**
693     * Whether or not system app permissions should be promoted from install to runtime.
694     */
695    boolean mPromoteSystemApps;
696
697    @GuardedBy("mPackages")
698    final Settings mSettings;
699
700    /**
701     * Set of package names that are currently "frozen", which means active
702     * surgery is being done on the code/data for that package. The platform
703     * will refuse to launch frozen packages to avoid race conditions.
704     *
705     * @see PackageFreezer
706     */
707    @GuardedBy("mPackages")
708    final ArraySet<String> mFrozenPackages = new ArraySet<>();
709
710    final ProtectedPackages mProtectedPackages;
711
712    boolean mFirstBoot;
713
714    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
715
716    // System configuration read by SystemConfig.
717    final int[] mGlobalGids;
718    final SparseArray<ArraySet<String>> mSystemPermissions;
719    @GuardedBy("mAvailableFeatures")
720    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
721
722    // If mac_permissions.xml was found for seinfo labeling.
723    boolean mFoundPolicyFile;
724
725    private final InstantAppRegistry mInstantAppRegistry;
726
727    @GuardedBy("mPackages")
728    int mChangedPackagesSequenceNumber;
729    /**
730     * List of changed [installed, removed or updated] packages.
731     * mapping from user id -> sequence number -> package name
732     */
733    @GuardedBy("mPackages")
734    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
735    /**
736     * The sequence number of the last change to a package.
737     * mapping from user id -> package name -> sequence number
738     */
739    @GuardedBy("mPackages")
740    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
741
742    class PackageParserCallback implements PackageParser.Callback {
743        @Override public final boolean hasFeature(String feature) {
744            return PackageManagerService.this.hasSystemFeature(feature, 0);
745        }
746
747        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
748                Collection<PackageParser.Package> allPackages, String targetPackageName) {
749            List<PackageParser.Package> overlayPackages = null;
750            for (PackageParser.Package p : allPackages) {
751                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
752                    if (overlayPackages == null) {
753                        overlayPackages = new ArrayList<PackageParser.Package>();
754                    }
755                    overlayPackages.add(p);
756                }
757            }
758            if (overlayPackages != null) {
759                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
760                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
761                        return p1.mOverlayPriority - p2.mOverlayPriority;
762                    }
763                };
764                Collections.sort(overlayPackages, cmp);
765            }
766            return overlayPackages;
767        }
768
769        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
770                String targetPackageName, String targetPath) {
771            if ("android".equals(targetPackageName)) {
772                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
773                // native AssetManager.
774                return null;
775            }
776            List<PackageParser.Package> overlayPackages =
777                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
778            if (overlayPackages == null || overlayPackages.isEmpty()) {
779                return null;
780            }
781            List<String> overlayPathList = null;
782            for (PackageParser.Package overlayPackage : overlayPackages) {
783                if (targetPath == null) {
784                    if (overlayPathList == null) {
785                        overlayPathList = new ArrayList<String>();
786                    }
787                    overlayPathList.add(overlayPackage.baseCodePath);
788                    continue;
789                }
790
791                try {
792                    // Creates idmaps for system to parse correctly the Android manifest of the
793                    // target package.
794                    //
795                    // OverlayManagerService will update each of them with a correct gid from its
796                    // target package app id.
797                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
798                            UserHandle.getSharedAppGid(
799                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
800                    if (overlayPathList == null) {
801                        overlayPathList = new ArrayList<String>();
802                    }
803                    overlayPathList.add(overlayPackage.baseCodePath);
804                } catch (InstallerException e) {
805                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
806                            overlayPackage.baseCodePath);
807                }
808            }
809            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
810        }
811
812        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
813            synchronized (mPackages) {
814                return getStaticOverlayPathsLocked(
815                        mPackages.values(), targetPackageName, targetPath);
816            }
817        }
818
819        @Override public final String[] getOverlayApks(String targetPackageName) {
820            return getStaticOverlayPaths(targetPackageName, null);
821        }
822
823        @Override public final String[] getOverlayPaths(String targetPackageName,
824                String targetPath) {
825            return getStaticOverlayPaths(targetPackageName, targetPath);
826        }
827    };
828
829    class ParallelPackageParserCallback extends PackageParserCallback {
830        List<PackageParser.Package> mOverlayPackages = null;
831
832        void findStaticOverlayPackages() {
833            synchronized (mPackages) {
834                for (PackageParser.Package p : mPackages.values()) {
835                    if (p.mIsStaticOverlay) {
836                        if (mOverlayPackages == null) {
837                            mOverlayPackages = new ArrayList<PackageParser.Package>();
838                        }
839                        mOverlayPackages.add(p);
840                    }
841                }
842            }
843        }
844
845        @Override
846        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
847            // We can trust mOverlayPackages without holding mPackages because package uninstall
848            // can't happen while running parallel parsing.
849            // Moreover holding mPackages on each parsing thread causes dead-lock.
850            return mOverlayPackages == null ? null :
851                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
852        }
853    }
854
855    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
856    final ParallelPackageParserCallback mParallelPackageParserCallback =
857            new ParallelPackageParserCallback();
858
859    public static final class SharedLibraryEntry {
860        public final String path;
861        public final String apk;
862        public final SharedLibraryInfo info;
863
864        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
865                String declaringPackageName, int declaringPackageVersionCode) {
866            path = _path;
867            apk = _apk;
868            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
869                    declaringPackageName, declaringPackageVersionCode), null);
870        }
871    }
872
873    // Currently known shared libraries.
874    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
875    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
876            new ArrayMap<>();
877
878    // All available activities, for your resolving pleasure.
879    final ActivityIntentResolver mActivities =
880            new ActivityIntentResolver();
881
882    // All available receivers, for your resolving pleasure.
883    final ActivityIntentResolver mReceivers =
884            new ActivityIntentResolver();
885
886    // All available services, for your resolving pleasure.
887    final ServiceIntentResolver mServices = new ServiceIntentResolver();
888
889    // All available providers, for your resolving pleasure.
890    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
891
892    // Mapping from provider base names (first directory in content URI codePath)
893    // to the provider information.
894    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
895            new ArrayMap<String, PackageParser.Provider>();
896
897    // Mapping from instrumentation class names to info about them.
898    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
899            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
900
901    // Mapping from permission names to info about them.
902    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
903            new ArrayMap<String, PackageParser.PermissionGroup>();
904
905    // Packages whose data we have transfered into another package, thus
906    // should no longer exist.
907    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
908
909    // Broadcast actions that are only available to the system.
910    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
911
912    /** List of packages waiting for verification. */
913    final SparseArray<PackageVerificationState> mPendingVerification
914            = new SparseArray<PackageVerificationState>();
915
916    /** Set of packages associated with each app op permission. */
917    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
918
919    final PackageInstallerService mInstallerService;
920
921    private final PackageDexOptimizer mPackageDexOptimizer;
922    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
923    // is used by other apps).
924    private final DexManager mDexManager;
925
926    private AtomicInteger mNextMoveId = new AtomicInteger();
927    private final MoveCallbacks mMoveCallbacks;
928
929    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
930
931    // Cache of users who need badging.
932    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
933
934    /** Token for keys in mPendingVerification. */
935    private int mPendingVerificationToken = 0;
936
937    volatile boolean mSystemReady;
938    volatile boolean mSafeMode;
939    volatile boolean mHasSystemUidErrors;
940    private volatile boolean mEphemeralAppsDisabled;
941
942    ApplicationInfo mAndroidApplication;
943    final ActivityInfo mResolveActivity = new ActivityInfo();
944    final ResolveInfo mResolveInfo = new ResolveInfo();
945    ComponentName mResolveComponentName;
946    PackageParser.Package mPlatformPackage;
947    ComponentName mCustomResolverComponentName;
948
949    boolean mResolverReplaced = false;
950
951    private final @Nullable ComponentName mIntentFilterVerifierComponent;
952    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
953
954    private int mIntentFilterVerificationToken = 0;
955
956    /** The service connection to the ephemeral resolver */
957    final EphemeralResolverConnection mInstantAppResolverConnection;
958    /** Component used to show resolver settings for Instant Apps */
959    final ComponentName mInstantAppResolverSettingsComponent;
960
961    /** Activity used to install instant applications */
962    ActivityInfo mInstantAppInstallerActivity;
963    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
964
965    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
966            = new SparseArray<IntentFilterVerificationState>();
967
968    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
969
970    // List of packages names to keep cached, even if they are uninstalled for all users
971    private List<String> mKeepUninstalledPackages;
972
973    private UserManagerInternal mUserManagerInternal;
974
975    private DeviceIdleController.LocalService mDeviceIdleController;
976
977    private File mCacheDir;
978
979    private ArraySet<String> mPrivappPermissionsViolations;
980
981    private Future<?> mPrepareAppDataFuture;
982
983    private static class IFVerificationParams {
984        PackageParser.Package pkg;
985        boolean replacing;
986        int userId;
987        int verifierUid;
988
989        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
990                int _userId, int _verifierUid) {
991            pkg = _pkg;
992            replacing = _replacing;
993            userId = _userId;
994            replacing = _replacing;
995            verifierUid = _verifierUid;
996        }
997    }
998
999    private interface IntentFilterVerifier<T extends IntentFilter> {
1000        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1001                                               T filter, String packageName);
1002        void startVerifications(int userId);
1003        void receiveVerificationResponse(int verificationId);
1004    }
1005
1006    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1007        private Context mContext;
1008        private ComponentName mIntentFilterVerifierComponent;
1009        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1010
1011        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1012            mContext = context;
1013            mIntentFilterVerifierComponent = verifierComponent;
1014        }
1015
1016        private String getDefaultScheme() {
1017            return IntentFilter.SCHEME_HTTPS;
1018        }
1019
1020        @Override
1021        public void startVerifications(int userId) {
1022            // Launch verifications requests
1023            int count = mCurrentIntentFilterVerifications.size();
1024            for (int n=0; n<count; n++) {
1025                int verificationId = mCurrentIntentFilterVerifications.get(n);
1026                final IntentFilterVerificationState ivs =
1027                        mIntentFilterVerificationStates.get(verificationId);
1028
1029                String packageName = ivs.getPackageName();
1030
1031                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1032                final int filterCount = filters.size();
1033                ArraySet<String> domainsSet = new ArraySet<>();
1034                for (int m=0; m<filterCount; m++) {
1035                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1036                    domainsSet.addAll(filter.getHostsList());
1037                }
1038                synchronized (mPackages) {
1039                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1040                            packageName, domainsSet) != null) {
1041                        scheduleWriteSettingsLocked();
1042                    }
1043                }
1044                sendVerificationRequest(userId, verificationId, ivs);
1045            }
1046            mCurrentIntentFilterVerifications.clear();
1047        }
1048
1049        private void sendVerificationRequest(int userId, int verificationId,
1050                IntentFilterVerificationState ivs) {
1051
1052            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1053            verificationIntent.putExtra(
1054                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1055                    verificationId);
1056            verificationIntent.putExtra(
1057                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1058                    getDefaultScheme());
1059            verificationIntent.putExtra(
1060                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1061                    ivs.getHostsString());
1062            verificationIntent.putExtra(
1063                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1064                    ivs.getPackageName());
1065            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1066            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1067
1068            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1069            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1070                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1071                    userId, false, "intent filter verifier");
1072
1073            UserHandle user = new UserHandle(userId);
1074            mContext.sendBroadcastAsUser(verificationIntent, user);
1075            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1076                    "Sending IntentFilter verification broadcast");
1077        }
1078
1079        public void receiveVerificationResponse(int verificationId) {
1080            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1081
1082            final boolean verified = ivs.isVerified();
1083
1084            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1085            final int count = filters.size();
1086            if (DEBUG_DOMAIN_VERIFICATION) {
1087                Slog.i(TAG, "Received verification response " + verificationId
1088                        + " for " + count + " filters, verified=" + verified);
1089            }
1090            for (int n=0; n<count; n++) {
1091                PackageParser.ActivityIntentInfo filter = filters.get(n);
1092                filter.setVerified(verified);
1093
1094                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1095                        + " verified with result:" + verified + " and hosts:"
1096                        + ivs.getHostsString());
1097            }
1098
1099            mIntentFilterVerificationStates.remove(verificationId);
1100
1101            final String packageName = ivs.getPackageName();
1102            IntentFilterVerificationInfo ivi = null;
1103
1104            synchronized (mPackages) {
1105                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1106            }
1107            if (ivi == null) {
1108                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1109                        + verificationId + " packageName:" + packageName);
1110                return;
1111            }
1112            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1113                    "Updating IntentFilterVerificationInfo for package " + packageName
1114                            +" verificationId:" + verificationId);
1115
1116            synchronized (mPackages) {
1117                if (verified) {
1118                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1119                } else {
1120                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1121                }
1122                scheduleWriteSettingsLocked();
1123
1124                final int userId = ivs.getUserId();
1125                if (userId != UserHandle.USER_ALL) {
1126                    final int userStatus =
1127                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1128
1129                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1130                    boolean needUpdate = false;
1131
1132                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1133                    // already been set by the User thru the Disambiguation dialog
1134                    switch (userStatus) {
1135                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1136                            if (verified) {
1137                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1138                            } else {
1139                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1140                            }
1141                            needUpdate = true;
1142                            break;
1143
1144                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1145                            if (verified) {
1146                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1147                                needUpdate = true;
1148                            }
1149                            break;
1150
1151                        default:
1152                            // Nothing to do
1153                    }
1154
1155                    if (needUpdate) {
1156                        mSettings.updateIntentFilterVerificationStatusLPw(
1157                                packageName, updatedStatus, userId);
1158                        scheduleWritePackageRestrictionsLocked(userId);
1159                    }
1160                }
1161            }
1162        }
1163
1164        @Override
1165        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1166                    ActivityIntentInfo filter, String packageName) {
1167            if (!hasValidDomains(filter)) {
1168                return false;
1169            }
1170            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1171            if (ivs == null) {
1172                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1173                        packageName);
1174            }
1175            if (DEBUG_DOMAIN_VERIFICATION) {
1176                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1177            }
1178            ivs.addFilter(filter);
1179            return true;
1180        }
1181
1182        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1183                int userId, int verificationId, String packageName) {
1184            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1185                    verifierUid, userId, packageName);
1186            ivs.setPendingState();
1187            synchronized (mPackages) {
1188                mIntentFilterVerificationStates.append(verificationId, ivs);
1189                mCurrentIntentFilterVerifications.add(verificationId);
1190            }
1191            return ivs;
1192        }
1193    }
1194
1195    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1196        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1197                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1198                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1199    }
1200
1201    // Set of pending broadcasts for aggregating enable/disable of components.
1202    static class PendingPackageBroadcasts {
1203        // for each user id, a map of <package name -> components within that package>
1204        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1205
1206        public PendingPackageBroadcasts() {
1207            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1208        }
1209
1210        public ArrayList<String> get(int userId, String packageName) {
1211            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1212            return packages.get(packageName);
1213        }
1214
1215        public void put(int userId, String packageName, ArrayList<String> components) {
1216            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1217            packages.put(packageName, components);
1218        }
1219
1220        public void remove(int userId, String packageName) {
1221            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1222            if (packages != null) {
1223                packages.remove(packageName);
1224            }
1225        }
1226
1227        public void remove(int userId) {
1228            mUidMap.remove(userId);
1229        }
1230
1231        public int userIdCount() {
1232            return mUidMap.size();
1233        }
1234
1235        public int userIdAt(int n) {
1236            return mUidMap.keyAt(n);
1237        }
1238
1239        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1240            return mUidMap.get(userId);
1241        }
1242
1243        public int size() {
1244            // total number of pending broadcast entries across all userIds
1245            int num = 0;
1246            for (int i = 0; i< mUidMap.size(); i++) {
1247                num += mUidMap.valueAt(i).size();
1248            }
1249            return num;
1250        }
1251
1252        public void clear() {
1253            mUidMap.clear();
1254        }
1255
1256        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1257            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1258            if (map == null) {
1259                map = new ArrayMap<String, ArrayList<String>>();
1260                mUidMap.put(userId, map);
1261            }
1262            return map;
1263        }
1264    }
1265    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1266
1267    // Service Connection to remote media container service to copy
1268    // package uri's from external media onto secure containers
1269    // or internal storage.
1270    private IMediaContainerService mContainerService = null;
1271
1272    static final int SEND_PENDING_BROADCAST = 1;
1273    static final int MCS_BOUND = 3;
1274    static final int END_COPY = 4;
1275    static final int INIT_COPY = 5;
1276    static final int MCS_UNBIND = 6;
1277    static final int START_CLEANING_PACKAGE = 7;
1278    static final int FIND_INSTALL_LOC = 8;
1279    static final int POST_INSTALL = 9;
1280    static final int MCS_RECONNECT = 10;
1281    static final int MCS_GIVE_UP = 11;
1282    static final int UPDATED_MEDIA_STATUS = 12;
1283    static final int WRITE_SETTINGS = 13;
1284    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1285    static final int PACKAGE_VERIFIED = 15;
1286    static final int CHECK_PENDING_VERIFICATION = 16;
1287    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1288    static final int INTENT_FILTER_VERIFIED = 18;
1289    static final int WRITE_PACKAGE_LIST = 19;
1290    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1291
1292    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1293
1294    // Delay time in millisecs
1295    static final int BROADCAST_DELAY = 10 * 1000;
1296
1297    static UserManagerService sUserManager;
1298
1299    // Stores a list of users whose package restrictions file needs to be updated
1300    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1301
1302    final private DefaultContainerConnection mDefContainerConn =
1303            new DefaultContainerConnection();
1304    class DefaultContainerConnection implements ServiceConnection {
1305        public void onServiceConnected(ComponentName name, IBinder service) {
1306            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1307            final IMediaContainerService imcs = IMediaContainerService.Stub
1308                    .asInterface(Binder.allowBlocking(service));
1309            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1310        }
1311
1312        public void onServiceDisconnected(ComponentName name) {
1313            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1314        }
1315    }
1316
1317    // Recordkeeping of restore-after-install operations that are currently in flight
1318    // between the Package Manager and the Backup Manager
1319    static class PostInstallData {
1320        public InstallArgs args;
1321        public PackageInstalledInfo res;
1322
1323        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1324            args = _a;
1325            res = _r;
1326        }
1327    }
1328
1329    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1330    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1331
1332    // XML tags for backup/restore of various bits of state
1333    private static final String TAG_PREFERRED_BACKUP = "pa";
1334    private static final String TAG_DEFAULT_APPS = "da";
1335    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1336
1337    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1338    private static final String TAG_ALL_GRANTS = "rt-grants";
1339    private static final String TAG_GRANT = "grant";
1340    private static final String ATTR_PACKAGE_NAME = "pkg";
1341
1342    private static final String TAG_PERMISSION = "perm";
1343    private static final String ATTR_PERMISSION_NAME = "name";
1344    private static final String ATTR_IS_GRANTED = "g";
1345    private static final String ATTR_USER_SET = "set";
1346    private static final String ATTR_USER_FIXED = "fixed";
1347    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1348
1349    // System/policy permission grants are not backed up
1350    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1351            FLAG_PERMISSION_POLICY_FIXED
1352            | FLAG_PERMISSION_SYSTEM_FIXED
1353            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1354
1355    // And we back up these user-adjusted states
1356    private static final int USER_RUNTIME_GRANT_MASK =
1357            FLAG_PERMISSION_USER_SET
1358            | FLAG_PERMISSION_USER_FIXED
1359            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1360
1361    final @Nullable String mRequiredVerifierPackage;
1362    final @NonNull String mRequiredInstallerPackage;
1363    final @NonNull String mRequiredUninstallerPackage;
1364    final @Nullable String mSetupWizardPackage;
1365    final @Nullable String mStorageManagerPackage;
1366    final @NonNull String mServicesSystemSharedLibraryPackageName;
1367    final @NonNull String mSharedSystemSharedLibraryPackageName;
1368
1369    final boolean mPermissionReviewRequired;
1370
1371    private final PackageUsage mPackageUsage = new PackageUsage();
1372    private final CompilerStats mCompilerStats = new CompilerStats();
1373
1374    class PackageHandler extends Handler {
1375        private boolean mBound = false;
1376        final ArrayList<HandlerParams> mPendingInstalls =
1377            new ArrayList<HandlerParams>();
1378
1379        private boolean connectToService() {
1380            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1381                    " DefaultContainerService");
1382            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1383            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1384            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1385                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1386                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1387                mBound = true;
1388                return true;
1389            }
1390            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1391            return false;
1392        }
1393
1394        private void disconnectService() {
1395            mContainerService = null;
1396            mBound = false;
1397            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1398            mContext.unbindService(mDefContainerConn);
1399            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1400        }
1401
1402        PackageHandler(Looper looper) {
1403            super(looper);
1404        }
1405
1406        public void handleMessage(Message msg) {
1407            try {
1408                doHandleMessage(msg);
1409            } finally {
1410                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1411            }
1412        }
1413
1414        void doHandleMessage(Message msg) {
1415            switch (msg.what) {
1416                case INIT_COPY: {
1417                    HandlerParams params = (HandlerParams) msg.obj;
1418                    int idx = mPendingInstalls.size();
1419                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1420                    // If a bind was already initiated we dont really
1421                    // need to do anything. The pending install
1422                    // will be processed later on.
1423                    if (!mBound) {
1424                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1425                                System.identityHashCode(mHandler));
1426                        // If this is the only one pending we might
1427                        // have to bind to the service again.
1428                        if (!connectToService()) {
1429                            Slog.e(TAG, "Failed to bind to media container service");
1430                            params.serviceError();
1431                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1432                                    System.identityHashCode(mHandler));
1433                            if (params.traceMethod != null) {
1434                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1435                                        params.traceCookie);
1436                            }
1437                            return;
1438                        } else {
1439                            // Once we bind to the service, the first
1440                            // pending request will be processed.
1441                            mPendingInstalls.add(idx, params);
1442                        }
1443                    } else {
1444                        mPendingInstalls.add(idx, params);
1445                        // Already bound to the service. Just make
1446                        // sure we trigger off processing the first request.
1447                        if (idx == 0) {
1448                            mHandler.sendEmptyMessage(MCS_BOUND);
1449                        }
1450                    }
1451                    break;
1452                }
1453                case MCS_BOUND: {
1454                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1455                    if (msg.obj != null) {
1456                        mContainerService = (IMediaContainerService) msg.obj;
1457                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1458                                System.identityHashCode(mHandler));
1459                    }
1460                    if (mContainerService == null) {
1461                        if (!mBound) {
1462                            // Something seriously wrong since we are not bound and we are not
1463                            // waiting for connection. Bail out.
1464                            Slog.e(TAG, "Cannot bind to media container service");
1465                            for (HandlerParams params : mPendingInstalls) {
1466                                // Indicate service bind error
1467                                params.serviceError();
1468                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1469                                        System.identityHashCode(params));
1470                                if (params.traceMethod != null) {
1471                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1472                                            params.traceMethod, params.traceCookie);
1473                                }
1474                                return;
1475                            }
1476                            mPendingInstalls.clear();
1477                        } else {
1478                            Slog.w(TAG, "Waiting to connect to media container service");
1479                        }
1480                    } else if (mPendingInstalls.size() > 0) {
1481                        HandlerParams params = mPendingInstalls.get(0);
1482                        if (params != null) {
1483                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1484                                    System.identityHashCode(params));
1485                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1486                            if (params.startCopy()) {
1487                                // We are done...  look for more work or to
1488                                // go idle.
1489                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1490                                        "Checking for more work or unbind...");
1491                                // Delete pending install
1492                                if (mPendingInstalls.size() > 0) {
1493                                    mPendingInstalls.remove(0);
1494                                }
1495                                if (mPendingInstalls.size() == 0) {
1496                                    if (mBound) {
1497                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1498                                                "Posting delayed MCS_UNBIND");
1499                                        removeMessages(MCS_UNBIND);
1500                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1501                                        // Unbind after a little delay, to avoid
1502                                        // continual thrashing.
1503                                        sendMessageDelayed(ubmsg, 10000);
1504                                    }
1505                                } else {
1506                                    // There are more pending requests in queue.
1507                                    // Just post MCS_BOUND message to trigger processing
1508                                    // of next pending install.
1509                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1510                                            "Posting MCS_BOUND for next work");
1511                                    mHandler.sendEmptyMessage(MCS_BOUND);
1512                                }
1513                            }
1514                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1515                        }
1516                    } else {
1517                        // Should never happen ideally.
1518                        Slog.w(TAG, "Empty queue");
1519                    }
1520                    break;
1521                }
1522                case MCS_RECONNECT: {
1523                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1524                    if (mPendingInstalls.size() > 0) {
1525                        if (mBound) {
1526                            disconnectService();
1527                        }
1528                        if (!connectToService()) {
1529                            Slog.e(TAG, "Failed to bind to media container service");
1530                            for (HandlerParams params : mPendingInstalls) {
1531                                // Indicate service bind error
1532                                params.serviceError();
1533                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1534                                        System.identityHashCode(params));
1535                            }
1536                            mPendingInstalls.clear();
1537                        }
1538                    }
1539                    break;
1540                }
1541                case MCS_UNBIND: {
1542                    // If there is no actual work left, then time to unbind.
1543                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1544
1545                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1546                        if (mBound) {
1547                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1548
1549                            disconnectService();
1550                        }
1551                    } else if (mPendingInstalls.size() > 0) {
1552                        // There are more pending requests in queue.
1553                        // Just post MCS_BOUND message to trigger processing
1554                        // of next pending install.
1555                        mHandler.sendEmptyMessage(MCS_BOUND);
1556                    }
1557
1558                    break;
1559                }
1560                case MCS_GIVE_UP: {
1561                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1562                    HandlerParams params = mPendingInstalls.remove(0);
1563                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1564                            System.identityHashCode(params));
1565                    break;
1566                }
1567                case SEND_PENDING_BROADCAST: {
1568                    String packages[];
1569                    ArrayList<String> components[];
1570                    int size = 0;
1571                    int uids[];
1572                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1573                    synchronized (mPackages) {
1574                        if (mPendingBroadcasts == null) {
1575                            return;
1576                        }
1577                        size = mPendingBroadcasts.size();
1578                        if (size <= 0) {
1579                            // Nothing to be done. Just return
1580                            return;
1581                        }
1582                        packages = new String[size];
1583                        components = new ArrayList[size];
1584                        uids = new int[size];
1585                        int i = 0;  // filling out the above arrays
1586
1587                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1588                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1589                            Iterator<Map.Entry<String, ArrayList<String>>> it
1590                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1591                                            .entrySet().iterator();
1592                            while (it.hasNext() && i < size) {
1593                                Map.Entry<String, ArrayList<String>> ent = it.next();
1594                                packages[i] = ent.getKey();
1595                                components[i] = ent.getValue();
1596                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1597                                uids[i] = (ps != null)
1598                                        ? UserHandle.getUid(packageUserId, ps.appId)
1599                                        : -1;
1600                                i++;
1601                            }
1602                        }
1603                        size = i;
1604                        mPendingBroadcasts.clear();
1605                    }
1606                    // Send broadcasts
1607                    for (int i = 0; i < size; i++) {
1608                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1609                    }
1610                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1611                    break;
1612                }
1613                case START_CLEANING_PACKAGE: {
1614                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1615                    final String packageName = (String)msg.obj;
1616                    final int userId = msg.arg1;
1617                    final boolean andCode = msg.arg2 != 0;
1618                    synchronized (mPackages) {
1619                        if (userId == UserHandle.USER_ALL) {
1620                            int[] users = sUserManager.getUserIds();
1621                            for (int user : users) {
1622                                mSettings.addPackageToCleanLPw(
1623                                        new PackageCleanItem(user, packageName, andCode));
1624                            }
1625                        } else {
1626                            mSettings.addPackageToCleanLPw(
1627                                    new PackageCleanItem(userId, packageName, andCode));
1628                        }
1629                    }
1630                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1631                    startCleaningPackages();
1632                } break;
1633                case POST_INSTALL: {
1634                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1635
1636                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1637                    final boolean didRestore = (msg.arg2 != 0);
1638                    mRunningInstalls.delete(msg.arg1);
1639
1640                    if (data != null) {
1641                        InstallArgs args = data.args;
1642                        PackageInstalledInfo parentRes = data.res;
1643
1644                        final boolean grantPermissions = (args.installFlags
1645                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1646                        final boolean killApp = (args.installFlags
1647                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1648                        final String[] grantedPermissions = args.installGrantPermissions;
1649
1650                        // Handle the parent package
1651                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1652                                grantedPermissions, didRestore, args.installerPackageName,
1653                                args.observer);
1654
1655                        // Handle the child packages
1656                        final int childCount = (parentRes.addedChildPackages != null)
1657                                ? parentRes.addedChildPackages.size() : 0;
1658                        for (int i = 0; i < childCount; i++) {
1659                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1660                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1661                                    grantedPermissions, false, args.installerPackageName,
1662                                    args.observer);
1663                        }
1664
1665                        // Log tracing if needed
1666                        if (args.traceMethod != null) {
1667                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1668                                    args.traceCookie);
1669                        }
1670                    } else {
1671                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1672                    }
1673
1674                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1675                } break;
1676                case UPDATED_MEDIA_STATUS: {
1677                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1678                    boolean reportStatus = msg.arg1 == 1;
1679                    boolean doGc = msg.arg2 == 1;
1680                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1681                    if (doGc) {
1682                        // Force a gc to clear up stale containers.
1683                        Runtime.getRuntime().gc();
1684                    }
1685                    if (msg.obj != null) {
1686                        @SuppressWarnings("unchecked")
1687                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1688                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1689                        // Unload containers
1690                        unloadAllContainers(args);
1691                    }
1692                    if (reportStatus) {
1693                        try {
1694                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1695                                    "Invoking StorageManagerService call back");
1696                            PackageHelper.getStorageManager().finishMediaUpdate();
1697                        } catch (RemoteException e) {
1698                            Log.e(TAG, "StorageManagerService not running?");
1699                        }
1700                    }
1701                } break;
1702                case WRITE_SETTINGS: {
1703                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1704                    synchronized (mPackages) {
1705                        removeMessages(WRITE_SETTINGS);
1706                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1707                        mSettings.writeLPr();
1708                        mDirtyUsers.clear();
1709                    }
1710                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1711                } break;
1712                case WRITE_PACKAGE_RESTRICTIONS: {
1713                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1714                    synchronized (mPackages) {
1715                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1716                        for (int userId : mDirtyUsers) {
1717                            mSettings.writePackageRestrictionsLPr(userId);
1718                        }
1719                        mDirtyUsers.clear();
1720                    }
1721                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1722                } break;
1723                case WRITE_PACKAGE_LIST: {
1724                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1725                    synchronized (mPackages) {
1726                        removeMessages(WRITE_PACKAGE_LIST);
1727                        mSettings.writePackageListLPr(msg.arg1);
1728                    }
1729                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1730                } break;
1731                case CHECK_PENDING_VERIFICATION: {
1732                    final int verificationId = msg.arg1;
1733                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1734
1735                    if ((state != null) && !state.timeoutExtended()) {
1736                        final InstallArgs args = state.getInstallArgs();
1737                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1738
1739                        Slog.i(TAG, "Verification timed out for " + originUri);
1740                        mPendingVerification.remove(verificationId);
1741
1742                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1743
1744                        final UserHandle user = args.getUser();
1745                        if (getDefaultVerificationResponse(user)
1746                                == PackageManager.VERIFICATION_ALLOW) {
1747                            Slog.i(TAG, "Continuing with installation of " + originUri);
1748                            state.setVerifierResponse(Binder.getCallingUid(),
1749                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1750                            broadcastPackageVerified(verificationId, originUri,
1751                                    PackageManager.VERIFICATION_ALLOW, user);
1752                            try {
1753                                ret = args.copyApk(mContainerService, true);
1754                            } catch (RemoteException e) {
1755                                Slog.e(TAG, "Could not contact the ContainerService");
1756                            }
1757                        } else {
1758                            broadcastPackageVerified(verificationId, originUri,
1759                                    PackageManager.VERIFICATION_REJECT, user);
1760                        }
1761
1762                        Trace.asyncTraceEnd(
1763                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1764
1765                        processPendingInstall(args, ret);
1766                        mHandler.sendEmptyMessage(MCS_UNBIND);
1767                    }
1768                    break;
1769                }
1770                case PACKAGE_VERIFIED: {
1771                    final int verificationId = msg.arg1;
1772
1773                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1774                    if (state == null) {
1775                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1776                        break;
1777                    }
1778
1779                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1780
1781                    state.setVerifierResponse(response.callerUid, response.code);
1782
1783                    if (state.isVerificationComplete()) {
1784                        mPendingVerification.remove(verificationId);
1785
1786                        final InstallArgs args = state.getInstallArgs();
1787                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1788
1789                        int ret;
1790                        if (state.isInstallAllowed()) {
1791                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1792                            broadcastPackageVerified(verificationId, originUri,
1793                                    response.code, state.getInstallArgs().getUser());
1794                            try {
1795                                ret = args.copyApk(mContainerService, true);
1796                            } catch (RemoteException e) {
1797                                Slog.e(TAG, "Could not contact the ContainerService");
1798                            }
1799                        } else {
1800                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1801                        }
1802
1803                        Trace.asyncTraceEnd(
1804                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1805
1806                        processPendingInstall(args, ret);
1807                        mHandler.sendEmptyMessage(MCS_UNBIND);
1808                    }
1809
1810                    break;
1811                }
1812                case START_INTENT_FILTER_VERIFICATIONS: {
1813                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1814                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1815                            params.replacing, params.pkg);
1816                    break;
1817                }
1818                case INTENT_FILTER_VERIFIED: {
1819                    final int verificationId = msg.arg1;
1820
1821                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1822                            verificationId);
1823                    if (state == null) {
1824                        Slog.w(TAG, "Invalid IntentFilter verification token "
1825                                + verificationId + " received");
1826                        break;
1827                    }
1828
1829                    final int userId = state.getUserId();
1830
1831                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1832                            "Processing IntentFilter verification with token:"
1833                            + verificationId + " and userId:" + userId);
1834
1835                    final IntentFilterVerificationResponse response =
1836                            (IntentFilterVerificationResponse) msg.obj;
1837
1838                    state.setVerifierResponse(response.callerUid, response.code);
1839
1840                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1841                            "IntentFilter verification with token:" + verificationId
1842                            + " and userId:" + userId
1843                            + " is settings verifier response with response code:"
1844                            + response.code);
1845
1846                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1847                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1848                                + response.getFailedDomainsString());
1849                    }
1850
1851                    if (state.isVerificationComplete()) {
1852                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1853                    } else {
1854                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1855                                "IntentFilter verification with token:" + verificationId
1856                                + " was not said to be complete");
1857                    }
1858
1859                    break;
1860                }
1861                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1862                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1863                            mInstantAppResolverConnection,
1864                            (InstantAppRequest) msg.obj,
1865                            mInstantAppInstallerActivity,
1866                            mHandler);
1867                }
1868            }
1869        }
1870    }
1871
1872    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1873            boolean killApp, String[] grantedPermissions,
1874            boolean launchedForRestore, String installerPackage,
1875            IPackageInstallObserver2 installObserver) {
1876        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1877            // Send the removed broadcasts
1878            if (res.removedInfo != null) {
1879                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1880            }
1881
1882            // Now that we successfully installed the package, grant runtime
1883            // permissions if requested before broadcasting the install. Also
1884            // for legacy apps in permission review mode we clear the permission
1885            // review flag which is used to emulate runtime permissions for
1886            // legacy apps.
1887            if (grantPermissions) {
1888                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1889            }
1890
1891            final boolean update = res.removedInfo != null
1892                    && res.removedInfo.removedPackage != null;
1893            final String origInstallerPackageName = res.removedInfo != null
1894                    ? res.removedInfo.installerPackageName : null;
1895
1896            // If this is the first time we have child packages for a disabled privileged
1897            // app that had no children, we grant requested runtime permissions to the new
1898            // children if the parent on the system image had them already granted.
1899            if (res.pkg.parentPackage != null) {
1900                synchronized (mPackages) {
1901                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1902                }
1903            }
1904
1905            synchronized (mPackages) {
1906                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1907            }
1908
1909            final String packageName = res.pkg.applicationInfo.packageName;
1910
1911            // Determine the set of users who are adding this package for
1912            // the first time vs. those who are seeing an update.
1913            int[] firstUsers = EMPTY_INT_ARRAY;
1914            int[] updateUsers = EMPTY_INT_ARRAY;
1915            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1916            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1917            for (int newUser : res.newUsers) {
1918                if (ps.getInstantApp(newUser)) {
1919                    continue;
1920                }
1921                if (allNewUsers) {
1922                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1923                    continue;
1924                }
1925                boolean isNew = true;
1926                for (int origUser : res.origUsers) {
1927                    if (origUser == newUser) {
1928                        isNew = false;
1929                        break;
1930                    }
1931                }
1932                if (isNew) {
1933                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1934                } else {
1935                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1936                }
1937            }
1938
1939            // Send installed broadcasts if the package is not a static shared lib.
1940            if (res.pkg.staticSharedLibName == null) {
1941                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1942
1943                // Send added for users that see the package for the first time
1944                // sendPackageAddedForNewUsers also deals with system apps
1945                int appId = UserHandle.getAppId(res.uid);
1946                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1947                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1948
1949                // Send added for users that don't see the package for the first time
1950                Bundle extras = new Bundle(1);
1951                extras.putInt(Intent.EXTRA_UID, res.uid);
1952                if (update) {
1953                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1954                }
1955                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1956                        extras, 0 /*flags*/,
1957                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1958                if (origInstallerPackageName != null) {
1959                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1960                            extras, 0 /*flags*/,
1961                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1962                }
1963
1964                // Send replaced for users that don't see the package for the first time
1965                if (update) {
1966                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1967                            packageName, extras, 0 /*flags*/,
1968                            null /*targetPackage*/, null /*finishedReceiver*/,
1969                            updateUsers);
1970                    if (origInstallerPackageName != null) {
1971                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1972                                extras, 0 /*flags*/,
1973                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1974                    }
1975                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1976                            null /*package*/, null /*extras*/, 0 /*flags*/,
1977                            packageName /*targetPackage*/,
1978                            null /*finishedReceiver*/, updateUsers);
1979                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1980                    // First-install and we did a restore, so we're responsible for the
1981                    // first-launch broadcast.
1982                    if (DEBUG_BACKUP) {
1983                        Slog.i(TAG, "Post-restore of " + packageName
1984                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1985                    }
1986                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1987                }
1988
1989                // Send broadcast package appeared if forward locked/external for all users
1990                // treat asec-hosted packages like removable media on upgrade
1991                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1992                    if (DEBUG_INSTALL) {
1993                        Slog.i(TAG, "upgrading pkg " + res.pkg
1994                                + " is ASEC-hosted -> AVAILABLE");
1995                    }
1996                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1997                    ArrayList<String> pkgList = new ArrayList<>(1);
1998                    pkgList.add(packageName);
1999                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2000                }
2001            }
2002
2003            // Work that needs to happen on first install within each user
2004            if (firstUsers != null && firstUsers.length > 0) {
2005                synchronized (mPackages) {
2006                    for (int userId : firstUsers) {
2007                        // If this app is a browser and it's newly-installed for some
2008                        // users, clear any default-browser state in those users. The
2009                        // app's nature doesn't depend on the user, so we can just check
2010                        // its browser nature in any user and generalize.
2011                        if (packageIsBrowser(packageName, userId)) {
2012                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2013                        }
2014
2015                        // We may also need to apply pending (restored) runtime
2016                        // permission grants within these users.
2017                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2018                    }
2019                }
2020            }
2021
2022            // Log current value of "unknown sources" setting
2023            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2024                    getUnknownSourcesSettings());
2025
2026            // Force a gc to clear up things
2027            Runtime.getRuntime().gc();
2028
2029            // Remove the replaced package's older resources safely now
2030            // We delete after a gc for applications  on sdcard.
2031            if (res.removedInfo != null && res.removedInfo.args != null) {
2032                synchronized (mInstallLock) {
2033                    res.removedInfo.args.doPostDeleteLI(true);
2034                }
2035            }
2036
2037            // Notify DexManager that the package was installed for new users.
2038            // The updated users should already be indexed and the package code paths
2039            // should not change.
2040            // Don't notify the manager for ephemeral apps as they are not expected to
2041            // survive long enough to benefit of background optimizations.
2042            for (int userId : firstUsers) {
2043                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2044                // There's a race currently where some install events may interleave with an uninstall.
2045                // This can lead to package info being null (b/36642664).
2046                if (info != null) {
2047                    mDexManager.notifyPackageInstalled(info, userId);
2048                }
2049            }
2050        }
2051
2052        // If someone is watching installs - notify them
2053        if (installObserver != null) {
2054            try {
2055                Bundle extras = extrasForInstallResult(res);
2056                installObserver.onPackageInstalled(res.name, res.returnCode,
2057                        res.returnMsg, extras);
2058            } catch (RemoteException e) {
2059                Slog.i(TAG, "Observer no longer exists.");
2060            }
2061        }
2062    }
2063
2064    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2065            PackageParser.Package pkg) {
2066        if (pkg.parentPackage == null) {
2067            return;
2068        }
2069        if (pkg.requestedPermissions == null) {
2070            return;
2071        }
2072        final PackageSetting disabledSysParentPs = mSettings
2073                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2074        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2075                || !disabledSysParentPs.isPrivileged()
2076                || (disabledSysParentPs.childPackageNames != null
2077                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2078            return;
2079        }
2080        final int[] allUserIds = sUserManager.getUserIds();
2081        final int permCount = pkg.requestedPermissions.size();
2082        for (int i = 0; i < permCount; i++) {
2083            String permission = pkg.requestedPermissions.get(i);
2084            BasePermission bp = mSettings.mPermissions.get(permission);
2085            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2086                continue;
2087            }
2088            for (int userId : allUserIds) {
2089                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2090                        permission, userId)) {
2091                    grantRuntimePermission(pkg.packageName, permission, userId);
2092                }
2093            }
2094        }
2095    }
2096
2097    private StorageEventListener mStorageListener = new StorageEventListener() {
2098        @Override
2099        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2100            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2101                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2102                    final String volumeUuid = vol.getFsUuid();
2103
2104                    // Clean up any users or apps that were removed or recreated
2105                    // while this volume was missing
2106                    sUserManager.reconcileUsers(volumeUuid);
2107                    reconcileApps(volumeUuid);
2108
2109                    // Clean up any install sessions that expired or were
2110                    // cancelled while this volume was missing
2111                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2112
2113                    loadPrivatePackages(vol);
2114
2115                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2116                    unloadPrivatePackages(vol);
2117                }
2118            }
2119
2120            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2121                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2122                    updateExternalMediaStatus(true, false);
2123                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2124                    updateExternalMediaStatus(false, false);
2125                }
2126            }
2127        }
2128
2129        @Override
2130        public void onVolumeForgotten(String fsUuid) {
2131            if (TextUtils.isEmpty(fsUuid)) {
2132                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2133                return;
2134            }
2135
2136            // Remove any apps installed on the forgotten volume
2137            synchronized (mPackages) {
2138                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2139                for (PackageSetting ps : packages) {
2140                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2141                    deletePackageVersioned(new VersionedPackage(ps.name,
2142                            PackageManager.VERSION_CODE_HIGHEST),
2143                            new LegacyPackageDeleteObserver(null).getBinder(),
2144                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2145                    // Try very hard to release any references to this package
2146                    // so we don't risk the system server being killed due to
2147                    // open FDs
2148                    AttributeCache.instance().removePackage(ps.name);
2149                }
2150
2151                mSettings.onVolumeForgotten(fsUuid);
2152                mSettings.writeLPr();
2153            }
2154        }
2155    };
2156
2157    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2158            String[] grantedPermissions) {
2159        for (int userId : userIds) {
2160            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2161        }
2162    }
2163
2164    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2165            String[] grantedPermissions) {
2166        SettingBase sb = (SettingBase) pkg.mExtras;
2167        if (sb == null) {
2168            return;
2169        }
2170
2171        PermissionsState permissionsState = sb.getPermissionsState();
2172
2173        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2174                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2175
2176        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2177                >= Build.VERSION_CODES.M;
2178
2179        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2180
2181        for (String permission : pkg.requestedPermissions) {
2182            final BasePermission bp;
2183            synchronized (mPackages) {
2184                bp = mSettings.mPermissions.get(permission);
2185            }
2186            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2187                    && (!instantApp || bp.isInstant())
2188                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2189                    && (grantedPermissions == null
2190                           || ArrayUtils.contains(grantedPermissions, permission))) {
2191                final int flags = permissionsState.getPermissionFlags(permission, userId);
2192                if (supportsRuntimePermissions) {
2193                    // Installer cannot change immutable permissions.
2194                    if ((flags & immutableFlags) == 0) {
2195                        grantRuntimePermission(pkg.packageName, permission, userId);
2196                    }
2197                } else if (mPermissionReviewRequired) {
2198                    // In permission review mode we clear the review flag when we
2199                    // are asked to install the app with all permissions granted.
2200                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2201                        updatePermissionFlags(permission, pkg.packageName,
2202                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2203                    }
2204                }
2205            }
2206        }
2207    }
2208
2209    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2210        Bundle extras = null;
2211        switch (res.returnCode) {
2212            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2213                extras = new Bundle();
2214                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2215                        res.origPermission);
2216                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2217                        res.origPackage);
2218                break;
2219            }
2220            case PackageManager.INSTALL_SUCCEEDED: {
2221                extras = new Bundle();
2222                extras.putBoolean(Intent.EXTRA_REPLACING,
2223                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2224                break;
2225            }
2226        }
2227        return extras;
2228    }
2229
2230    void scheduleWriteSettingsLocked() {
2231        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2232            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2233        }
2234    }
2235
2236    void scheduleWritePackageListLocked(int userId) {
2237        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2238            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2239            msg.arg1 = userId;
2240            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2241        }
2242    }
2243
2244    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2245        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2246        scheduleWritePackageRestrictionsLocked(userId);
2247    }
2248
2249    void scheduleWritePackageRestrictionsLocked(int userId) {
2250        final int[] userIds = (userId == UserHandle.USER_ALL)
2251                ? sUserManager.getUserIds() : new int[]{userId};
2252        for (int nextUserId : userIds) {
2253            if (!sUserManager.exists(nextUserId)) return;
2254            mDirtyUsers.add(nextUserId);
2255            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2256                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2257            }
2258        }
2259    }
2260
2261    public static PackageManagerService main(Context context, Installer installer,
2262            boolean factoryTest, boolean onlyCore) {
2263        // Self-check for initial settings.
2264        PackageManagerServiceCompilerMapping.checkProperties();
2265
2266        PackageManagerService m = new PackageManagerService(context, installer,
2267                factoryTest, onlyCore);
2268        m.enableSystemUserPackages();
2269        ServiceManager.addService("package", m);
2270        return m;
2271    }
2272
2273    private void enableSystemUserPackages() {
2274        if (!UserManager.isSplitSystemUser()) {
2275            return;
2276        }
2277        // For system user, enable apps based on the following conditions:
2278        // - app is whitelisted or belong to one of these groups:
2279        //   -- system app which has no launcher icons
2280        //   -- system app which has INTERACT_ACROSS_USERS permission
2281        //   -- system IME app
2282        // - app is not in the blacklist
2283        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2284        Set<String> enableApps = new ArraySet<>();
2285        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2286                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2287                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2288        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2289        enableApps.addAll(wlApps);
2290        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2291                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2292        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2293        enableApps.removeAll(blApps);
2294        Log.i(TAG, "Applications installed for system user: " + enableApps);
2295        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2296                UserHandle.SYSTEM);
2297        final int allAppsSize = allAps.size();
2298        synchronized (mPackages) {
2299            for (int i = 0; i < allAppsSize; i++) {
2300                String pName = allAps.get(i);
2301                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2302                // Should not happen, but we shouldn't be failing if it does
2303                if (pkgSetting == null) {
2304                    continue;
2305                }
2306                boolean install = enableApps.contains(pName);
2307                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2308                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2309                            + " for system user");
2310                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2311                }
2312            }
2313            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2314        }
2315    }
2316
2317    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2318        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2319                Context.DISPLAY_SERVICE);
2320        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2321    }
2322
2323    /**
2324     * Requests that files preopted on a secondary system partition be copied to the data partition
2325     * if possible.  Note that the actual copying of the files is accomplished by init for security
2326     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2327     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2328     */
2329    private static void requestCopyPreoptedFiles() {
2330        final int WAIT_TIME_MS = 100;
2331        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2332        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2333            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2334            // We will wait for up to 100 seconds.
2335            final long timeStart = SystemClock.uptimeMillis();
2336            final long timeEnd = timeStart + 100 * 1000;
2337            long timeNow = timeStart;
2338            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2339                try {
2340                    Thread.sleep(WAIT_TIME_MS);
2341                } catch (InterruptedException e) {
2342                    // Do nothing
2343                }
2344                timeNow = SystemClock.uptimeMillis();
2345                if (timeNow > timeEnd) {
2346                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2347                    Slog.wtf(TAG, "cppreopt did not finish!");
2348                    break;
2349                }
2350            }
2351
2352            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2353        }
2354    }
2355
2356    public PackageManagerService(Context context, Installer installer,
2357            boolean factoryTest, boolean onlyCore) {
2358        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2359        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2360        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2361                SystemClock.uptimeMillis());
2362
2363        if (mSdkVersion <= 0) {
2364            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2365        }
2366
2367        mContext = context;
2368
2369        mPermissionReviewRequired = context.getResources().getBoolean(
2370                R.bool.config_permissionReviewRequired);
2371
2372        mFactoryTest = factoryTest;
2373        mOnlyCore = onlyCore;
2374        mMetrics = new DisplayMetrics();
2375        mSettings = new Settings(mPackages);
2376        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2377                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2378        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2379                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2380        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2381                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2382        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2383                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2384        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2385                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2386        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2387                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2388
2389        String separateProcesses = SystemProperties.get("debug.separate_processes");
2390        if (separateProcesses != null && separateProcesses.length() > 0) {
2391            if ("*".equals(separateProcesses)) {
2392                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2393                mSeparateProcesses = null;
2394                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2395            } else {
2396                mDefParseFlags = 0;
2397                mSeparateProcesses = separateProcesses.split(",");
2398                Slog.w(TAG, "Running with debug.separate_processes: "
2399                        + separateProcesses);
2400            }
2401        } else {
2402            mDefParseFlags = 0;
2403            mSeparateProcesses = null;
2404        }
2405
2406        mInstaller = installer;
2407        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2408                "*dexopt*");
2409        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2410        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2411
2412        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2413                FgThread.get().getLooper());
2414
2415        getDefaultDisplayMetrics(context, mMetrics);
2416
2417        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2418        SystemConfig systemConfig = SystemConfig.getInstance();
2419        mGlobalGids = systemConfig.getGlobalGids();
2420        mSystemPermissions = systemConfig.getSystemPermissions();
2421        mAvailableFeatures = systemConfig.getAvailableFeatures();
2422        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2423
2424        mProtectedPackages = new ProtectedPackages(mContext);
2425
2426        synchronized (mInstallLock) {
2427        // writer
2428        synchronized (mPackages) {
2429            mHandlerThread = new ServiceThread(TAG,
2430                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2431            mHandlerThread.start();
2432            mHandler = new PackageHandler(mHandlerThread.getLooper());
2433            mProcessLoggingHandler = new ProcessLoggingHandler();
2434            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2435
2436            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2437            mInstantAppRegistry = new InstantAppRegistry(this);
2438
2439            File dataDir = Environment.getDataDirectory();
2440            mAppInstallDir = new File(dataDir, "app");
2441            mAppLib32InstallDir = new File(dataDir, "app-lib");
2442            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2443            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2444            sUserManager = new UserManagerService(context, this,
2445                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2446
2447            // Propagate permission configuration in to package manager.
2448            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2449                    = systemConfig.getPermissions();
2450            for (int i=0; i<permConfig.size(); i++) {
2451                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2452                BasePermission bp = mSettings.mPermissions.get(perm.name);
2453                if (bp == null) {
2454                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2455                    mSettings.mPermissions.put(perm.name, bp);
2456                }
2457                if (perm.gids != null) {
2458                    bp.setGids(perm.gids, perm.perUser);
2459                }
2460            }
2461
2462            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2463            final int builtInLibCount = libConfig.size();
2464            for (int i = 0; i < builtInLibCount; i++) {
2465                String name = libConfig.keyAt(i);
2466                String path = libConfig.valueAt(i);
2467                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2468                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2469            }
2470
2471            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2472
2473            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2474            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2475            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2476
2477            // Clean up orphaned packages for which the code path doesn't exist
2478            // and they are an update to a system app - caused by bug/32321269
2479            final int packageSettingCount = mSettings.mPackages.size();
2480            for (int i = packageSettingCount - 1; i >= 0; i--) {
2481                PackageSetting ps = mSettings.mPackages.valueAt(i);
2482                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2483                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2484                    mSettings.mPackages.removeAt(i);
2485                    mSettings.enableSystemPackageLPw(ps.name);
2486                }
2487            }
2488
2489            if (mFirstBoot) {
2490                requestCopyPreoptedFiles();
2491            }
2492
2493            String customResolverActivity = Resources.getSystem().getString(
2494                    R.string.config_customResolverActivity);
2495            if (TextUtils.isEmpty(customResolverActivity)) {
2496                customResolverActivity = null;
2497            } else {
2498                mCustomResolverComponentName = ComponentName.unflattenFromString(
2499                        customResolverActivity);
2500            }
2501
2502            long startTime = SystemClock.uptimeMillis();
2503
2504            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2505                    startTime);
2506
2507            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2508            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2509
2510            if (bootClassPath == null) {
2511                Slog.w(TAG, "No BOOTCLASSPATH found!");
2512            }
2513
2514            if (systemServerClassPath == null) {
2515                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2516            }
2517
2518            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2519
2520            final VersionInfo ver = mSettings.getInternalVersion();
2521            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2522            if (mIsUpgrade) {
2523                logCriticalInfo(Log.INFO,
2524                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2525            }
2526
2527            // when upgrading from pre-M, promote system app permissions from install to runtime
2528            mPromoteSystemApps =
2529                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2530
2531            // When upgrading from pre-N, we need to handle package extraction like first boot,
2532            // as there is no profiling data available.
2533            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2534
2535            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2536
2537            // save off the names of pre-existing system packages prior to scanning; we don't
2538            // want to automatically grant runtime permissions for new system apps
2539            if (mPromoteSystemApps) {
2540                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2541                while (pkgSettingIter.hasNext()) {
2542                    PackageSetting ps = pkgSettingIter.next();
2543                    if (isSystemApp(ps)) {
2544                        mExistingSystemPackages.add(ps.name);
2545                    }
2546                }
2547            }
2548
2549            mCacheDir = preparePackageParserCache(mIsUpgrade);
2550
2551            // Set flag to monitor and not change apk file paths when
2552            // scanning install directories.
2553            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2554
2555            if (mIsUpgrade || mFirstBoot) {
2556                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2557            }
2558
2559            // Collect vendor overlay packages. (Do this before scanning any apps.)
2560            // For security and version matching reason, only consider
2561            // overlay packages if they reside in the right directory.
2562            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2563                    | PackageParser.PARSE_IS_SYSTEM
2564                    | PackageParser.PARSE_IS_SYSTEM_DIR
2565                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2566
2567            mParallelPackageParserCallback.findStaticOverlayPackages();
2568
2569            // Find base frameworks (resource packages without code).
2570            scanDirTracedLI(frameworkDir, mDefParseFlags
2571                    | PackageParser.PARSE_IS_SYSTEM
2572                    | PackageParser.PARSE_IS_SYSTEM_DIR
2573                    | PackageParser.PARSE_IS_PRIVILEGED,
2574                    scanFlags | SCAN_NO_DEX, 0);
2575
2576            // Collected privileged system packages.
2577            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2578            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2579                    | PackageParser.PARSE_IS_SYSTEM
2580                    | PackageParser.PARSE_IS_SYSTEM_DIR
2581                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2582
2583            // Collect ordinary system packages.
2584            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2585            scanDirTracedLI(systemAppDir, mDefParseFlags
2586                    | PackageParser.PARSE_IS_SYSTEM
2587                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2588
2589            // Collect all vendor packages.
2590            File vendorAppDir = new File("/vendor/app");
2591            try {
2592                vendorAppDir = vendorAppDir.getCanonicalFile();
2593            } catch (IOException e) {
2594                // failed to look up canonical path, continue with original one
2595            }
2596            scanDirTracedLI(vendorAppDir, mDefParseFlags
2597                    | PackageParser.PARSE_IS_SYSTEM
2598                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2599
2600            // Collect all OEM packages.
2601            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2602            scanDirTracedLI(oemAppDir, mDefParseFlags
2603                    | PackageParser.PARSE_IS_SYSTEM
2604                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2605
2606            // Prune any system packages that no longer exist.
2607            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2608            if (!mOnlyCore) {
2609                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2610                while (psit.hasNext()) {
2611                    PackageSetting ps = psit.next();
2612
2613                    /*
2614                     * If this is not a system app, it can't be a
2615                     * disable system app.
2616                     */
2617                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2618                        continue;
2619                    }
2620
2621                    /*
2622                     * If the package is scanned, it's not erased.
2623                     */
2624                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2625                    if (scannedPkg != null) {
2626                        /*
2627                         * If the system app is both scanned and in the
2628                         * disabled packages list, then it must have been
2629                         * added via OTA. Remove it from the currently
2630                         * scanned package so the previously user-installed
2631                         * application can be scanned.
2632                         */
2633                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2634                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2635                                    + ps.name + "; removing system app.  Last known codePath="
2636                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2637                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2638                                    + scannedPkg.mVersionCode);
2639                            removePackageLI(scannedPkg, true);
2640                            mExpectingBetter.put(ps.name, ps.codePath);
2641                        }
2642
2643                        continue;
2644                    }
2645
2646                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2647                        psit.remove();
2648                        logCriticalInfo(Log.WARN, "System package " + ps.name
2649                                + " no longer exists; it's data will be wiped");
2650                        // Actual deletion of code and data will be handled by later
2651                        // reconciliation step
2652                    } else {
2653                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2654                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2655                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2656                        }
2657                    }
2658                }
2659            }
2660
2661            //look for any incomplete package installations
2662            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2663            for (int i = 0; i < deletePkgsList.size(); i++) {
2664                // Actual deletion of code and data will be handled by later
2665                // reconciliation step
2666                final String packageName = deletePkgsList.get(i).name;
2667                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2668                synchronized (mPackages) {
2669                    mSettings.removePackageLPw(packageName);
2670                }
2671            }
2672
2673            //delete tmp files
2674            deleteTempPackageFiles();
2675
2676            // Remove any shared userIDs that have no associated packages
2677            mSettings.pruneSharedUsersLPw();
2678
2679            if (!mOnlyCore) {
2680                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2681                        SystemClock.uptimeMillis());
2682                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2683
2684                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2685                        | PackageParser.PARSE_FORWARD_LOCK,
2686                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2687
2688                /**
2689                 * Remove disable package settings for any updated system
2690                 * apps that were removed via an OTA. If they're not a
2691                 * previously-updated app, remove them completely.
2692                 * Otherwise, just revoke their system-level permissions.
2693                 */
2694                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2695                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2696                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2697
2698                    String msg;
2699                    if (deletedPkg == null) {
2700                        msg = "Updated system package " + deletedAppName
2701                                + " no longer exists; it's data will be wiped";
2702                        // Actual deletion of code and data will be handled by later
2703                        // reconciliation step
2704                    } else {
2705                        msg = "Updated system app + " + deletedAppName
2706                                + " no longer present; removing system privileges for "
2707                                + deletedAppName;
2708
2709                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2710
2711                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2712                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2713                    }
2714                    logCriticalInfo(Log.WARN, msg);
2715                }
2716
2717                /**
2718                 * Make sure all system apps that we expected to appear on
2719                 * the userdata partition actually showed up. If they never
2720                 * appeared, crawl back and revive the system version.
2721                 */
2722                for (int i = 0; i < mExpectingBetter.size(); i++) {
2723                    final String packageName = mExpectingBetter.keyAt(i);
2724                    if (!mPackages.containsKey(packageName)) {
2725                        final File scanFile = mExpectingBetter.valueAt(i);
2726
2727                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2728                                + " but never showed up; reverting to system");
2729
2730                        int reparseFlags = mDefParseFlags;
2731                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2732                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2733                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2734                                    | PackageParser.PARSE_IS_PRIVILEGED;
2735                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2736                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2737                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2738                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2739                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2740                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2741                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2742                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2743                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2744                        } else {
2745                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2746                            continue;
2747                        }
2748
2749                        mSettings.enableSystemPackageLPw(packageName);
2750
2751                        try {
2752                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2753                        } catch (PackageManagerException e) {
2754                            Slog.e(TAG, "Failed to parse original system package: "
2755                                    + e.getMessage());
2756                        }
2757                    }
2758                }
2759            }
2760            mExpectingBetter.clear();
2761
2762            // Resolve the storage manager.
2763            mStorageManagerPackage = getStorageManagerPackageName();
2764
2765            // Resolve protected action filters. Only the setup wizard is allowed to
2766            // have a high priority filter for these actions.
2767            mSetupWizardPackage = getSetupWizardPackageName();
2768            if (mProtectedFilters.size() > 0) {
2769                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2770                    Slog.i(TAG, "No setup wizard;"
2771                        + " All protected intents capped to priority 0");
2772                }
2773                for (ActivityIntentInfo filter : mProtectedFilters) {
2774                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2775                        if (DEBUG_FILTERS) {
2776                            Slog.i(TAG, "Found setup wizard;"
2777                                + " allow priority " + filter.getPriority() + ";"
2778                                + " package: " + filter.activity.info.packageName
2779                                + " activity: " + filter.activity.className
2780                                + " priority: " + filter.getPriority());
2781                        }
2782                        // skip setup wizard; allow it to keep the high priority filter
2783                        continue;
2784                    }
2785                    Slog.w(TAG, "Protected action; cap priority to 0;"
2786                            + " package: " + filter.activity.info.packageName
2787                            + " activity: " + filter.activity.className
2788                            + " origPrio: " + filter.getPriority());
2789                    filter.setPriority(0);
2790                }
2791            }
2792            mDeferProtectedFilters = false;
2793            mProtectedFilters.clear();
2794
2795            // Now that we know all of the shared libraries, update all clients to have
2796            // the correct library paths.
2797            updateAllSharedLibrariesLPw(null);
2798
2799            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2800                // NOTE: We ignore potential failures here during a system scan (like
2801                // the rest of the commands above) because there's precious little we
2802                // can do about it. A settings error is reported, though.
2803                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2804            }
2805
2806            // Now that we know all the packages we are keeping,
2807            // read and update their last usage times.
2808            mPackageUsage.read(mPackages);
2809            mCompilerStats.read();
2810
2811            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2812                    SystemClock.uptimeMillis());
2813            Slog.i(TAG, "Time to scan packages: "
2814                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2815                    + " seconds");
2816
2817            // If the platform SDK has changed since the last time we booted,
2818            // we need to re-grant app permission to catch any new ones that
2819            // appear.  This is really a hack, and means that apps can in some
2820            // cases get permissions that the user didn't initially explicitly
2821            // allow...  it would be nice to have some better way to handle
2822            // this situation.
2823            int updateFlags = UPDATE_PERMISSIONS_ALL;
2824            if (ver.sdkVersion != mSdkVersion) {
2825                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2826                        + mSdkVersion + "; regranting permissions for internal storage");
2827                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2828            }
2829            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2830            ver.sdkVersion = mSdkVersion;
2831
2832            // If this is the first boot or an update from pre-M, and it is a normal
2833            // boot, then we need to initialize the default preferred apps across
2834            // all defined users.
2835            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2836                for (UserInfo user : sUserManager.getUsers(true)) {
2837                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2838                    applyFactoryDefaultBrowserLPw(user.id);
2839                    primeDomainVerificationsLPw(user.id);
2840                }
2841            }
2842
2843            // Prepare storage for system user really early during boot,
2844            // since core system apps like SettingsProvider and SystemUI
2845            // can't wait for user to start
2846            final int storageFlags;
2847            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2848                storageFlags = StorageManager.FLAG_STORAGE_DE;
2849            } else {
2850                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2851            }
2852            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2853                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2854                    true /* onlyCoreApps */);
2855            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2856                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2857                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2858                traceLog.traceBegin("AppDataFixup");
2859                try {
2860                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2861                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2862                } catch (InstallerException e) {
2863                    Slog.w(TAG, "Trouble fixing GIDs", e);
2864                }
2865                traceLog.traceEnd();
2866
2867                traceLog.traceBegin("AppDataPrepare");
2868                if (deferPackages == null || deferPackages.isEmpty()) {
2869                    return;
2870                }
2871                int count = 0;
2872                for (String pkgName : deferPackages) {
2873                    PackageParser.Package pkg = null;
2874                    synchronized (mPackages) {
2875                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2876                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2877                            pkg = ps.pkg;
2878                        }
2879                    }
2880                    if (pkg != null) {
2881                        synchronized (mInstallLock) {
2882                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2883                                    true /* maybeMigrateAppData */);
2884                        }
2885                        count++;
2886                    }
2887                }
2888                traceLog.traceEnd();
2889                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2890            }, "prepareAppData");
2891
2892            // If this is first boot after an OTA, and a normal boot, then
2893            // we need to clear code cache directories.
2894            // Note that we do *not* clear the application profiles. These remain valid
2895            // across OTAs and are used to drive profile verification (post OTA) and
2896            // profile compilation (without waiting to collect a fresh set of profiles).
2897            if (mIsUpgrade && !onlyCore) {
2898                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2899                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2900                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2901                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2902                        // No apps are running this early, so no need to freeze
2903                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2904                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2905                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2906                    }
2907                }
2908                ver.fingerprint = Build.FINGERPRINT;
2909            }
2910
2911            checkDefaultBrowser();
2912
2913            // clear only after permissions and other defaults have been updated
2914            mExistingSystemPackages.clear();
2915            mPromoteSystemApps = false;
2916
2917            // All the changes are done during package scanning.
2918            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2919
2920            // can downgrade to reader
2921            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2922            mSettings.writeLPr();
2923            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2924
2925            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2926                    SystemClock.uptimeMillis());
2927
2928            if (!mOnlyCore) {
2929                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2930                mRequiredInstallerPackage = getRequiredInstallerLPr();
2931                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2932                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2933                if (mIntentFilterVerifierComponent != null) {
2934                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2935                            mIntentFilterVerifierComponent);
2936                } else {
2937                    mIntentFilterVerifier = null;
2938                }
2939                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2940                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2941                        SharedLibraryInfo.VERSION_UNDEFINED);
2942                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2943                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2944                        SharedLibraryInfo.VERSION_UNDEFINED);
2945            } else {
2946                mRequiredVerifierPackage = null;
2947                mRequiredInstallerPackage = null;
2948                mRequiredUninstallerPackage = null;
2949                mIntentFilterVerifierComponent = null;
2950                mIntentFilterVerifier = null;
2951                mServicesSystemSharedLibraryPackageName = null;
2952                mSharedSystemSharedLibraryPackageName = null;
2953            }
2954
2955            mInstallerService = new PackageInstallerService(context, this);
2956            final Pair<ComponentName, String> instantAppResolverComponent =
2957                    getInstantAppResolverLPr();
2958            if (instantAppResolverComponent != null) {
2959                if (DEBUG_EPHEMERAL) {
2960                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2961                }
2962                mInstantAppResolverConnection = new EphemeralResolverConnection(
2963                        mContext, instantAppResolverComponent.first,
2964                        instantAppResolverComponent.second);
2965                mInstantAppResolverSettingsComponent =
2966                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2967            } else {
2968                mInstantAppResolverConnection = null;
2969                mInstantAppResolverSettingsComponent = null;
2970            }
2971            updateInstantAppInstallerLocked(null);
2972
2973            // Read and update the usage of dex files.
2974            // Do this at the end of PM init so that all the packages have their
2975            // data directory reconciled.
2976            // At this point we know the code paths of the packages, so we can validate
2977            // the disk file and build the internal cache.
2978            // The usage file is expected to be small so loading and verifying it
2979            // should take a fairly small time compare to the other activities (e.g. package
2980            // scanning).
2981            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2982            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2983            for (int userId : currentUserIds) {
2984                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2985            }
2986            mDexManager.load(userPackages);
2987        } // synchronized (mPackages)
2988        } // synchronized (mInstallLock)
2989
2990        // Now after opening every single application zip, make sure they
2991        // are all flushed.  Not really needed, but keeps things nice and
2992        // tidy.
2993        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2994        Runtime.getRuntime().gc();
2995        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2996
2997        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2998        FallbackCategoryProvider.loadFallbacks();
2999        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3000
3001        // The initial scanning above does many calls into installd while
3002        // holding the mPackages lock, but we're mostly interested in yelling
3003        // once we have a booted system.
3004        mInstaller.setWarnIfHeld(mPackages);
3005
3006        // Expose private service for system components to use.
3007        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3008        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3009    }
3010
3011    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3012        // we're only interested in updating the installer appliction when 1) it's not
3013        // already set or 2) the modified package is the installer
3014        if (mInstantAppInstallerActivity != null
3015                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3016                        .equals(modifiedPackage)) {
3017            return;
3018        }
3019        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3020    }
3021
3022    private static File preparePackageParserCache(boolean isUpgrade) {
3023        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3024            return null;
3025        }
3026
3027        // Disable package parsing on eng builds to allow for faster incremental development.
3028        if ("eng".equals(Build.TYPE)) {
3029            return null;
3030        }
3031
3032        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3033            Slog.i(TAG, "Disabling package parser cache due to system property.");
3034            return null;
3035        }
3036
3037        // The base directory for the package parser cache lives under /data/system/.
3038        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3039                "package_cache");
3040        if (cacheBaseDir == null) {
3041            return null;
3042        }
3043
3044        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3045        // This also serves to "GC" unused entries when the package cache version changes (which
3046        // can only happen during upgrades).
3047        if (isUpgrade) {
3048            FileUtils.deleteContents(cacheBaseDir);
3049        }
3050
3051
3052        // Return the versioned package cache directory. This is something like
3053        // "/data/system/package_cache/1"
3054        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3055
3056        // The following is a workaround to aid development on non-numbered userdebug
3057        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3058        // the system partition is newer.
3059        //
3060        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3061        // that starts with "eng." to signify that this is an engineering build and not
3062        // destined for release.
3063        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3064            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3065
3066            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3067            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3068            // in general and should not be used for production changes. In this specific case,
3069            // we know that they will work.
3070            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3071            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3072                FileUtils.deleteContents(cacheBaseDir);
3073                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3074            }
3075        }
3076
3077        return cacheDir;
3078    }
3079
3080    @Override
3081    public boolean isFirstBoot() {
3082        return mFirstBoot;
3083    }
3084
3085    @Override
3086    public boolean isOnlyCoreApps() {
3087        return mOnlyCore;
3088    }
3089
3090    @Override
3091    public boolean isUpgrade() {
3092        return mIsUpgrade;
3093    }
3094
3095    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3096        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3097
3098        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3099                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3100                UserHandle.USER_SYSTEM);
3101        if (matches.size() == 1) {
3102            return matches.get(0).getComponentInfo().packageName;
3103        } else if (matches.size() == 0) {
3104            Log.e(TAG, "There should probably be a verifier, but, none were found");
3105            return null;
3106        }
3107        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3108    }
3109
3110    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3111        synchronized (mPackages) {
3112            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3113            if (libraryEntry == null) {
3114                throw new IllegalStateException("Missing required shared library:" + name);
3115            }
3116            return libraryEntry.apk;
3117        }
3118    }
3119
3120    private @NonNull String getRequiredInstallerLPr() {
3121        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3122        intent.addCategory(Intent.CATEGORY_DEFAULT);
3123        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3124
3125        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3126                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3127                UserHandle.USER_SYSTEM);
3128        if (matches.size() == 1) {
3129            ResolveInfo resolveInfo = matches.get(0);
3130            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3131                throw new RuntimeException("The installer must be a privileged app");
3132            }
3133            return matches.get(0).getComponentInfo().packageName;
3134        } else {
3135            throw new RuntimeException("There must be exactly one installer; found " + matches);
3136        }
3137    }
3138
3139    private @NonNull String getRequiredUninstallerLPr() {
3140        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3141        intent.addCategory(Intent.CATEGORY_DEFAULT);
3142        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3143
3144        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3145                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3146                UserHandle.USER_SYSTEM);
3147        if (resolveInfo == null ||
3148                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3149            throw new RuntimeException("There must be exactly one uninstaller; found "
3150                    + resolveInfo);
3151        }
3152        return resolveInfo.getComponentInfo().packageName;
3153    }
3154
3155    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3156        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3157
3158        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3159                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3160                UserHandle.USER_SYSTEM);
3161        ResolveInfo best = null;
3162        final int N = matches.size();
3163        for (int i = 0; i < N; i++) {
3164            final ResolveInfo cur = matches.get(i);
3165            final String packageName = cur.getComponentInfo().packageName;
3166            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3167                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3168                continue;
3169            }
3170
3171            if (best == null || cur.priority > best.priority) {
3172                best = cur;
3173            }
3174        }
3175
3176        if (best != null) {
3177            return best.getComponentInfo().getComponentName();
3178        }
3179        Slog.w(TAG, "Intent filter verifier not found");
3180        return null;
3181    }
3182
3183    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3184        final String[] packageArray =
3185                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3186        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3187            if (DEBUG_EPHEMERAL) {
3188                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3189            }
3190            return null;
3191        }
3192
3193        final int callingUid = Binder.getCallingUid();
3194        final int resolveFlags =
3195                MATCH_DIRECT_BOOT_AWARE
3196                | MATCH_DIRECT_BOOT_UNAWARE
3197                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3198        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3199        final Intent resolverIntent = new Intent(actionName);
3200        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3201                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3202        // temporarily look for the old action
3203        if (resolvers.size() == 0) {
3204            if (DEBUG_EPHEMERAL) {
3205                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3206            }
3207            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3208            resolverIntent.setAction(actionName);
3209            resolvers = queryIntentServicesInternal(resolverIntent, null,
3210                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3211        }
3212        final int N = resolvers.size();
3213        if (N == 0) {
3214            if (DEBUG_EPHEMERAL) {
3215                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3216            }
3217            return null;
3218        }
3219
3220        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3221        for (int i = 0; i < N; i++) {
3222            final ResolveInfo info = resolvers.get(i);
3223
3224            if (info.serviceInfo == null) {
3225                continue;
3226            }
3227
3228            final String packageName = info.serviceInfo.packageName;
3229            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3230                if (DEBUG_EPHEMERAL) {
3231                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3232                            + " pkg: " + packageName + ", info:" + info);
3233                }
3234                continue;
3235            }
3236
3237            if (DEBUG_EPHEMERAL) {
3238                Slog.v(TAG, "Ephemeral resolver found;"
3239                        + " pkg: " + packageName + ", info:" + info);
3240            }
3241            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3242        }
3243        if (DEBUG_EPHEMERAL) {
3244            Slog.v(TAG, "Ephemeral resolver NOT found");
3245        }
3246        return null;
3247    }
3248
3249    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3250        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3251        intent.addCategory(Intent.CATEGORY_DEFAULT);
3252        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3253
3254        final int resolveFlags =
3255                MATCH_DIRECT_BOOT_AWARE
3256                | MATCH_DIRECT_BOOT_UNAWARE
3257                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3258        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3259                resolveFlags, UserHandle.USER_SYSTEM);
3260        // temporarily look for the old action
3261        if (matches.isEmpty()) {
3262            if (DEBUG_EPHEMERAL) {
3263                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3264            }
3265            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3266            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3267                    resolveFlags, UserHandle.USER_SYSTEM);
3268        }
3269        Iterator<ResolveInfo> iter = matches.iterator();
3270        while (iter.hasNext()) {
3271            final ResolveInfo rInfo = iter.next();
3272            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3273            if (ps != null) {
3274                final PermissionsState permissionsState = ps.getPermissionsState();
3275                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3276                    continue;
3277                }
3278            }
3279            iter.remove();
3280        }
3281        if (matches.size() == 0) {
3282            return null;
3283        } else if (matches.size() == 1) {
3284            return (ActivityInfo) matches.get(0).getComponentInfo();
3285        } else {
3286            throw new RuntimeException(
3287                    "There must be at most one ephemeral installer; found " + matches);
3288        }
3289    }
3290
3291    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3292            @NonNull ComponentName resolver) {
3293        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3294                .addCategory(Intent.CATEGORY_DEFAULT)
3295                .setPackage(resolver.getPackageName());
3296        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3297        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3298                UserHandle.USER_SYSTEM);
3299        // temporarily look for the old action
3300        if (matches.isEmpty()) {
3301            if (DEBUG_EPHEMERAL) {
3302                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3303            }
3304            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3305            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3306                    UserHandle.USER_SYSTEM);
3307        }
3308        if (matches.isEmpty()) {
3309            return null;
3310        }
3311        return matches.get(0).getComponentInfo().getComponentName();
3312    }
3313
3314    private void primeDomainVerificationsLPw(int userId) {
3315        if (DEBUG_DOMAIN_VERIFICATION) {
3316            Slog.d(TAG, "Priming domain verifications in user " + userId);
3317        }
3318
3319        SystemConfig systemConfig = SystemConfig.getInstance();
3320        ArraySet<String> packages = systemConfig.getLinkedApps();
3321
3322        for (String packageName : packages) {
3323            PackageParser.Package pkg = mPackages.get(packageName);
3324            if (pkg != null) {
3325                if (!pkg.isSystemApp()) {
3326                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3327                    continue;
3328                }
3329
3330                ArraySet<String> domains = null;
3331                for (PackageParser.Activity a : pkg.activities) {
3332                    for (ActivityIntentInfo filter : a.intents) {
3333                        if (hasValidDomains(filter)) {
3334                            if (domains == null) {
3335                                domains = new ArraySet<String>();
3336                            }
3337                            domains.addAll(filter.getHostsList());
3338                        }
3339                    }
3340                }
3341
3342                if (domains != null && domains.size() > 0) {
3343                    if (DEBUG_DOMAIN_VERIFICATION) {
3344                        Slog.v(TAG, "      + " + packageName);
3345                    }
3346                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3347                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3348                    // and then 'always' in the per-user state actually used for intent resolution.
3349                    final IntentFilterVerificationInfo ivi;
3350                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3351                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3352                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3353                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3354                } else {
3355                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3356                            + "' does not handle web links");
3357                }
3358            } else {
3359                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3360            }
3361        }
3362
3363        scheduleWritePackageRestrictionsLocked(userId);
3364        scheduleWriteSettingsLocked();
3365    }
3366
3367    private void applyFactoryDefaultBrowserLPw(int userId) {
3368        // The default browser app's package name is stored in a string resource,
3369        // with a product-specific overlay used for vendor customization.
3370        String browserPkg = mContext.getResources().getString(
3371                com.android.internal.R.string.default_browser);
3372        if (!TextUtils.isEmpty(browserPkg)) {
3373            // non-empty string => required to be a known package
3374            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3375            if (ps == null) {
3376                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3377                browserPkg = null;
3378            } else {
3379                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3380            }
3381        }
3382
3383        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3384        // default.  If there's more than one, just leave everything alone.
3385        if (browserPkg == null) {
3386            calculateDefaultBrowserLPw(userId);
3387        }
3388    }
3389
3390    private void calculateDefaultBrowserLPw(int userId) {
3391        List<String> allBrowsers = resolveAllBrowserApps(userId);
3392        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3393        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3394    }
3395
3396    private List<String> resolveAllBrowserApps(int userId) {
3397        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3398        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3399                PackageManager.MATCH_ALL, userId);
3400
3401        final int count = list.size();
3402        List<String> result = new ArrayList<String>(count);
3403        for (int i=0; i<count; i++) {
3404            ResolveInfo info = list.get(i);
3405            if (info.activityInfo == null
3406                    || !info.handleAllWebDataURI
3407                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3408                    || result.contains(info.activityInfo.packageName)) {
3409                continue;
3410            }
3411            result.add(info.activityInfo.packageName);
3412        }
3413
3414        return result;
3415    }
3416
3417    private boolean packageIsBrowser(String packageName, int userId) {
3418        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3419                PackageManager.MATCH_ALL, userId);
3420        final int N = list.size();
3421        for (int i = 0; i < N; i++) {
3422            ResolveInfo info = list.get(i);
3423            if (packageName.equals(info.activityInfo.packageName)) {
3424                return true;
3425            }
3426        }
3427        return false;
3428    }
3429
3430    private void checkDefaultBrowser() {
3431        final int myUserId = UserHandle.myUserId();
3432        final String packageName = getDefaultBrowserPackageName(myUserId);
3433        if (packageName != null) {
3434            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3435            if (info == null) {
3436                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3437                synchronized (mPackages) {
3438                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3439                }
3440            }
3441        }
3442    }
3443
3444    @Override
3445    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3446            throws RemoteException {
3447        try {
3448            return super.onTransact(code, data, reply, flags);
3449        } catch (RuntimeException e) {
3450            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3451                Slog.wtf(TAG, "Package Manager Crash", e);
3452            }
3453            throw e;
3454        }
3455    }
3456
3457    static int[] appendInts(int[] cur, int[] add) {
3458        if (add == null) return cur;
3459        if (cur == null) return add;
3460        final int N = add.length;
3461        for (int i=0; i<N; i++) {
3462            cur = appendInt(cur, add[i]);
3463        }
3464        return cur;
3465    }
3466
3467    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3468        if (!sUserManager.exists(userId)) return null;
3469        if (ps == null) {
3470            return null;
3471        }
3472        final PackageParser.Package p = ps.pkg;
3473        if (p == null) {
3474            return null;
3475        }
3476        // Filter out ephemeral app metadata:
3477        //   * The system/shell/root can see metadata for any app
3478        //   * An installed app can see metadata for 1) other installed apps
3479        //     and 2) ephemeral apps that have explicitly interacted with it
3480        //   * Ephemeral apps can only see their own data and exposed installed apps
3481        //   * Holding a signature permission allows seeing instant apps
3482        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3483        if (callingAppId != Process.SYSTEM_UID
3484                && callingAppId != Process.SHELL_UID
3485                && callingAppId != Process.ROOT_UID
3486                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3487                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3488            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3489            if (instantAppPackageName != null) {
3490                // ephemeral apps can only get information on themselves or
3491                // installed apps that are exposed.
3492                if (!instantAppPackageName.equals(p.packageName)
3493                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3494                    return null;
3495                }
3496            } else {
3497                if (ps.getInstantApp(userId)) {
3498                    // only get access to the ephemeral app if we've been granted access
3499                    if (!mInstantAppRegistry.isInstantAccessGranted(
3500                            userId, callingAppId, ps.appId)) {
3501                        return null;
3502                    }
3503                }
3504            }
3505        }
3506
3507        final PermissionsState permissionsState = ps.getPermissionsState();
3508
3509        // Compute GIDs only if requested
3510        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3511                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3512        // Compute granted permissions only if package has requested permissions
3513        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3514                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3515        final PackageUserState state = ps.readUserState(userId);
3516
3517        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3518                && ps.isSystem()) {
3519            flags |= MATCH_ANY_USER;
3520        }
3521
3522        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3523                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3524
3525        if (packageInfo == null) {
3526            return null;
3527        }
3528
3529        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3530
3531        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3532                resolveExternalPackageNameLPr(p);
3533
3534        return packageInfo;
3535    }
3536
3537    @Override
3538    public void checkPackageStartable(String packageName, int userId) {
3539        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3540
3541        synchronized (mPackages) {
3542            final PackageSetting ps = mSettings.mPackages.get(packageName);
3543            if (ps == null) {
3544                throw new SecurityException("Package " + packageName + " was not found!");
3545            }
3546
3547            if (!ps.getInstalled(userId)) {
3548                throw new SecurityException(
3549                        "Package " + packageName + " was not installed for user " + userId + "!");
3550            }
3551
3552            if (mSafeMode && !ps.isSystem()) {
3553                throw new SecurityException("Package " + packageName + " not a system app!");
3554            }
3555
3556            if (mFrozenPackages.contains(packageName)) {
3557                throw new SecurityException("Package " + packageName + " is currently frozen!");
3558            }
3559
3560            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3561                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3562                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3563            }
3564        }
3565    }
3566
3567    @Override
3568    public boolean isPackageAvailable(String packageName, int userId) {
3569        if (!sUserManager.exists(userId)) return false;
3570        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3571                false /* requireFullPermission */, false /* checkShell */, "is package available");
3572        synchronized (mPackages) {
3573            PackageParser.Package p = mPackages.get(packageName);
3574            if (p != null) {
3575                final PackageSetting ps = (PackageSetting) p.mExtras;
3576                if (ps != null) {
3577                    final PackageUserState state = ps.readUserState(userId);
3578                    if (state != null) {
3579                        return PackageParser.isAvailable(state);
3580                    }
3581                }
3582            }
3583        }
3584        return false;
3585    }
3586
3587    @Override
3588    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3589        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3590                flags, userId);
3591    }
3592
3593    @Override
3594    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3595            int flags, int userId) {
3596        return getPackageInfoInternal(versionedPackage.getPackageName(),
3597                // TODO: We will change version code to long, so in the new API it is long
3598                (int) versionedPackage.getVersionCode(), flags, userId);
3599    }
3600
3601    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3602            int flags, int userId) {
3603        if (!sUserManager.exists(userId)) return null;
3604        flags = updateFlagsForPackage(flags, userId, packageName);
3605        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3606                false /* requireFullPermission */, false /* checkShell */, "get package info");
3607
3608        // reader
3609        synchronized (mPackages) {
3610            // Normalize package name to handle renamed packages and static libs
3611            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3612
3613            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3614            if (matchFactoryOnly) {
3615                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3616                if (ps != null) {
3617                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3618                        return null;
3619                    }
3620                    return generatePackageInfo(ps, flags, userId);
3621                }
3622            }
3623
3624            PackageParser.Package p = mPackages.get(packageName);
3625            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3626                return null;
3627            }
3628            if (DEBUG_PACKAGE_INFO)
3629                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3630            if (p != null) {
3631                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3632                        Binder.getCallingUid(), userId)) {
3633                    return null;
3634                }
3635                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3636            }
3637            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3638                final PackageSetting ps = mSettings.mPackages.get(packageName);
3639                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3640                    return null;
3641                }
3642                return generatePackageInfo(ps, flags, userId);
3643            }
3644        }
3645        return null;
3646    }
3647
3648
3649    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3650        // System/shell/root get to see all static libs
3651        final int appId = UserHandle.getAppId(uid);
3652        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3653                || appId == Process.ROOT_UID) {
3654            return false;
3655        }
3656
3657        // No package means no static lib as it is always on internal storage
3658        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3659            return false;
3660        }
3661
3662        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3663                ps.pkg.staticSharedLibVersion);
3664        if (libEntry == null) {
3665            return false;
3666        }
3667
3668        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3669        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3670        if (uidPackageNames == null) {
3671            return true;
3672        }
3673
3674        for (String uidPackageName : uidPackageNames) {
3675            if (ps.name.equals(uidPackageName)) {
3676                return false;
3677            }
3678            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3679            if (uidPs != null) {
3680                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3681                        libEntry.info.getName());
3682                if (index < 0) {
3683                    continue;
3684                }
3685                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3686                    return false;
3687                }
3688            }
3689        }
3690        return true;
3691    }
3692
3693    @Override
3694    public String[] currentToCanonicalPackageNames(String[] names) {
3695        String[] out = new String[names.length];
3696        // reader
3697        synchronized (mPackages) {
3698            for (int i=names.length-1; i>=0; i--) {
3699                PackageSetting ps = mSettings.mPackages.get(names[i]);
3700                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3701            }
3702        }
3703        return out;
3704    }
3705
3706    @Override
3707    public String[] canonicalToCurrentPackageNames(String[] names) {
3708        String[] out = new String[names.length];
3709        // reader
3710        synchronized (mPackages) {
3711            for (int i=names.length-1; i>=0; i--) {
3712                String cur = mSettings.getRenamedPackageLPr(names[i]);
3713                out[i] = cur != null ? cur : names[i];
3714            }
3715        }
3716        return out;
3717    }
3718
3719    @Override
3720    public int getPackageUid(String packageName, int flags, int userId) {
3721        if (!sUserManager.exists(userId)) return -1;
3722        flags = updateFlagsForPackage(flags, userId, packageName);
3723        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3724                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3725
3726        // reader
3727        synchronized (mPackages) {
3728            final PackageParser.Package p = mPackages.get(packageName);
3729            if (p != null && p.isMatch(flags)) {
3730                return UserHandle.getUid(userId, p.applicationInfo.uid);
3731            }
3732            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3733                final PackageSetting ps = mSettings.mPackages.get(packageName);
3734                if (ps != null && ps.isMatch(flags)) {
3735                    return UserHandle.getUid(userId, ps.appId);
3736                }
3737            }
3738        }
3739
3740        return -1;
3741    }
3742
3743    @Override
3744    public int[] getPackageGids(String packageName, int flags, int userId) {
3745        if (!sUserManager.exists(userId)) return null;
3746        flags = updateFlagsForPackage(flags, userId, packageName);
3747        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3748                false /* requireFullPermission */, false /* checkShell */,
3749                "getPackageGids");
3750
3751        // reader
3752        synchronized (mPackages) {
3753            final PackageParser.Package p = mPackages.get(packageName);
3754            if (p != null && p.isMatch(flags)) {
3755                PackageSetting ps = (PackageSetting) p.mExtras;
3756                // TODO: Shouldn't this be checking for package installed state for userId and
3757                // return null?
3758                return ps.getPermissionsState().computeGids(userId);
3759            }
3760            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3761                final PackageSetting ps = mSettings.mPackages.get(packageName);
3762                if (ps != null && ps.isMatch(flags)) {
3763                    return ps.getPermissionsState().computeGids(userId);
3764                }
3765            }
3766        }
3767
3768        return null;
3769    }
3770
3771    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3772        if (bp.perm != null) {
3773            return PackageParser.generatePermissionInfo(bp.perm, flags);
3774        }
3775        PermissionInfo pi = new PermissionInfo();
3776        pi.name = bp.name;
3777        pi.packageName = bp.sourcePackage;
3778        pi.nonLocalizedLabel = bp.name;
3779        pi.protectionLevel = bp.protectionLevel;
3780        return pi;
3781    }
3782
3783    @Override
3784    public PermissionInfo getPermissionInfo(String name, int flags) {
3785        // reader
3786        synchronized (mPackages) {
3787            final BasePermission p = mSettings.mPermissions.get(name);
3788            if (p != null) {
3789                return generatePermissionInfo(p, flags);
3790            }
3791            return null;
3792        }
3793    }
3794
3795    @Override
3796    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3797            int flags) {
3798        // reader
3799        synchronized (mPackages) {
3800            if (group != null && !mPermissionGroups.containsKey(group)) {
3801                // This is thrown as NameNotFoundException
3802                return null;
3803            }
3804
3805            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3806            for (BasePermission p : mSettings.mPermissions.values()) {
3807                if (group == null) {
3808                    if (p.perm == null || p.perm.info.group == null) {
3809                        out.add(generatePermissionInfo(p, flags));
3810                    }
3811                } else {
3812                    if (p.perm != null && group.equals(p.perm.info.group)) {
3813                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3814                    }
3815                }
3816            }
3817            return new ParceledListSlice<>(out);
3818        }
3819    }
3820
3821    @Override
3822    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3823        // reader
3824        synchronized (mPackages) {
3825            return PackageParser.generatePermissionGroupInfo(
3826                    mPermissionGroups.get(name), flags);
3827        }
3828    }
3829
3830    @Override
3831    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3832        // reader
3833        synchronized (mPackages) {
3834            final int N = mPermissionGroups.size();
3835            ArrayList<PermissionGroupInfo> out
3836                    = new ArrayList<PermissionGroupInfo>(N);
3837            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3838                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3839            }
3840            return new ParceledListSlice<>(out);
3841        }
3842    }
3843
3844    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3845            int uid, int userId) {
3846        if (!sUserManager.exists(userId)) return null;
3847        PackageSetting ps = mSettings.mPackages.get(packageName);
3848        if (ps != null) {
3849            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3850                return null;
3851            }
3852            if (ps.pkg == null) {
3853                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3854                if (pInfo != null) {
3855                    return pInfo.applicationInfo;
3856                }
3857                return null;
3858            }
3859            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3860                    ps.readUserState(userId), userId);
3861            if (ai != null) {
3862                rebaseEnabledOverlays(ai, userId);
3863                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3864            }
3865            return ai;
3866        }
3867        return null;
3868    }
3869
3870    @Override
3871    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3872        if (!sUserManager.exists(userId)) return null;
3873        flags = updateFlagsForApplication(flags, userId, packageName);
3874        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3875                false /* requireFullPermission */, false /* checkShell */, "get application info");
3876
3877        // writer
3878        synchronized (mPackages) {
3879            // Normalize package name to handle renamed packages and static libs
3880            packageName = resolveInternalPackageNameLPr(packageName,
3881                    PackageManager.VERSION_CODE_HIGHEST);
3882
3883            PackageParser.Package p = mPackages.get(packageName);
3884            if (DEBUG_PACKAGE_INFO) Log.v(
3885                    TAG, "getApplicationInfo " + packageName
3886                    + ": " + p);
3887            if (p != null) {
3888                PackageSetting ps = mSettings.mPackages.get(packageName);
3889                if (ps == null) return null;
3890                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3891                    return null;
3892                }
3893                // Note: isEnabledLP() does not apply here - always return info
3894                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3895                        p, flags, ps.readUserState(userId), userId);
3896                if (ai != null) {
3897                    rebaseEnabledOverlays(ai, userId);
3898                    ai.packageName = resolveExternalPackageNameLPr(p);
3899                }
3900                return ai;
3901            }
3902            if ("android".equals(packageName)||"system".equals(packageName)) {
3903                return mAndroidApplication;
3904            }
3905            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3906                // Already generates the external package name
3907                return generateApplicationInfoFromSettingsLPw(packageName,
3908                        Binder.getCallingUid(), flags, userId);
3909            }
3910        }
3911        return null;
3912    }
3913
3914    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3915        List<String> paths = new ArrayList<>();
3916        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3917            mEnabledOverlayPaths.get(userId);
3918        if (userSpecificOverlays != null) {
3919            if (!"android".equals(ai.packageName)) {
3920                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3921                if (frameworkOverlays != null) {
3922                    paths.addAll(frameworkOverlays);
3923                }
3924            }
3925
3926            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3927            if (appOverlays != null) {
3928                paths.addAll(appOverlays);
3929            }
3930        }
3931        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3932    }
3933
3934    private String normalizePackageNameLPr(String packageName) {
3935        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3936        return normalizedPackageName != null ? normalizedPackageName : packageName;
3937    }
3938
3939    @Override
3940    public void deletePreloadsFileCache() {
3941        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
3942            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
3943        }
3944        File dir = Environment.getDataPreloadsFileCacheDirectory();
3945        Slog.i(TAG, "Deleting preloaded file cache " + dir);
3946        FileUtils.deleteContents(dir);
3947    }
3948
3949    @Override
3950    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3951            final IPackageDataObserver observer) {
3952        mContext.enforceCallingOrSelfPermission(
3953                android.Manifest.permission.CLEAR_APP_CACHE, null);
3954        mHandler.post(() -> {
3955            boolean success = false;
3956            try {
3957                freeStorage(volumeUuid, freeStorageSize, 0);
3958                success = true;
3959            } catch (IOException e) {
3960                Slog.w(TAG, e);
3961            }
3962            if (observer != null) {
3963                try {
3964                    observer.onRemoveCompleted(null, success);
3965                } catch (RemoteException e) {
3966                    Slog.w(TAG, e);
3967                }
3968            }
3969        });
3970    }
3971
3972    @Override
3973    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3974            final IntentSender pi) {
3975        mContext.enforceCallingOrSelfPermission(
3976                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3977        mHandler.post(() -> {
3978            boolean success = false;
3979            try {
3980                freeStorage(volumeUuid, freeStorageSize, 0);
3981                success = true;
3982            } catch (IOException e) {
3983                Slog.w(TAG, e);
3984            }
3985            if (pi != null) {
3986                try {
3987                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3988                } catch (SendIntentException e) {
3989                    Slog.w(TAG, e);
3990                }
3991            }
3992        });
3993    }
3994
3995    /**
3996     * Blocking call to clear various types of cached data across the system
3997     * until the requested bytes are available.
3998     */
3999    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4000        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4001        final File file = storage.findPathForUuid(volumeUuid);
4002        if (file.getUsableSpace() >= bytes) return;
4003
4004        if (ENABLE_FREE_CACHE_V2) {
4005            final boolean aggressive = (storageFlags
4006                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4007            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4008                    volumeUuid);
4009
4010            // 1. Pre-flight to determine if we have any chance to succeed
4011            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4012            if (internalVolume && (aggressive || SystemProperties
4013                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4014                deletePreloadsFileCache();
4015                if (file.getUsableSpace() >= bytes) return;
4016            }
4017
4018            // 3. Consider parsed APK data (aggressive only)
4019            if (internalVolume && aggressive) {
4020                FileUtils.deleteContents(mCacheDir);
4021                if (file.getUsableSpace() >= bytes) return;
4022            }
4023
4024            // 4. Consider cached app data (above quotas)
4025            try {
4026                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
4027            } catch (InstallerException ignored) {
4028            }
4029            if (file.getUsableSpace() >= bytes) return;
4030
4031            // 5. Consider shared libraries with refcount=0 and age>2h
4032            // 6. Consider dexopt output (aggressive only)
4033            // 7. Consider ephemeral apps not used in last week
4034
4035            // 8. Consider cached app data (below quotas)
4036            try {
4037                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
4038                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4039            } catch (InstallerException ignored) {
4040            }
4041            if (file.getUsableSpace() >= bytes) return;
4042
4043            // 9. Consider DropBox entries
4044            // 10. Consider ephemeral cookies
4045
4046        } else {
4047            try {
4048                mInstaller.freeCache(volumeUuid, bytes, 0);
4049            } catch (InstallerException ignored) {
4050            }
4051            if (file.getUsableSpace() >= bytes) return;
4052        }
4053
4054        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4055    }
4056
4057    /**
4058     * Update given flags based on encryption status of current user.
4059     */
4060    private int updateFlags(int flags, int userId) {
4061        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4062                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4063            // Caller expressed an explicit opinion about what encryption
4064            // aware/unaware components they want to see, so fall through and
4065            // give them what they want
4066        } else {
4067            // Caller expressed no opinion, so match based on user state
4068            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4069                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4070            } else {
4071                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4072            }
4073        }
4074        return flags;
4075    }
4076
4077    private UserManagerInternal getUserManagerInternal() {
4078        if (mUserManagerInternal == null) {
4079            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4080        }
4081        return mUserManagerInternal;
4082    }
4083
4084    private DeviceIdleController.LocalService getDeviceIdleController() {
4085        if (mDeviceIdleController == null) {
4086            mDeviceIdleController =
4087                    LocalServices.getService(DeviceIdleController.LocalService.class);
4088        }
4089        return mDeviceIdleController;
4090    }
4091
4092    /**
4093     * Update given flags when being used to request {@link PackageInfo}.
4094     */
4095    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4096        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4097        boolean triaged = true;
4098        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4099                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4100            // Caller is asking for component details, so they'd better be
4101            // asking for specific encryption matching behavior, or be triaged
4102            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4103                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4104                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4105                triaged = false;
4106            }
4107        }
4108        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4109                | PackageManager.MATCH_SYSTEM_ONLY
4110                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4111            triaged = false;
4112        }
4113        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4114            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4115                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4116                    + Debug.getCallers(5));
4117        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4118                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4119            // If the caller wants all packages and has a restricted profile associated with it,
4120            // then match all users. This is to make sure that launchers that need to access work
4121            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4122            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4123            flags |= PackageManager.MATCH_ANY_USER;
4124        }
4125        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4126            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4127                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4128        }
4129        return updateFlags(flags, userId);
4130    }
4131
4132    /**
4133     * Update given flags when being used to request {@link ApplicationInfo}.
4134     */
4135    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4136        return updateFlagsForPackage(flags, userId, cookie);
4137    }
4138
4139    /**
4140     * Update given flags when being used to request {@link ComponentInfo}.
4141     */
4142    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4143        if (cookie instanceof Intent) {
4144            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4145                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4146            }
4147        }
4148
4149        boolean triaged = true;
4150        // Caller is asking for component details, so they'd better be
4151        // asking for specific encryption matching behavior, or be triaged
4152        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4153                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4154                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4155            triaged = false;
4156        }
4157        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4158            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4159                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4160        }
4161
4162        return updateFlags(flags, userId);
4163    }
4164
4165    /**
4166     * Update given intent when being used to request {@link ResolveInfo}.
4167     */
4168    private Intent updateIntentForResolve(Intent intent) {
4169        if (intent.getSelector() != null) {
4170            intent = intent.getSelector();
4171        }
4172        if (DEBUG_PREFERRED) {
4173            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4174        }
4175        return intent;
4176    }
4177
4178    /**
4179     * Update given flags when being used to request {@link ResolveInfo}.
4180     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4181     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4182     * flag set. However, this flag is only honoured in three circumstances:
4183     * <ul>
4184     * <li>when called from a system process</li>
4185     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4186     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4187     * action and a {@code android.intent.category.BROWSABLE} category</li>
4188     * </ul>
4189     */
4190    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4191        return updateFlagsForResolve(flags, userId, intent, callingUid,
4192                false /*includeInstantApps*/, false /*onlyExposedExplicitly*/);
4193    }
4194    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4195            boolean includeInstantApps) {
4196        return updateFlagsForResolve(flags, userId, intent, callingUid,
4197                includeInstantApps, false /*onlyExposedExplicitly*/);
4198    }
4199    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4200            boolean includeInstantApps, boolean onlyExposedExplicitly) {
4201        // Safe mode means we shouldn't match any third-party components
4202        if (mSafeMode) {
4203            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4204        }
4205        if (getInstantAppPackageName(callingUid) != null) {
4206            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4207            if (onlyExposedExplicitly) {
4208                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4209            }
4210            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4211            flags |= PackageManager.MATCH_INSTANT;
4212        } else {
4213            // Otherwise, prevent leaking ephemeral components
4214            final boolean isSpecialProcess =
4215                    callingUid == Process.SYSTEM_UID
4216                    || callingUid == Process.SHELL_UID
4217                    || callingUid == 0;
4218            final boolean allowMatchInstant =
4219                    (includeInstantApps
4220                            && Intent.ACTION_VIEW.equals(intent.getAction())
4221                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4222                            && hasWebURI(intent))
4223                    || isSpecialProcess
4224                    || mContext.checkCallingOrSelfPermission(
4225                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4226            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4227                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4228            if (!allowMatchInstant) {
4229                flags &= ~PackageManager.MATCH_INSTANT;
4230            }
4231        }
4232        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4233    }
4234
4235    private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state,
4236            int userId) {
4237        ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId);
4238        if (ret != null) {
4239            rebaseEnabledOverlays(ret.applicationInfo, userId);
4240        }
4241        return ret;
4242    }
4243
4244    private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags,
4245            PackageUserState state, int userId) {
4246        ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId);
4247        if (ai != null) {
4248            rebaseEnabledOverlays(ai.applicationInfo, userId);
4249        }
4250        return ai;
4251    }
4252
4253    @Override
4254    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4255        if (!sUserManager.exists(userId)) return null;
4256        flags = updateFlagsForComponent(flags, userId, component);
4257        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4258                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4259        synchronized (mPackages) {
4260            PackageParser.Activity a = mActivities.mActivities.get(component);
4261
4262            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4263            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4264                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4265                if (ps == null) return null;
4266                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4267            }
4268            if (mResolveComponentName.equals(component)) {
4269                return generateActivityInfo(mResolveActivity, flags, new PackageUserState(),
4270                        userId);
4271            }
4272        }
4273        return null;
4274    }
4275
4276    @Override
4277    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4278            String resolvedType) {
4279        synchronized (mPackages) {
4280            if (component.equals(mResolveComponentName)) {
4281                // The resolver supports EVERYTHING!
4282                return true;
4283            }
4284            PackageParser.Activity a = mActivities.mActivities.get(component);
4285            if (a == null) {
4286                return false;
4287            }
4288            for (int i=0; i<a.intents.size(); i++) {
4289                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4290                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4291                    return true;
4292                }
4293            }
4294            return false;
4295        }
4296    }
4297
4298    @Override
4299    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4300        if (!sUserManager.exists(userId)) return null;
4301        flags = updateFlagsForComponent(flags, userId, component);
4302        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4303                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4304        synchronized (mPackages) {
4305            PackageParser.Activity a = mReceivers.mActivities.get(component);
4306            if (DEBUG_PACKAGE_INFO) Log.v(
4307                TAG, "getReceiverInfo " + component + ": " + a);
4308            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4309                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4310                if (ps == null) return null;
4311                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4312            }
4313        }
4314        return null;
4315    }
4316
4317    @Override
4318    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4319        if (!sUserManager.exists(userId)) return null;
4320        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4321
4322        flags = updateFlagsForPackage(flags, userId, null);
4323
4324        final boolean canSeeStaticLibraries =
4325                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4326                        == PERMISSION_GRANTED
4327                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4328                        == PERMISSION_GRANTED
4329                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4330                        == PERMISSION_GRANTED
4331                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4332                        == PERMISSION_GRANTED;
4333
4334        synchronized (mPackages) {
4335            List<SharedLibraryInfo> result = null;
4336
4337            final int libCount = mSharedLibraries.size();
4338            for (int i = 0; i < libCount; i++) {
4339                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4340                if (versionedLib == null) {
4341                    continue;
4342                }
4343
4344                final int versionCount = versionedLib.size();
4345                for (int j = 0; j < versionCount; j++) {
4346                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4347                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4348                        break;
4349                    }
4350                    final long identity = Binder.clearCallingIdentity();
4351                    try {
4352                        // TODO: We will change version code to long, so in the new API it is long
4353                        PackageInfo packageInfo = getPackageInfoVersioned(
4354                                libInfo.getDeclaringPackage(), flags, userId);
4355                        if (packageInfo == null) {
4356                            continue;
4357                        }
4358                    } finally {
4359                        Binder.restoreCallingIdentity(identity);
4360                    }
4361
4362                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4363                            libInfo.getVersion(), libInfo.getType(),
4364                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4365                            flags, userId));
4366
4367                    if (result == null) {
4368                        result = new ArrayList<>();
4369                    }
4370                    result.add(resLibInfo);
4371                }
4372            }
4373
4374            return result != null ? new ParceledListSlice<>(result) : null;
4375        }
4376    }
4377
4378    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4379            SharedLibraryInfo libInfo, int flags, int userId) {
4380        List<VersionedPackage> versionedPackages = null;
4381        final int packageCount = mSettings.mPackages.size();
4382        for (int i = 0; i < packageCount; i++) {
4383            PackageSetting ps = mSettings.mPackages.valueAt(i);
4384
4385            if (ps == null) {
4386                continue;
4387            }
4388
4389            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4390                continue;
4391            }
4392
4393            final String libName = libInfo.getName();
4394            if (libInfo.isStatic()) {
4395                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4396                if (libIdx < 0) {
4397                    continue;
4398                }
4399                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4400                    continue;
4401                }
4402                if (versionedPackages == null) {
4403                    versionedPackages = new ArrayList<>();
4404                }
4405                // If the dependent is a static shared lib, use the public package name
4406                String dependentPackageName = ps.name;
4407                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4408                    dependentPackageName = ps.pkg.manifestPackageName;
4409                }
4410                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4411            } else if (ps.pkg != null) {
4412                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4413                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4414                    if (versionedPackages == null) {
4415                        versionedPackages = new ArrayList<>();
4416                    }
4417                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4418                }
4419            }
4420        }
4421
4422        return versionedPackages;
4423    }
4424
4425    @Override
4426    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4427        if (!sUserManager.exists(userId)) return null;
4428        flags = updateFlagsForComponent(flags, userId, component);
4429        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4430                false /* requireFullPermission */, false /* checkShell */, "get service info");
4431        synchronized (mPackages) {
4432            PackageParser.Service s = mServices.mServices.get(component);
4433            if (DEBUG_PACKAGE_INFO) Log.v(
4434                TAG, "getServiceInfo " + component + ": " + s);
4435            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4436                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4437                if (ps == null) return null;
4438                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4439                        ps.readUserState(userId), userId);
4440                if (si != null) {
4441                    rebaseEnabledOverlays(si.applicationInfo, userId);
4442                }
4443                return si;
4444            }
4445        }
4446        return null;
4447    }
4448
4449    @Override
4450    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4451        if (!sUserManager.exists(userId)) return null;
4452        flags = updateFlagsForComponent(flags, userId, component);
4453        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4454                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4455        synchronized (mPackages) {
4456            PackageParser.Provider p = mProviders.mProviders.get(component);
4457            if (DEBUG_PACKAGE_INFO) Log.v(
4458                TAG, "getProviderInfo " + component + ": " + p);
4459            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4460                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4461                if (ps == null) return null;
4462                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4463                        ps.readUserState(userId), userId);
4464                if (pi != null) {
4465                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4466                }
4467                return pi;
4468            }
4469        }
4470        return null;
4471    }
4472
4473    @Override
4474    public String[] getSystemSharedLibraryNames() {
4475        synchronized (mPackages) {
4476            Set<String> libs = null;
4477            final int libCount = mSharedLibraries.size();
4478            for (int i = 0; i < libCount; i++) {
4479                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4480                if (versionedLib == null) {
4481                    continue;
4482                }
4483                final int versionCount = versionedLib.size();
4484                for (int j = 0; j < versionCount; j++) {
4485                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4486                    if (!libEntry.info.isStatic()) {
4487                        if (libs == null) {
4488                            libs = new ArraySet<>();
4489                        }
4490                        libs.add(libEntry.info.getName());
4491                        break;
4492                    }
4493                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4494                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4495                            UserHandle.getUserId(Binder.getCallingUid()))) {
4496                        if (libs == null) {
4497                            libs = new ArraySet<>();
4498                        }
4499                        libs.add(libEntry.info.getName());
4500                        break;
4501                    }
4502                }
4503            }
4504
4505            if (libs != null) {
4506                String[] libsArray = new String[libs.size()];
4507                libs.toArray(libsArray);
4508                return libsArray;
4509            }
4510
4511            return null;
4512        }
4513    }
4514
4515    @Override
4516    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4517        synchronized (mPackages) {
4518            return mServicesSystemSharedLibraryPackageName;
4519        }
4520    }
4521
4522    @Override
4523    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4524        synchronized (mPackages) {
4525            return mSharedSystemSharedLibraryPackageName;
4526        }
4527    }
4528
4529    private void updateSequenceNumberLP(String packageName, int[] userList) {
4530        for (int i = userList.length - 1; i >= 0; --i) {
4531            final int userId = userList[i];
4532            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4533            if (changedPackages == null) {
4534                changedPackages = new SparseArray<>();
4535                mChangedPackages.put(userId, changedPackages);
4536            }
4537            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4538            if (sequenceNumbers == null) {
4539                sequenceNumbers = new HashMap<>();
4540                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4541            }
4542            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4543            if (sequenceNumber != null) {
4544                changedPackages.remove(sequenceNumber);
4545            }
4546            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4547            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4548        }
4549        mChangedPackagesSequenceNumber++;
4550    }
4551
4552    @Override
4553    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4554        synchronized (mPackages) {
4555            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4556                return null;
4557            }
4558            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4559            if (changedPackages == null) {
4560                return null;
4561            }
4562            final List<String> packageNames =
4563                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4564            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4565                final String packageName = changedPackages.get(i);
4566                if (packageName != null) {
4567                    packageNames.add(packageName);
4568                }
4569            }
4570            return packageNames.isEmpty()
4571                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4572        }
4573    }
4574
4575    @Override
4576    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4577        ArrayList<FeatureInfo> res;
4578        synchronized (mAvailableFeatures) {
4579            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4580            res.addAll(mAvailableFeatures.values());
4581        }
4582        final FeatureInfo fi = new FeatureInfo();
4583        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4584                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4585        res.add(fi);
4586
4587        return new ParceledListSlice<>(res);
4588    }
4589
4590    @Override
4591    public boolean hasSystemFeature(String name, int version) {
4592        synchronized (mAvailableFeatures) {
4593            final FeatureInfo feat = mAvailableFeatures.get(name);
4594            if (feat == null) {
4595                return false;
4596            } else {
4597                return feat.version >= version;
4598            }
4599        }
4600    }
4601
4602    @Override
4603    public int checkPermission(String permName, String pkgName, int userId) {
4604        if (!sUserManager.exists(userId)) {
4605            return PackageManager.PERMISSION_DENIED;
4606        }
4607
4608        synchronized (mPackages) {
4609            final PackageParser.Package p = mPackages.get(pkgName);
4610            if (p != null && p.mExtras != null) {
4611                final PackageSetting ps = (PackageSetting) p.mExtras;
4612                final PermissionsState permissionsState = ps.getPermissionsState();
4613                if (permissionsState.hasPermission(permName, userId)) {
4614                    return PackageManager.PERMISSION_GRANTED;
4615                }
4616                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4617                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4618                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4619                    return PackageManager.PERMISSION_GRANTED;
4620                }
4621            }
4622        }
4623
4624        return PackageManager.PERMISSION_DENIED;
4625    }
4626
4627    @Override
4628    public int checkUidPermission(String permName, int uid) {
4629        final int userId = UserHandle.getUserId(uid);
4630
4631        if (!sUserManager.exists(userId)) {
4632            return PackageManager.PERMISSION_DENIED;
4633        }
4634
4635        synchronized (mPackages) {
4636            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4637            if (obj != null) {
4638                final SettingBase ps = (SettingBase) obj;
4639                final PermissionsState permissionsState = ps.getPermissionsState();
4640                if (permissionsState.hasPermission(permName, userId)) {
4641                    return PackageManager.PERMISSION_GRANTED;
4642                }
4643                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4644                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4645                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4646                    return PackageManager.PERMISSION_GRANTED;
4647                }
4648            } else {
4649                ArraySet<String> perms = mSystemPermissions.get(uid);
4650                if (perms != null) {
4651                    if (perms.contains(permName)) {
4652                        return PackageManager.PERMISSION_GRANTED;
4653                    }
4654                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4655                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4656                        return PackageManager.PERMISSION_GRANTED;
4657                    }
4658                }
4659            }
4660        }
4661
4662        return PackageManager.PERMISSION_DENIED;
4663    }
4664
4665    @Override
4666    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4667        if (UserHandle.getCallingUserId() != userId) {
4668            mContext.enforceCallingPermission(
4669                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4670                    "isPermissionRevokedByPolicy for user " + userId);
4671        }
4672
4673        if (checkPermission(permission, packageName, userId)
4674                == PackageManager.PERMISSION_GRANTED) {
4675            return false;
4676        }
4677
4678        final long identity = Binder.clearCallingIdentity();
4679        try {
4680            final int flags = getPermissionFlags(permission, packageName, userId);
4681            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4682        } finally {
4683            Binder.restoreCallingIdentity(identity);
4684        }
4685    }
4686
4687    @Override
4688    public String getPermissionControllerPackageName() {
4689        synchronized (mPackages) {
4690            return mRequiredInstallerPackage;
4691        }
4692    }
4693
4694    /**
4695     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4696     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4697     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4698     * @param message the message to log on security exception
4699     */
4700    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4701            boolean checkShell, String message) {
4702        if (userId < 0) {
4703            throw new IllegalArgumentException("Invalid userId " + userId);
4704        }
4705        if (checkShell) {
4706            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4707        }
4708        if (userId == UserHandle.getUserId(callingUid)) return;
4709        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4710            if (requireFullPermission) {
4711                mContext.enforceCallingOrSelfPermission(
4712                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4713            } else {
4714                try {
4715                    mContext.enforceCallingOrSelfPermission(
4716                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4717                } catch (SecurityException se) {
4718                    mContext.enforceCallingOrSelfPermission(
4719                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4720                }
4721            }
4722        }
4723    }
4724
4725    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4726        if (callingUid == Process.SHELL_UID) {
4727            if (userHandle >= 0
4728                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4729                throw new SecurityException("Shell does not have permission to access user "
4730                        + userHandle);
4731            } else if (userHandle < 0) {
4732                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4733                        + Debug.getCallers(3));
4734            }
4735        }
4736    }
4737
4738    private BasePermission findPermissionTreeLP(String permName) {
4739        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4740            if (permName.startsWith(bp.name) &&
4741                    permName.length() > bp.name.length() &&
4742                    permName.charAt(bp.name.length()) == '.') {
4743                return bp;
4744            }
4745        }
4746        return null;
4747    }
4748
4749    private BasePermission checkPermissionTreeLP(String permName) {
4750        if (permName != null) {
4751            BasePermission bp = findPermissionTreeLP(permName);
4752            if (bp != null) {
4753                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4754                    return bp;
4755                }
4756                throw new SecurityException("Calling uid "
4757                        + Binder.getCallingUid()
4758                        + " is not allowed to add to permission tree "
4759                        + bp.name + " owned by uid " + bp.uid);
4760            }
4761        }
4762        throw new SecurityException("No permission tree found for " + permName);
4763    }
4764
4765    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4766        if (s1 == null) {
4767            return s2 == null;
4768        }
4769        if (s2 == null) {
4770            return false;
4771        }
4772        if (s1.getClass() != s2.getClass()) {
4773            return false;
4774        }
4775        return s1.equals(s2);
4776    }
4777
4778    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4779        if (pi1.icon != pi2.icon) return false;
4780        if (pi1.logo != pi2.logo) return false;
4781        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4782        if (!compareStrings(pi1.name, pi2.name)) return false;
4783        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4784        // We'll take care of setting this one.
4785        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4786        // These are not currently stored in settings.
4787        //if (!compareStrings(pi1.group, pi2.group)) return false;
4788        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4789        //if (pi1.labelRes != pi2.labelRes) return false;
4790        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4791        return true;
4792    }
4793
4794    int permissionInfoFootprint(PermissionInfo info) {
4795        int size = info.name.length();
4796        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4797        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4798        return size;
4799    }
4800
4801    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4802        int size = 0;
4803        for (BasePermission perm : mSettings.mPermissions.values()) {
4804            if (perm.uid == tree.uid) {
4805                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4806            }
4807        }
4808        return size;
4809    }
4810
4811    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4812        // We calculate the max size of permissions defined by this uid and throw
4813        // if that plus the size of 'info' would exceed our stated maximum.
4814        if (tree.uid != Process.SYSTEM_UID) {
4815            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4816            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4817                throw new SecurityException("Permission tree size cap exceeded");
4818            }
4819        }
4820    }
4821
4822    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4823        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4824            throw new SecurityException("Label must be specified in permission");
4825        }
4826        BasePermission tree = checkPermissionTreeLP(info.name);
4827        BasePermission bp = mSettings.mPermissions.get(info.name);
4828        boolean added = bp == null;
4829        boolean changed = true;
4830        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4831        if (added) {
4832            enforcePermissionCapLocked(info, tree);
4833            bp = new BasePermission(info.name, tree.sourcePackage,
4834                    BasePermission.TYPE_DYNAMIC);
4835        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4836            throw new SecurityException(
4837                    "Not allowed to modify non-dynamic permission "
4838                    + info.name);
4839        } else {
4840            if (bp.protectionLevel == fixedLevel
4841                    && bp.perm.owner.equals(tree.perm.owner)
4842                    && bp.uid == tree.uid
4843                    && comparePermissionInfos(bp.perm.info, info)) {
4844                changed = false;
4845            }
4846        }
4847        bp.protectionLevel = fixedLevel;
4848        info = new PermissionInfo(info);
4849        info.protectionLevel = fixedLevel;
4850        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4851        bp.perm.info.packageName = tree.perm.info.packageName;
4852        bp.uid = tree.uid;
4853        if (added) {
4854            mSettings.mPermissions.put(info.name, bp);
4855        }
4856        if (changed) {
4857            if (!async) {
4858                mSettings.writeLPr();
4859            } else {
4860                scheduleWriteSettingsLocked();
4861            }
4862        }
4863        return added;
4864    }
4865
4866    @Override
4867    public boolean addPermission(PermissionInfo info) {
4868        synchronized (mPackages) {
4869            return addPermissionLocked(info, false);
4870        }
4871    }
4872
4873    @Override
4874    public boolean addPermissionAsync(PermissionInfo info) {
4875        synchronized (mPackages) {
4876            return addPermissionLocked(info, true);
4877        }
4878    }
4879
4880    @Override
4881    public void removePermission(String name) {
4882        synchronized (mPackages) {
4883            checkPermissionTreeLP(name);
4884            BasePermission bp = mSettings.mPermissions.get(name);
4885            if (bp != null) {
4886                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4887                    throw new SecurityException(
4888                            "Not allowed to modify non-dynamic permission "
4889                            + name);
4890                }
4891                mSettings.mPermissions.remove(name);
4892                mSettings.writeLPr();
4893            }
4894        }
4895    }
4896
4897    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4898            BasePermission bp) {
4899        int index = pkg.requestedPermissions.indexOf(bp.name);
4900        if (index == -1) {
4901            throw new SecurityException("Package " + pkg.packageName
4902                    + " has not requested permission " + bp.name);
4903        }
4904        if (!bp.isRuntime() && !bp.isDevelopment()) {
4905            throw new SecurityException("Permission " + bp.name
4906                    + " is not a changeable permission type");
4907        }
4908    }
4909
4910    @Override
4911    public void grantRuntimePermission(String packageName, String name, final int userId) {
4912        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4913    }
4914
4915    private void grantRuntimePermission(String packageName, String name, final int userId,
4916            boolean overridePolicy) {
4917        if (!sUserManager.exists(userId)) {
4918            Log.e(TAG, "No such user:" + userId);
4919            return;
4920        }
4921
4922        mContext.enforceCallingOrSelfPermission(
4923                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4924                "grantRuntimePermission");
4925
4926        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4927                true /* requireFullPermission */, true /* checkShell */,
4928                "grantRuntimePermission");
4929
4930        final int uid;
4931        final SettingBase sb;
4932
4933        synchronized (mPackages) {
4934            final PackageParser.Package pkg = mPackages.get(packageName);
4935            if (pkg == null) {
4936                throw new IllegalArgumentException("Unknown package: " + packageName);
4937            }
4938
4939            final BasePermission bp = mSettings.mPermissions.get(name);
4940            if (bp == null) {
4941                throw new IllegalArgumentException("Unknown permission: " + name);
4942            }
4943
4944            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4945
4946            // If a permission review is required for legacy apps we represent
4947            // their permissions as always granted runtime ones since we need
4948            // to keep the review required permission flag per user while an
4949            // install permission's state is shared across all users.
4950            if (mPermissionReviewRequired
4951                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4952                    && bp.isRuntime()) {
4953                return;
4954            }
4955
4956            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4957            sb = (SettingBase) pkg.mExtras;
4958            if (sb == null) {
4959                throw new IllegalArgumentException("Unknown package: " + packageName);
4960            }
4961
4962            final PermissionsState permissionsState = sb.getPermissionsState();
4963
4964            final int flags = permissionsState.getPermissionFlags(name, userId);
4965            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4966                throw new SecurityException("Cannot grant system fixed permission "
4967                        + name + " for package " + packageName);
4968            }
4969            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4970                throw new SecurityException("Cannot grant policy fixed permission "
4971                        + name + " for package " + packageName);
4972            }
4973
4974            if (bp.isDevelopment()) {
4975                // Development permissions must be handled specially, since they are not
4976                // normal runtime permissions.  For now they apply to all users.
4977                if (permissionsState.grantInstallPermission(bp) !=
4978                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4979                    scheduleWriteSettingsLocked();
4980                }
4981                return;
4982            }
4983
4984            final PackageSetting ps = mSettings.mPackages.get(packageName);
4985            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4986                throw new SecurityException("Cannot grant non-ephemeral permission"
4987                        + name + " for package " + packageName);
4988            }
4989
4990            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4991                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4992                return;
4993            }
4994
4995            final int result = permissionsState.grantRuntimePermission(bp, userId);
4996            switch (result) {
4997                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4998                    return;
4999                }
5000
5001                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5002                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5003                    mHandler.post(new Runnable() {
5004                        @Override
5005                        public void run() {
5006                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5007                        }
5008                    });
5009                }
5010                break;
5011            }
5012
5013            if (bp.isRuntime()) {
5014                logPermissionGranted(mContext, name, packageName);
5015            }
5016
5017            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5018
5019            // Not critical if that is lost - app has to request again.
5020            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5021        }
5022
5023        // Only need to do this if user is initialized. Otherwise it's a new user
5024        // and there are no processes running as the user yet and there's no need
5025        // to make an expensive call to remount processes for the changed permissions.
5026        if (READ_EXTERNAL_STORAGE.equals(name)
5027                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5028            final long token = Binder.clearCallingIdentity();
5029            try {
5030                if (sUserManager.isInitialized(userId)) {
5031                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5032                            StorageManagerInternal.class);
5033                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5034                }
5035            } finally {
5036                Binder.restoreCallingIdentity(token);
5037            }
5038        }
5039    }
5040
5041    @Override
5042    public void revokeRuntimePermission(String packageName, String name, int userId) {
5043        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5044    }
5045
5046    private void revokeRuntimePermission(String packageName, String name, int userId,
5047            boolean overridePolicy) {
5048        if (!sUserManager.exists(userId)) {
5049            Log.e(TAG, "No such user:" + userId);
5050            return;
5051        }
5052
5053        mContext.enforceCallingOrSelfPermission(
5054                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5055                "revokeRuntimePermission");
5056
5057        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5058                true /* requireFullPermission */, true /* checkShell */,
5059                "revokeRuntimePermission");
5060
5061        final int appId;
5062
5063        synchronized (mPackages) {
5064            final PackageParser.Package pkg = mPackages.get(packageName);
5065            if (pkg == null) {
5066                throw new IllegalArgumentException("Unknown package: " + packageName);
5067            }
5068
5069            final BasePermission bp = mSettings.mPermissions.get(name);
5070            if (bp == null) {
5071                throw new IllegalArgumentException("Unknown permission: " + name);
5072            }
5073
5074            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5075
5076            // If a permission review is required for legacy apps we represent
5077            // their permissions as always granted runtime ones since we need
5078            // to keep the review required permission flag per user while an
5079            // install permission's state is shared across all users.
5080            if (mPermissionReviewRequired
5081                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5082                    && bp.isRuntime()) {
5083                return;
5084            }
5085
5086            SettingBase sb = (SettingBase) pkg.mExtras;
5087            if (sb == null) {
5088                throw new IllegalArgumentException("Unknown package: " + packageName);
5089            }
5090
5091            final PermissionsState permissionsState = sb.getPermissionsState();
5092
5093            final int flags = permissionsState.getPermissionFlags(name, userId);
5094            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5095                throw new SecurityException("Cannot revoke system fixed permission "
5096                        + name + " for package " + packageName);
5097            }
5098            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5099                throw new SecurityException("Cannot revoke policy fixed permission "
5100                        + name + " for package " + packageName);
5101            }
5102
5103            if (bp.isDevelopment()) {
5104                // Development permissions must be handled specially, since they are not
5105                // normal runtime permissions.  For now they apply to all users.
5106                if (permissionsState.revokeInstallPermission(bp) !=
5107                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5108                    scheduleWriteSettingsLocked();
5109                }
5110                return;
5111            }
5112
5113            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5114                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5115                return;
5116            }
5117
5118            if (bp.isRuntime()) {
5119                logPermissionRevoked(mContext, name, packageName);
5120            }
5121
5122            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5123
5124            // Critical, after this call app should never have the permission.
5125            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5126
5127            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5128        }
5129
5130        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5131    }
5132
5133    /**
5134     * Get the first event id for the permission.
5135     *
5136     * <p>There are four events for each permission: <ul>
5137     *     <li>Request permission: first id + 0</li>
5138     *     <li>Grant permission: first id + 1</li>
5139     *     <li>Request for permission denied: first id + 2</li>
5140     *     <li>Revoke permission: first id + 3</li>
5141     * </ul></p>
5142     *
5143     * @param name name of the permission
5144     *
5145     * @return The first event id for the permission
5146     */
5147    private static int getBaseEventId(@NonNull String name) {
5148        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5149
5150        if (eventIdIndex == -1) {
5151            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5152                    || "user".equals(Build.TYPE)) {
5153                Log.i(TAG, "Unknown permission " + name);
5154
5155                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5156            } else {
5157                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5158                //
5159                // Also update
5160                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5161                // - metrics_constants.proto
5162                throw new IllegalStateException("Unknown permission " + name);
5163            }
5164        }
5165
5166        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5167    }
5168
5169    /**
5170     * Log that a permission was revoked.
5171     *
5172     * @param context Context of the caller
5173     * @param name name of the permission
5174     * @param packageName package permission if for
5175     */
5176    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5177            @NonNull String packageName) {
5178        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5179    }
5180
5181    /**
5182     * Log that a permission request was granted.
5183     *
5184     * @param context Context of the caller
5185     * @param name name of the permission
5186     * @param packageName package permission if for
5187     */
5188    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5189            @NonNull String packageName) {
5190        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5191    }
5192
5193    @Override
5194    public void resetRuntimePermissions() {
5195        mContext.enforceCallingOrSelfPermission(
5196                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5197                "revokeRuntimePermission");
5198
5199        int callingUid = Binder.getCallingUid();
5200        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5201            mContext.enforceCallingOrSelfPermission(
5202                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5203                    "resetRuntimePermissions");
5204        }
5205
5206        synchronized (mPackages) {
5207            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5208            for (int userId : UserManagerService.getInstance().getUserIds()) {
5209                final int packageCount = mPackages.size();
5210                for (int i = 0; i < packageCount; i++) {
5211                    PackageParser.Package pkg = mPackages.valueAt(i);
5212                    if (!(pkg.mExtras instanceof PackageSetting)) {
5213                        continue;
5214                    }
5215                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5216                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5217                }
5218            }
5219        }
5220    }
5221
5222    @Override
5223    public int getPermissionFlags(String name, String packageName, int userId) {
5224        if (!sUserManager.exists(userId)) {
5225            return 0;
5226        }
5227
5228        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5229
5230        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5231                true /* requireFullPermission */, false /* checkShell */,
5232                "getPermissionFlags");
5233
5234        synchronized (mPackages) {
5235            final PackageParser.Package pkg = mPackages.get(packageName);
5236            if (pkg == null) {
5237                return 0;
5238            }
5239
5240            final BasePermission bp = mSettings.mPermissions.get(name);
5241            if (bp == null) {
5242                return 0;
5243            }
5244
5245            SettingBase sb = (SettingBase) pkg.mExtras;
5246            if (sb == null) {
5247                return 0;
5248            }
5249
5250            PermissionsState permissionsState = sb.getPermissionsState();
5251            return permissionsState.getPermissionFlags(name, userId);
5252        }
5253    }
5254
5255    @Override
5256    public void updatePermissionFlags(String name, String packageName, int flagMask,
5257            int flagValues, int userId) {
5258        if (!sUserManager.exists(userId)) {
5259            return;
5260        }
5261
5262        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5263
5264        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5265                true /* requireFullPermission */, true /* checkShell */,
5266                "updatePermissionFlags");
5267
5268        // Only the system can change these flags and nothing else.
5269        if (getCallingUid() != Process.SYSTEM_UID) {
5270            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5271            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5272            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5273            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5274            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5275        }
5276
5277        synchronized (mPackages) {
5278            final PackageParser.Package pkg = mPackages.get(packageName);
5279            if (pkg == null) {
5280                throw new IllegalArgumentException("Unknown package: " + packageName);
5281            }
5282
5283            final BasePermission bp = mSettings.mPermissions.get(name);
5284            if (bp == null) {
5285                throw new IllegalArgumentException("Unknown permission: " + name);
5286            }
5287
5288            SettingBase sb = (SettingBase) pkg.mExtras;
5289            if (sb == null) {
5290                throw new IllegalArgumentException("Unknown package: " + packageName);
5291            }
5292
5293            PermissionsState permissionsState = sb.getPermissionsState();
5294
5295            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5296
5297            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5298                // Install and runtime permissions are stored in different places,
5299                // so figure out what permission changed and persist the change.
5300                if (permissionsState.getInstallPermissionState(name) != null) {
5301                    scheduleWriteSettingsLocked();
5302                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5303                        || hadState) {
5304                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5305                }
5306            }
5307        }
5308    }
5309
5310    /**
5311     * Update the permission flags for all packages and runtime permissions of a user in order
5312     * to allow device or profile owner to remove POLICY_FIXED.
5313     */
5314    @Override
5315    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5316        if (!sUserManager.exists(userId)) {
5317            return;
5318        }
5319
5320        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5321
5322        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5323                true /* requireFullPermission */, true /* checkShell */,
5324                "updatePermissionFlagsForAllApps");
5325
5326        // Only the system can change system fixed flags.
5327        if (getCallingUid() != Process.SYSTEM_UID) {
5328            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5329            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5330        }
5331
5332        synchronized (mPackages) {
5333            boolean changed = false;
5334            final int packageCount = mPackages.size();
5335            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5336                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5337                SettingBase sb = (SettingBase) pkg.mExtras;
5338                if (sb == null) {
5339                    continue;
5340                }
5341                PermissionsState permissionsState = sb.getPermissionsState();
5342                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5343                        userId, flagMask, flagValues);
5344            }
5345            if (changed) {
5346                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5347            }
5348        }
5349    }
5350
5351    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5352        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5353                != PackageManager.PERMISSION_GRANTED
5354            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5355                != PackageManager.PERMISSION_GRANTED) {
5356            throw new SecurityException(message + " requires "
5357                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5358                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5359        }
5360    }
5361
5362    @Override
5363    public boolean shouldShowRequestPermissionRationale(String permissionName,
5364            String packageName, int userId) {
5365        if (UserHandle.getCallingUserId() != userId) {
5366            mContext.enforceCallingPermission(
5367                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5368                    "canShowRequestPermissionRationale for user " + userId);
5369        }
5370
5371        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5372        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5373            return false;
5374        }
5375
5376        if (checkPermission(permissionName, packageName, userId)
5377                == PackageManager.PERMISSION_GRANTED) {
5378            return false;
5379        }
5380
5381        final int flags;
5382
5383        final long identity = Binder.clearCallingIdentity();
5384        try {
5385            flags = getPermissionFlags(permissionName,
5386                    packageName, userId);
5387        } finally {
5388            Binder.restoreCallingIdentity(identity);
5389        }
5390
5391        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5392                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5393                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5394
5395        if ((flags & fixedFlags) != 0) {
5396            return false;
5397        }
5398
5399        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5400    }
5401
5402    @Override
5403    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5404        mContext.enforceCallingOrSelfPermission(
5405                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5406                "addOnPermissionsChangeListener");
5407
5408        synchronized (mPackages) {
5409            mOnPermissionChangeListeners.addListenerLocked(listener);
5410        }
5411    }
5412
5413    @Override
5414    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5415        synchronized (mPackages) {
5416            mOnPermissionChangeListeners.removeListenerLocked(listener);
5417        }
5418    }
5419
5420    @Override
5421    public boolean isProtectedBroadcast(String actionName) {
5422        synchronized (mPackages) {
5423            if (mProtectedBroadcasts.contains(actionName)) {
5424                return true;
5425            } else if (actionName != null) {
5426                // TODO: remove these terrible hacks
5427                if (actionName.startsWith("android.net.netmon.lingerExpired")
5428                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5429                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5430                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5431                    return true;
5432                }
5433            }
5434        }
5435        return false;
5436    }
5437
5438    @Override
5439    public int checkSignatures(String pkg1, String pkg2) {
5440        synchronized (mPackages) {
5441            final PackageParser.Package p1 = mPackages.get(pkg1);
5442            final PackageParser.Package p2 = mPackages.get(pkg2);
5443            if (p1 == null || p1.mExtras == null
5444                    || p2 == null || p2.mExtras == null) {
5445                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5446            }
5447            return compareSignatures(p1.mSignatures, p2.mSignatures);
5448        }
5449    }
5450
5451    @Override
5452    public int checkUidSignatures(int uid1, int uid2) {
5453        // Map to base uids.
5454        uid1 = UserHandle.getAppId(uid1);
5455        uid2 = UserHandle.getAppId(uid2);
5456        // reader
5457        synchronized (mPackages) {
5458            Signature[] s1;
5459            Signature[] s2;
5460            Object obj = mSettings.getUserIdLPr(uid1);
5461            if (obj != null) {
5462                if (obj instanceof SharedUserSetting) {
5463                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5464                } else if (obj instanceof PackageSetting) {
5465                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5466                } else {
5467                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5468                }
5469            } else {
5470                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5471            }
5472            obj = mSettings.getUserIdLPr(uid2);
5473            if (obj != null) {
5474                if (obj instanceof SharedUserSetting) {
5475                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5476                } else if (obj instanceof PackageSetting) {
5477                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5478                } else {
5479                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5480                }
5481            } else {
5482                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5483            }
5484            return compareSignatures(s1, s2);
5485        }
5486    }
5487
5488    /**
5489     * This method should typically only be used when granting or revoking
5490     * permissions, since the app may immediately restart after this call.
5491     * <p>
5492     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5493     * guard your work against the app being relaunched.
5494     */
5495    private void killUid(int appId, int userId, String reason) {
5496        final long identity = Binder.clearCallingIdentity();
5497        try {
5498            IActivityManager am = ActivityManager.getService();
5499            if (am != null) {
5500                try {
5501                    am.killUid(appId, userId, reason);
5502                } catch (RemoteException e) {
5503                    /* ignore - same process */
5504                }
5505            }
5506        } finally {
5507            Binder.restoreCallingIdentity(identity);
5508        }
5509    }
5510
5511    /**
5512     * Compares two sets of signatures. Returns:
5513     * <br />
5514     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5515     * <br />
5516     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5517     * <br />
5518     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5519     * <br />
5520     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5521     * <br />
5522     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5523     */
5524    static int compareSignatures(Signature[] s1, Signature[] s2) {
5525        if (s1 == null) {
5526            return s2 == null
5527                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5528                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5529        }
5530
5531        if (s2 == null) {
5532            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5533        }
5534
5535        if (s1.length != s2.length) {
5536            return PackageManager.SIGNATURE_NO_MATCH;
5537        }
5538
5539        // Since both signature sets are of size 1, we can compare without HashSets.
5540        if (s1.length == 1) {
5541            return s1[0].equals(s2[0]) ?
5542                    PackageManager.SIGNATURE_MATCH :
5543                    PackageManager.SIGNATURE_NO_MATCH;
5544        }
5545
5546        ArraySet<Signature> set1 = new ArraySet<Signature>();
5547        for (Signature sig : s1) {
5548            set1.add(sig);
5549        }
5550        ArraySet<Signature> set2 = new ArraySet<Signature>();
5551        for (Signature sig : s2) {
5552            set2.add(sig);
5553        }
5554        // Make sure s2 contains all signatures in s1.
5555        if (set1.equals(set2)) {
5556            return PackageManager.SIGNATURE_MATCH;
5557        }
5558        return PackageManager.SIGNATURE_NO_MATCH;
5559    }
5560
5561    /**
5562     * If the database version for this type of package (internal storage or
5563     * external storage) is less than the version where package signatures
5564     * were updated, return true.
5565     */
5566    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5567        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5568        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5569    }
5570
5571    /**
5572     * Used for backward compatibility to make sure any packages with
5573     * certificate chains get upgraded to the new style. {@code existingSigs}
5574     * will be in the old format (since they were stored on disk from before the
5575     * system upgrade) and {@code scannedSigs} will be in the newer format.
5576     */
5577    private int compareSignaturesCompat(PackageSignatures existingSigs,
5578            PackageParser.Package scannedPkg) {
5579        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5580            return PackageManager.SIGNATURE_NO_MATCH;
5581        }
5582
5583        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5584        for (Signature sig : existingSigs.mSignatures) {
5585            existingSet.add(sig);
5586        }
5587        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5588        for (Signature sig : scannedPkg.mSignatures) {
5589            try {
5590                Signature[] chainSignatures = sig.getChainSignatures();
5591                for (Signature chainSig : chainSignatures) {
5592                    scannedCompatSet.add(chainSig);
5593                }
5594            } catch (CertificateEncodingException e) {
5595                scannedCompatSet.add(sig);
5596            }
5597        }
5598        /*
5599         * Make sure the expanded scanned set contains all signatures in the
5600         * existing one.
5601         */
5602        if (scannedCompatSet.equals(existingSet)) {
5603            // Migrate the old signatures to the new scheme.
5604            existingSigs.assignSignatures(scannedPkg.mSignatures);
5605            // The new KeySets will be re-added later in the scanning process.
5606            synchronized (mPackages) {
5607                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5608            }
5609            return PackageManager.SIGNATURE_MATCH;
5610        }
5611        return PackageManager.SIGNATURE_NO_MATCH;
5612    }
5613
5614    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5615        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5616        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5617    }
5618
5619    private int compareSignaturesRecover(PackageSignatures existingSigs,
5620            PackageParser.Package scannedPkg) {
5621        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5622            return PackageManager.SIGNATURE_NO_MATCH;
5623        }
5624
5625        String msg = null;
5626        try {
5627            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5628                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5629                        + scannedPkg.packageName);
5630                return PackageManager.SIGNATURE_MATCH;
5631            }
5632        } catch (CertificateException e) {
5633            msg = e.getMessage();
5634        }
5635
5636        logCriticalInfo(Log.INFO,
5637                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5638        return PackageManager.SIGNATURE_NO_MATCH;
5639    }
5640
5641    @Override
5642    public List<String> getAllPackages() {
5643        synchronized (mPackages) {
5644            return new ArrayList<String>(mPackages.keySet());
5645        }
5646    }
5647
5648    @Override
5649    public String[] getPackagesForUid(int uid) {
5650        final int userId = UserHandle.getUserId(uid);
5651        uid = UserHandle.getAppId(uid);
5652        // reader
5653        synchronized (mPackages) {
5654            Object obj = mSettings.getUserIdLPr(uid);
5655            if (obj instanceof SharedUserSetting) {
5656                final SharedUserSetting sus = (SharedUserSetting) obj;
5657                final int N = sus.packages.size();
5658                String[] res = new String[N];
5659                final Iterator<PackageSetting> it = sus.packages.iterator();
5660                int i = 0;
5661                while (it.hasNext()) {
5662                    PackageSetting ps = it.next();
5663                    if (ps.getInstalled(userId)) {
5664                        res[i++] = ps.name;
5665                    } else {
5666                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5667                    }
5668                }
5669                return res;
5670            } else if (obj instanceof PackageSetting) {
5671                final PackageSetting ps = (PackageSetting) obj;
5672                if (ps.getInstalled(userId)) {
5673                    return new String[]{ps.name};
5674                }
5675            }
5676        }
5677        return null;
5678    }
5679
5680    @Override
5681    public String getNameForUid(int uid) {
5682        // reader
5683        synchronized (mPackages) {
5684            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5685            if (obj instanceof SharedUserSetting) {
5686                final SharedUserSetting sus = (SharedUserSetting) obj;
5687                return sus.name + ":" + sus.userId;
5688            } else if (obj instanceof PackageSetting) {
5689                final PackageSetting ps = (PackageSetting) obj;
5690                return ps.name;
5691            }
5692        }
5693        return null;
5694    }
5695
5696    @Override
5697    public int getUidForSharedUser(String sharedUserName) {
5698        if(sharedUserName == null) {
5699            return -1;
5700        }
5701        // reader
5702        synchronized (mPackages) {
5703            SharedUserSetting suid;
5704            try {
5705                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5706                if (suid != null) {
5707                    return suid.userId;
5708                }
5709            } catch (PackageManagerException ignore) {
5710                // can't happen, but, still need to catch it
5711            }
5712            return -1;
5713        }
5714    }
5715
5716    @Override
5717    public int getFlagsForUid(int uid) {
5718        synchronized (mPackages) {
5719            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5720            if (obj instanceof SharedUserSetting) {
5721                final SharedUserSetting sus = (SharedUserSetting) obj;
5722                return sus.pkgFlags;
5723            } else if (obj instanceof PackageSetting) {
5724                final PackageSetting ps = (PackageSetting) obj;
5725                return ps.pkgFlags;
5726            }
5727        }
5728        return 0;
5729    }
5730
5731    @Override
5732    public int getPrivateFlagsForUid(int uid) {
5733        synchronized (mPackages) {
5734            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5735            if (obj instanceof SharedUserSetting) {
5736                final SharedUserSetting sus = (SharedUserSetting) obj;
5737                return sus.pkgPrivateFlags;
5738            } else if (obj instanceof PackageSetting) {
5739                final PackageSetting ps = (PackageSetting) obj;
5740                return ps.pkgPrivateFlags;
5741            }
5742        }
5743        return 0;
5744    }
5745
5746    @Override
5747    public boolean isUidPrivileged(int uid) {
5748        uid = UserHandle.getAppId(uid);
5749        // reader
5750        synchronized (mPackages) {
5751            Object obj = mSettings.getUserIdLPr(uid);
5752            if (obj instanceof SharedUserSetting) {
5753                final SharedUserSetting sus = (SharedUserSetting) obj;
5754                final Iterator<PackageSetting> it = sus.packages.iterator();
5755                while (it.hasNext()) {
5756                    if (it.next().isPrivileged()) {
5757                        return true;
5758                    }
5759                }
5760            } else if (obj instanceof PackageSetting) {
5761                final PackageSetting ps = (PackageSetting) obj;
5762                return ps.isPrivileged();
5763            }
5764        }
5765        return false;
5766    }
5767
5768    @Override
5769    public String[] getAppOpPermissionPackages(String permissionName) {
5770        synchronized (mPackages) {
5771            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5772            if (pkgs == null) {
5773                return null;
5774            }
5775            return pkgs.toArray(new String[pkgs.size()]);
5776        }
5777    }
5778
5779    @Override
5780    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5781            int flags, int userId) {
5782        return resolveIntentInternal(
5783                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
5784    }
5785
5786    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5787            int flags, int userId, boolean resolveForStart) {
5788        try {
5789            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5790
5791            if (!sUserManager.exists(userId)) return null;
5792            final int callingUid = Binder.getCallingUid();
5793            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5794            enforceCrossUserPermission(callingUid, userId,
5795                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5796
5797            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5798            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5799                    flags, userId, resolveForStart);
5800            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5801
5802            final ResolveInfo bestChoice =
5803                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5804            return bestChoice;
5805        } finally {
5806            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5807        }
5808    }
5809
5810    @Override
5811    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5812        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5813            throw new SecurityException(
5814                    "findPersistentPreferredActivity can only be run by the system");
5815        }
5816        if (!sUserManager.exists(userId)) {
5817            return null;
5818        }
5819        final int callingUid = Binder.getCallingUid();
5820        intent = updateIntentForResolve(intent);
5821        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5822        final int flags = updateFlagsForResolve(
5823                0, userId, intent, callingUid, false /*includeInstantApps*/);
5824        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5825                userId);
5826        synchronized (mPackages) {
5827            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5828                    userId);
5829        }
5830    }
5831
5832    @Override
5833    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5834            IntentFilter filter, int match, ComponentName activity) {
5835        final int userId = UserHandle.getCallingUserId();
5836        if (DEBUG_PREFERRED) {
5837            Log.v(TAG, "setLastChosenActivity intent=" + intent
5838                + " resolvedType=" + resolvedType
5839                + " flags=" + flags
5840                + " filter=" + filter
5841                + " match=" + match
5842                + " activity=" + activity);
5843            filter.dump(new PrintStreamPrinter(System.out), "    ");
5844        }
5845        intent.setComponent(null);
5846        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5847                userId);
5848        // Find any earlier preferred or last chosen entries and nuke them
5849        findPreferredActivity(intent, resolvedType,
5850                flags, query, 0, false, true, false, userId);
5851        // Add the new activity as the last chosen for this filter
5852        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5853                "Setting last chosen");
5854    }
5855
5856    @Override
5857    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5858        final int userId = UserHandle.getCallingUserId();
5859        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5860        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5861                userId);
5862        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5863                false, false, false, userId);
5864    }
5865
5866    /**
5867     * Returns whether or not instant apps have been disabled remotely.
5868     */
5869    private boolean isEphemeralDisabled() {
5870        return mEphemeralAppsDisabled;
5871    }
5872
5873    private boolean isInstantAppAllowed(
5874            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5875            boolean skipPackageCheck) {
5876        if (mInstantAppResolverConnection == null) {
5877            return false;
5878        }
5879        if (mInstantAppInstallerActivity == null) {
5880            return false;
5881        }
5882        if (intent.getComponent() != null) {
5883            return false;
5884        }
5885        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5886            return false;
5887        }
5888        if (!skipPackageCheck && intent.getPackage() != null) {
5889            return false;
5890        }
5891        final boolean isWebUri = hasWebURI(intent);
5892        if (!isWebUri || intent.getData().getHost() == null) {
5893            return false;
5894        }
5895        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5896        // Or if there's already an ephemeral app installed that handles the action
5897        synchronized (mPackages) {
5898            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5899            for (int n = 0; n < count; n++) {
5900                final ResolveInfo info = resolvedActivities.get(n);
5901                final String packageName = info.activityInfo.packageName;
5902                final PackageSetting ps = mSettings.mPackages.get(packageName);
5903                if (ps != null) {
5904                    // only check domain verification status if the app is not a browser
5905                    if (!info.handleAllWebDataURI) {
5906                        // Try to get the status from User settings first
5907                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5908                        final int status = (int) (packedStatus >> 32);
5909                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5910                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5911                            if (DEBUG_EPHEMERAL) {
5912                                Slog.v(TAG, "DENY instant app;"
5913                                    + " pkg: " + packageName + ", status: " + status);
5914                            }
5915                            return false;
5916                        }
5917                    }
5918                    if (ps.getInstantApp(userId)) {
5919                        if (DEBUG_EPHEMERAL) {
5920                            Slog.v(TAG, "DENY instant app installed;"
5921                                    + " pkg: " + packageName);
5922                        }
5923                        return false;
5924                    }
5925                }
5926            }
5927        }
5928        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5929        return true;
5930    }
5931
5932    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5933            Intent origIntent, String resolvedType, String callingPackage,
5934            Bundle verificationBundle, int userId) {
5935        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5936                new InstantAppRequest(responseObj, origIntent, resolvedType,
5937                        callingPackage, userId, verificationBundle));
5938        mHandler.sendMessage(msg);
5939    }
5940
5941    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5942            int flags, List<ResolveInfo> query, int userId) {
5943        if (query != null) {
5944            final int N = query.size();
5945            if (N == 1) {
5946                return query.get(0);
5947            } else if (N > 1) {
5948                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5949                // If there is more than one activity with the same priority,
5950                // then let the user decide between them.
5951                ResolveInfo r0 = query.get(0);
5952                ResolveInfo r1 = query.get(1);
5953                if (DEBUG_INTENT_MATCHING || debug) {
5954                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5955                            + r1.activityInfo.name + "=" + r1.priority);
5956                }
5957                // If the first activity has a higher priority, or a different
5958                // default, then it is always desirable to pick it.
5959                if (r0.priority != r1.priority
5960                        || r0.preferredOrder != r1.preferredOrder
5961                        || r0.isDefault != r1.isDefault) {
5962                    return query.get(0);
5963                }
5964                // If we have saved a preference for a preferred activity for
5965                // this Intent, use that.
5966                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5967                        flags, query, r0.priority, true, false, debug, userId);
5968                if (ri != null) {
5969                    return ri;
5970                }
5971                // If we have an ephemeral app, use it
5972                for (int i = 0; i < N; i++) {
5973                    ri = query.get(i);
5974                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5975                        final String packageName = ri.activityInfo.packageName;
5976                        final PackageSetting ps = mSettings.mPackages.get(packageName);
5977                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5978                        final int status = (int)(packedStatus >> 32);
5979                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5980                            return ri;
5981                        }
5982                    }
5983                }
5984                ri = new ResolveInfo(mResolveInfo);
5985                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5986                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5987                // If all of the options come from the same package, show the application's
5988                // label and icon instead of the generic resolver's.
5989                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5990                // and then throw away the ResolveInfo itself, meaning that the caller loses
5991                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5992                // a fallback for this case; we only set the target package's resources on
5993                // the ResolveInfo, not the ActivityInfo.
5994                final String intentPackage = intent.getPackage();
5995                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5996                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5997                    ri.resolvePackageName = intentPackage;
5998                    if (userNeedsBadging(userId)) {
5999                        ri.noResourceId = true;
6000                    } else {
6001                        ri.icon = appi.icon;
6002                    }
6003                    ri.iconResourceId = appi.icon;
6004                    ri.labelRes = appi.labelRes;
6005                }
6006                ri.activityInfo.applicationInfo = new ApplicationInfo(
6007                        ri.activityInfo.applicationInfo);
6008                if (userId != 0) {
6009                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6010                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6011                }
6012                // Make sure that the resolver is displayable in car mode
6013                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6014                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6015                return ri;
6016            }
6017        }
6018        return null;
6019    }
6020
6021    /**
6022     * Return true if the given list is not empty and all of its contents have
6023     * an activityInfo with the given package name.
6024     */
6025    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6026        if (ArrayUtils.isEmpty(list)) {
6027            return false;
6028        }
6029        for (int i = 0, N = list.size(); i < N; i++) {
6030            final ResolveInfo ri = list.get(i);
6031            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6032            if (ai == null || !packageName.equals(ai.packageName)) {
6033                return false;
6034            }
6035        }
6036        return true;
6037    }
6038
6039    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6040            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6041        final int N = query.size();
6042        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6043                .get(userId);
6044        // Get the list of persistent preferred activities that handle the intent
6045        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6046        List<PersistentPreferredActivity> pprefs = ppir != null
6047                ? ppir.queryIntent(intent, resolvedType,
6048                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6049                        userId)
6050                : null;
6051        if (pprefs != null && pprefs.size() > 0) {
6052            final int M = pprefs.size();
6053            for (int i=0; i<M; i++) {
6054                final PersistentPreferredActivity ppa = pprefs.get(i);
6055                if (DEBUG_PREFERRED || debug) {
6056                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6057                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6058                            + "\n  component=" + ppa.mComponent);
6059                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6060                }
6061                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6062                        flags | MATCH_DISABLED_COMPONENTS, userId);
6063                if (DEBUG_PREFERRED || debug) {
6064                    Slog.v(TAG, "Found persistent preferred activity:");
6065                    if (ai != null) {
6066                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6067                    } else {
6068                        Slog.v(TAG, "  null");
6069                    }
6070                }
6071                if (ai == null) {
6072                    // This previously registered persistent preferred activity
6073                    // component is no longer known. Ignore it and do NOT remove it.
6074                    continue;
6075                }
6076                for (int j=0; j<N; j++) {
6077                    final ResolveInfo ri = query.get(j);
6078                    if (!ri.activityInfo.applicationInfo.packageName
6079                            .equals(ai.applicationInfo.packageName)) {
6080                        continue;
6081                    }
6082                    if (!ri.activityInfo.name.equals(ai.name)) {
6083                        continue;
6084                    }
6085                    //  Found a persistent preference that can handle the intent.
6086                    if (DEBUG_PREFERRED || debug) {
6087                        Slog.v(TAG, "Returning persistent preferred activity: " +
6088                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6089                    }
6090                    return ri;
6091                }
6092            }
6093        }
6094        return null;
6095    }
6096
6097    // TODO: handle preferred activities missing while user has amnesia
6098    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6099            List<ResolveInfo> query, int priority, boolean always,
6100            boolean removeMatches, boolean debug, int userId) {
6101        if (!sUserManager.exists(userId)) return null;
6102        final int callingUid = Binder.getCallingUid();
6103        flags = updateFlagsForResolve(
6104                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6105        intent = updateIntentForResolve(intent);
6106        // writer
6107        synchronized (mPackages) {
6108            // Try to find a matching persistent preferred activity.
6109            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6110                    debug, userId);
6111
6112            // If a persistent preferred activity matched, use it.
6113            if (pri != null) {
6114                return pri;
6115            }
6116
6117            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6118            // Get the list of preferred activities that handle the intent
6119            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6120            List<PreferredActivity> prefs = pir != null
6121                    ? pir.queryIntent(intent, resolvedType,
6122                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6123                            userId)
6124                    : null;
6125            if (prefs != null && prefs.size() > 0) {
6126                boolean changed = false;
6127                try {
6128                    // First figure out how good the original match set is.
6129                    // We will only allow preferred activities that came
6130                    // from the same match quality.
6131                    int match = 0;
6132
6133                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6134
6135                    final int N = query.size();
6136                    for (int j=0; j<N; j++) {
6137                        final ResolveInfo ri = query.get(j);
6138                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6139                                + ": 0x" + Integer.toHexString(match));
6140                        if (ri.match > match) {
6141                            match = ri.match;
6142                        }
6143                    }
6144
6145                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6146                            + Integer.toHexString(match));
6147
6148                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6149                    final int M = prefs.size();
6150                    for (int i=0; i<M; i++) {
6151                        final PreferredActivity pa = prefs.get(i);
6152                        if (DEBUG_PREFERRED || debug) {
6153                            Slog.v(TAG, "Checking PreferredActivity ds="
6154                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6155                                    + "\n  component=" + pa.mPref.mComponent);
6156                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6157                        }
6158                        if (pa.mPref.mMatch != match) {
6159                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6160                                    + Integer.toHexString(pa.mPref.mMatch));
6161                            continue;
6162                        }
6163                        // If it's not an "always" type preferred activity and that's what we're
6164                        // looking for, skip it.
6165                        if (always && !pa.mPref.mAlways) {
6166                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6167                            continue;
6168                        }
6169                        final ActivityInfo ai = getActivityInfo(
6170                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6171                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6172                                userId);
6173                        if (DEBUG_PREFERRED || debug) {
6174                            Slog.v(TAG, "Found preferred activity:");
6175                            if (ai != null) {
6176                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6177                            } else {
6178                                Slog.v(TAG, "  null");
6179                            }
6180                        }
6181                        if (ai == null) {
6182                            // This previously registered preferred activity
6183                            // component is no longer known.  Most likely an update
6184                            // to the app was installed and in the new version this
6185                            // component no longer exists.  Clean it up by removing
6186                            // it from the preferred activities list, and skip it.
6187                            Slog.w(TAG, "Removing dangling preferred activity: "
6188                                    + pa.mPref.mComponent);
6189                            pir.removeFilter(pa);
6190                            changed = true;
6191                            continue;
6192                        }
6193                        for (int j=0; j<N; j++) {
6194                            final ResolveInfo ri = query.get(j);
6195                            if (!ri.activityInfo.applicationInfo.packageName
6196                                    .equals(ai.applicationInfo.packageName)) {
6197                                continue;
6198                            }
6199                            if (!ri.activityInfo.name.equals(ai.name)) {
6200                                continue;
6201                            }
6202
6203                            if (removeMatches) {
6204                                pir.removeFilter(pa);
6205                                changed = true;
6206                                if (DEBUG_PREFERRED) {
6207                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6208                                }
6209                                break;
6210                            }
6211
6212                            // Okay we found a previously set preferred or last chosen app.
6213                            // If the result set is different from when this
6214                            // was created, we need to clear it and re-ask the
6215                            // user their preference, if we're looking for an "always" type entry.
6216                            if (always && !pa.mPref.sameSet(query)) {
6217                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6218                                        + intent + " type " + resolvedType);
6219                                if (DEBUG_PREFERRED) {
6220                                    Slog.v(TAG, "Removing preferred activity since set changed "
6221                                            + pa.mPref.mComponent);
6222                                }
6223                                pir.removeFilter(pa);
6224                                // Re-add the filter as a "last chosen" entry (!always)
6225                                PreferredActivity lastChosen = new PreferredActivity(
6226                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6227                                pir.addFilter(lastChosen);
6228                                changed = true;
6229                                return null;
6230                            }
6231
6232                            // Yay! Either the set matched or we're looking for the last chosen
6233                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6234                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6235                            return ri;
6236                        }
6237                    }
6238                } finally {
6239                    if (changed) {
6240                        if (DEBUG_PREFERRED) {
6241                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6242                        }
6243                        scheduleWritePackageRestrictionsLocked(userId);
6244                    }
6245                }
6246            }
6247        }
6248        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6249        return null;
6250    }
6251
6252    /*
6253     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6254     */
6255    @Override
6256    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6257            int targetUserId) {
6258        mContext.enforceCallingOrSelfPermission(
6259                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6260        List<CrossProfileIntentFilter> matches =
6261                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6262        if (matches != null) {
6263            int size = matches.size();
6264            for (int i = 0; i < size; i++) {
6265                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6266            }
6267        }
6268        if (hasWebURI(intent)) {
6269            // cross-profile app linking works only towards the parent.
6270            final int callingUid = Binder.getCallingUid();
6271            final UserInfo parent = getProfileParent(sourceUserId);
6272            synchronized(mPackages) {
6273                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6274                        false /*includeInstantApps*/);
6275                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6276                        intent, resolvedType, flags, sourceUserId, parent.id);
6277                return xpDomainInfo != null;
6278            }
6279        }
6280        return false;
6281    }
6282
6283    private UserInfo getProfileParent(int userId) {
6284        final long identity = Binder.clearCallingIdentity();
6285        try {
6286            return sUserManager.getProfileParent(userId);
6287        } finally {
6288            Binder.restoreCallingIdentity(identity);
6289        }
6290    }
6291
6292    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6293            String resolvedType, int userId) {
6294        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6295        if (resolver != null) {
6296            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6297        }
6298        return null;
6299    }
6300
6301    @Override
6302    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6303            String resolvedType, int flags, int userId) {
6304        try {
6305            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6306
6307            return new ParceledListSlice<>(
6308                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6309        } finally {
6310            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6311        }
6312    }
6313
6314    /**
6315     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6316     * instant, returns {@code null}.
6317     */
6318    private String getInstantAppPackageName(int callingUid) {
6319        // If the caller is an isolated app use the owner's uid for the lookup.
6320        if (Process.isIsolated(callingUid)) {
6321            callingUid = mIsolatedOwners.get(callingUid);
6322        }
6323        final int appId = UserHandle.getAppId(callingUid);
6324        synchronized (mPackages) {
6325            final Object obj = mSettings.getUserIdLPr(appId);
6326            if (obj instanceof PackageSetting) {
6327                final PackageSetting ps = (PackageSetting) obj;
6328                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6329                return isInstantApp ? ps.pkg.packageName : null;
6330            }
6331        }
6332        return null;
6333    }
6334
6335    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6336            String resolvedType, int flags, int userId) {
6337        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6338    }
6339
6340    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6341            String resolvedType, int flags, int userId, boolean resolveForStart) {
6342        if (!sUserManager.exists(userId)) return Collections.emptyList();
6343        final int callingUid = Binder.getCallingUid();
6344        final String instantAppPkgName = getInstantAppPackageName(callingUid);
6345        enforceCrossUserPermission(callingUid, userId,
6346                false /* requireFullPermission */, false /* checkShell */,
6347                "query intent activities");
6348        final String pkgName = intent.getPackage();
6349        ComponentName comp = intent.getComponent();
6350        if (comp == null) {
6351            if (intent.getSelector() != null) {
6352                intent = intent.getSelector();
6353                comp = intent.getComponent();
6354            }
6355        }
6356
6357        flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart,
6358                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6359        if (comp != null) {
6360            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6361            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6362            if (ai != null) {
6363                // When specifying an explicit component, we prevent the activity from being
6364                // used when either 1) the calling package is normal and the activity is within
6365                // an ephemeral application or 2) the calling package is ephemeral and the
6366                // activity is not visible to ephemeral applications.
6367                final boolean matchInstantApp =
6368                        (flags & PackageManager.MATCH_INSTANT) != 0;
6369                final boolean matchVisibleToInstantAppOnly =
6370                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6371                final boolean matchExplicitlyVisibleOnly =
6372                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6373                final boolean isCallerInstantApp =
6374                        instantAppPkgName != null;
6375                final boolean isTargetSameInstantApp =
6376                        comp.getPackageName().equals(instantAppPkgName);
6377                final boolean isTargetInstantApp =
6378                        (ai.applicationInfo.privateFlags
6379                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6380                final boolean isTargetVisibleToInstantApp =
6381                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6382                final boolean isTargetExplicitlyVisibleToInstantApp =
6383                        isTargetVisibleToInstantApp
6384                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6385                final boolean isTargetHiddenFromInstantApp =
6386                        !isTargetVisibleToInstantApp
6387                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6388                final boolean blockResolution =
6389                        !isTargetSameInstantApp
6390                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6391                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6392                                        && isTargetHiddenFromInstantApp));
6393                if (!blockResolution) {
6394                    final ResolveInfo ri = new ResolveInfo();
6395                    ri.activityInfo = ai;
6396                    list.add(ri);
6397                }
6398            }
6399            return applyPostResolutionFilter(list, instantAppPkgName);
6400        }
6401
6402        // reader
6403        boolean sortResult = false;
6404        boolean addEphemeral = false;
6405        List<ResolveInfo> result;
6406        final boolean ephemeralDisabled = isEphemeralDisabled();
6407        synchronized (mPackages) {
6408            if (pkgName == null) {
6409                List<CrossProfileIntentFilter> matchingFilters =
6410                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6411                // Check for results that need to skip the current profile.
6412                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6413                        resolvedType, flags, userId);
6414                if (xpResolveInfo != null) {
6415                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6416                    xpResult.add(xpResolveInfo);
6417                    return applyPostResolutionFilter(
6418                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6419                }
6420
6421                // Check for results in the current profile.
6422                result = filterIfNotSystemUser(mActivities.queryIntent(
6423                        intent, resolvedType, flags, userId), userId);
6424                addEphemeral = !ephemeralDisabled
6425                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6426                // Check for cross profile results.
6427                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6428                xpResolveInfo = queryCrossProfileIntents(
6429                        matchingFilters, intent, resolvedType, flags, userId,
6430                        hasNonNegativePriorityResult);
6431                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6432                    boolean isVisibleToUser = filterIfNotSystemUser(
6433                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6434                    if (isVisibleToUser) {
6435                        result.add(xpResolveInfo);
6436                        sortResult = true;
6437                    }
6438                }
6439                if (hasWebURI(intent)) {
6440                    CrossProfileDomainInfo xpDomainInfo = null;
6441                    final UserInfo parent = getProfileParent(userId);
6442                    if (parent != null) {
6443                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6444                                flags, userId, parent.id);
6445                    }
6446                    if (xpDomainInfo != null) {
6447                        if (xpResolveInfo != null) {
6448                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6449                            // in the result.
6450                            result.remove(xpResolveInfo);
6451                        }
6452                        if (result.size() == 0 && !addEphemeral) {
6453                            // No result in current profile, but found candidate in parent user.
6454                            // And we are not going to add emphemeral app, so we can return the
6455                            // result straight away.
6456                            result.add(xpDomainInfo.resolveInfo);
6457                            return applyPostResolutionFilter(result, instantAppPkgName);
6458                        }
6459                    } else if (result.size() <= 1 && !addEphemeral) {
6460                        // No result in parent user and <= 1 result in current profile, and we
6461                        // are not going to add emphemeral app, so we can return the result without
6462                        // further processing.
6463                        return applyPostResolutionFilter(result, instantAppPkgName);
6464                    }
6465                    // We have more than one candidate (combining results from current and parent
6466                    // profile), so we need filtering and sorting.
6467                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6468                            intent, flags, result, xpDomainInfo, userId);
6469                    sortResult = true;
6470                }
6471            } else {
6472                final PackageParser.Package pkg = mPackages.get(pkgName);
6473                if (pkg != null) {
6474                    return applyPostResolutionFilter(filterIfNotSystemUser(
6475                            mActivities.queryIntentForPackage(
6476                                    intent, resolvedType, flags, pkg.activities, userId),
6477                            userId), instantAppPkgName);
6478                } else {
6479                    // the caller wants to resolve for a particular package; however, there
6480                    // were no installed results, so, try to find an ephemeral result
6481                    addEphemeral = !ephemeralDisabled
6482                            && isInstantAppAllowed(
6483                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6484                    result = new ArrayList<ResolveInfo>();
6485                }
6486            }
6487        }
6488        if (addEphemeral) {
6489            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
6490        }
6491        if (sortResult) {
6492            Collections.sort(result, mResolvePrioritySorter);
6493        }
6494        return applyPostResolutionFilter(result, instantAppPkgName);
6495    }
6496
6497    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6498            String resolvedType, int flags, int userId) {
6499        // first, check to see if we've got an instant app already installed
6500        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6501        ResolveInfo localInstantApp = null;
6502        boolean blockResolution = false;
6503        if (!alreadyResolvedLocally) {
6504            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6505                    flags
6506                        | PackageManager.GET_RESOLVED_FILTER
6507                        | PackageManager.MATCH_INSTANT
6508                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6509                    userId);
6510            for (int i = instantApps.size() - 1; i >= 0; --i) {
6511                final ResolveInfo info = instantApps.get(i);
6512                final String packageName = info.activityInfo.packageName;
6513                final PackageSetting ps = mSettings.mPackages.get(packageName);
6514                if (ps.getInstantApp(userId)) {
6515                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6516                    final int status = (int)(packedStatus >> 32);
6517                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6518                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6519                        // there's a local instant application installed, but, the user has
6520                        // chosen to never use it; skip resolution and don't acknowledge
6521                        // an instant application is even available
6522                        if (DEBUG_EPHEMERAL) {
6523                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6524                        }
6525                        blockResolution = true;
6526                        break;
6527                    } else {
6528                        // we have a locally installed instant application; skip resolution
6529                        // but acknowledge there's an instant application available
6530                        if (DEBUG_EPHEMERAL) {
6531                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6532                        }
6533                        localInstantApp = info;
6534                        break;
6535                    }
6536                }
6537            }
6538        }
6539        // no app installed, let's see if one's available
6540        AuxiliaryResolveInfo auxiliaryResponse = null;
6541        if (!blockResolution) {
6542            if (localInstantApp == null) {
6543                // we don't have an instant app locally, resolve externally
6544                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6545                final InstantAppRequest requestObject = new InstantAppRequest(
6546                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6547                        null /*callingPackage*/, userId, null /*verificationBundle*/);
6548                auxiliaryResponse =
6549                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6550                                mContext, mInstantAppResolverConnection, requestObject);
6551                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6552            } else {
6553                // we have an instant application locally, but, we can't admit that since
6554                // callers shouldn't be able to determine prior browsing. create a dummy
6555                // auxiliary response so the downstream code behaves as if there's an
6556                // instant application available externally. when it comes time to start
6557                // the instant application, we'll do the right thing.
6558                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6559                auxiliaryResponse = new AuxiliaryResolveInfo(
6560                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
6561            }
6562        }
6563        if (auxiliaryResponse != null) {
6564            if (DEBUG_EPHEMERAL) {
6565                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6566            }
6567            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6568            final PackageSetting ps =
6569                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6570            if (ps != null) {
6571                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6572                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6573                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6574                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6575                // make sure this resolver is the default
6576                ephemeralInstaller.isDefault = true;
6577                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6578                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6579                // add a non-generic filter
6580                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6581                ephemeralInstaller.filter.addDataPath(
6582                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6583                ephemeralInstaller.isInstantAppAvailable = true;
6584                result.add(ephemeralInstaller);
6585            }
6586        }
6587        return result;
6588    }
6589
6590    private static class CrossProfileDomainInfo {
6591        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6592        ResolveInfo resolveInfo;
6593        /* Best domain verification status of the activities found in the other profile */
6594        int bestDomainVerificationStatus;
6595    }
6596
6597    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6598            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6599        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6600                sourceUserId)) {
6601            return null;
6602        }
6603        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6604                resolvedType, flags, parentUserId);
6605
6606        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6607            return null;
6608        }
6609        CrossProfileDomainInfo result = null;
6610        int size = resultTargetUser.size();
6611        for (int i = 0; i < size; i++) {
6612            ResolveInfo riTargetUser = resultTargetUser.get(i);
6613            // Intent filter verification is only for filters that specify a host. So don't return
6614            // those that handle all web uris.
6615            if (riTargetUser.handleAllWebDataURI) {
6616                continue;
6617            }
6618            String packageName = riTargetUser.activityInfo.packageName;
6619            PackageSetting ps = mSettings.mPackages.get(packageName);
6620            if (ps == null) {
6621                continue;
6622            }
6623            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6624            int status = (int)(verificationState >> 32);
6625            if (result == null) {
6626                result = new CrossProfileDomainInfo();
6627                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6628                        sourceUserId, parentUserId);
6629                result.bestDomainVerificationStatus = status;
6630            } else {
6631                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6632                        result.bestDomainVerificationStatus);
6633            }
6634        }
6635        // Don't consider matches with status NEVER across profiles.
6636        if (result != null && result.bestDomainVerificationStatus
6637                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6638            return null;
6639        }
6640        return result;
6641    }
6642
6643    /**
6644     * Verification statuses are ordered from the worse to the best, except for
6645     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6646     */
6647    private int bestDomainVerificationStatus(int status1, int status2) {
6648        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6649            return status2;
6650        }
6651        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6652            return status1;
6653        }
6654        return (int) MathUtils.max(status1, status2);
6655    }
6656
6657    private boolean isUserEnabled(int userId) {
6658        long callingId = Binder.clearCallingIdentity();
6659        try {
6660            UserInfo userInfo = sUserManager.getUserInfo(userId);
6661            return userInfo != null && userInfo.isEnabled();
6662        } finally {
6663            Binder.restoreCallingIdentity(callingId);
6664        }
6665    }
6666
6667    /**
6668     * Filter out activities with systemUserOnly flag set, when current user is not System.
6669     *
6670     * @return filtered list
6671     */
6672    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6673        if (userId == UserHandle.USER_SYSTEM) {
6674            return resolveInfos;
6675        }
6676        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6677            ResolveInfo info = resolveInfos.get(i);
6678            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6679                resolveInfos.remove(i);
6680            }
6681        }
6682        return resolveInfos;
6683    }
6684
6685    /**
6686     * Filters out ephemeral activities.
6687     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6688     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6689     *
6690     * @param resolveInfos The pre-filtered list of resolved activities
6691     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6692     *          is performed.
6693     * @return A filtered list of resolved activities.
6694     */
6695    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6696            String ephemeralPkgName) {
6697        // TODO: When adding on-demand split support for non-instant apps, remove this check
6698        // and always apply post filtering
6699        if (ephemeralPkgName == null) {
6700            return resolveInfos;
6701        }
6702        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6703            final ResolveInfo info = resolveInfos.get(i);
6704            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6705            // allow activities that are defined in the provided package
6706            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6707                if (info.activityInfo.splitName != null
6708                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6709                                info.activityInfo.splitName)) {
6710                    // requested activity is defined in a split that hasn't been installed yet.
6711                    // add the installer to the resolve list
6712                    if (DEBUG_EPHEMERAL) {
6713                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6714                    }
6715                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6716                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6717                            info.activityInfo.packageName, info.activityInfo.splitName,
6718                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
6719                    // make sure this resolver is the default
6720                    installerInfo.isDefault = true;
6721                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6722                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6723                    // add a non-generic filter
6724                    installerInfo.filter = new IntentFilter();
6725                    // load resources from the correct package
6726                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6727                    resolveInfos.set(i, installerInfo);
6728                }
6729                continue;
6730            }
6731            // allow activities that have been explicitly exposed to ephemeral apps
6732            if (!isEphemeralApp
6733                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6734                continue;
6735            }
6736            resolveInfos.remove(i);
6737        }
6738        return resolveInfos;
6739    }
6740
6741    /**
6742     * @param resolveInfos list of resolve infos in descending priority order
6743     * @return if the list contains a resolve info with non-negative priority
6744     */
6745    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6746        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6747    }
6748
6749    private static boolean hasWebURI(Intent intent) {
6750        if (intent.getData() == null) {
6751            return false;
6752        }
6753        final String scheme = intent.getScheme();
6754        if (TextUtils.isEmpty(scheme)) {
6755            return false;
6756        }
6757        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6758    }
6759
6760    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6761            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6762            int userId) {
6763        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6764
6765        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6766            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6767                    candidates.size());
6768        }
6769
6770        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6771        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6772        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6773        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6774        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6775        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6776
6777        synchronized (mPackages) {
6778            final int count = candidates.size();
6779            // First, try to use linked apps. Partition the candidates into four lists:
6780            // one for the final results, one for the "do not use ever", one for "undefined status"
6781            // and finally one for "browser app type".
6782            for (int n=0; n<count; n++) {
6783                ResolveInfo info = candidates.get(n);
6784                String packageName = info.activityInfo.packageName;
6785                PackageSetting ps = mSettings.mPackages.get(packageName);
6786                if (ps != null) {
6787                    // Add to the special match all list (Browser use case)
6788                    if (info.handleAllWebDataURI) {
6789                        matchAllList.add(info);
6790                        continue;
6791                    }
6792                    // Try to get the status from User settings first
6793                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6794                    int status = (int)(packedStatus >> 32);
6795                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6796                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6797                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6798                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6799                                    + " : linkgen=" + linkGeneration);
6800                        }
6801                        // Use link-enabled generation as preferredOrder, i.e.
6802                        // prefer newly-enabled over earlier-enabled.
6803                        info.preferredOrder = linkGeneration;
6804                        alwaysList.add(info);
6805                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6806                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6807                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6808                        }
6809                        neverList.add(info);
6810                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6811                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6812                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6813                        }
6814                        alwaysAskList.add(info);
6815                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6816                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6817                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6818                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6819                        }
6820                        undefinedList.add(info);
6821                    }
6822                }
6823            }
6824
6825            // We'll want to include browser possibilities in a few cases
6826            boolean includeBrowser = false;
6827
6828            // First try to add the "always" resolution(s) for the current user, if any
6829            if (alwaysList.size() > 0) {
6830                result.addAll(alwaysList);
6831            } else {
6832                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6833                result.addAll(undefinedList);
6834                // Maybe add one for the other profile.
6835                if (xpDomainInfo != null && (
6836                        xpDomainInfo.bestDomainVerificationStatus
6837                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6838                    result.add(xpDomainInfo.resolveInfo);
6839                }
6840                includeBrowser = true;
6841            }
6842
6843            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6844            // If there were 'always' entries their preferred order has been set, so we also
6845            // back that off to make the alternatives equivalent
6846            if (alwaysAskList.size() > 0) {
6847                for (ResolveInfo i : result) {
6848                    i.preferredOrder = 0;
6849                }
6850                result.addAll(alwaysAskList);
6851                includeBrowser = true;
6852            }
6853
6854            if (includeBrowser) {
6855                // Also add browsers (all of them or only the default one)
6856                if (DEBUG_DOMAIN_VERIFICATION) {
6857                    Slog.v(TAG, "   ...including browsers in candidate set");
6858                }
6859                if ((matchFlags & MATCH_ALL) != 0) {
6860                    result.addAll(matchAllList);
6861                } else {
6862                    // Browser/generic handling case.  If there's a default browser, go straight
6863                    // to that (but only if there is no other higher-priority match).
6864                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6865                    int maxMatchPrio = 0;
6866                    ResolveInfo defaultBrowserMatch = null;
6867                    final int numCandidates = matchAllList.size();
6868                    for (int n = 0; n < numCandidates; n++) {
6869                        ResolveInfo info = matchAllList.get(n);
6870                        // track the highest overall match priority...
6871                        if (info.priority > maxMatchPrio) {
6872                            maxMatchPrio = info.priority;
6873                        }
6874                        // ...and the highest-priority default browser match
6875                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6876                            if (defaultBrowserMatch == null
6877                                    || (defaultBrowserMatch.priority < info.priority)) {
6878                                if (debug) {
6879                                    Slog.v(TAG, "Considering default browser match " + info);
6880                                }
6881                                defaultBrowserMatch = info;
6882                            }
6883                        }
6884                    }
6885                    if (defaultBrowserMatch != null
6886                            && defaultBrowserMatch.priority >= maxMatchPrio
6887                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6888                    {
6889                        if (debug) {
6890                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6891                        }
6892                        result.add(defaultBrowserMatch);
6893                    } else {
6894                        result.addAll(matchAllList);
6895                    }
6896                }
6897
6898                // If there is nothing selected, add all candidates and remove the ones that the user
6899                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6900                if (result.size() == 0) {
6901                    result.addAll(candidates);
6902                    result.removeAll(neverList);
6903                }
6904            }
6905        }
6906        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6907            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6908                    result.size());
6909            for (ResolveInfo info : result) {
6910                Slog.v(TAG, "  + " + info.activityInfo);
6911            }
6912        }
6913        return result;
6914    }
6915
6916    // Returns a packed value as a long:
6917    //
6918    // high 'int'-sized word: link status: undefined/ask/never/always.
6919    // low 'int'-sized word: relative priority among 'always' results.
6920    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6921        long result = ps.getDomainVerificationStatusForUser(userId);
6922        // if none available, get the master status
6923        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6924            if (ps.getIntentFilterVerificationInfo() != null) {
6925                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6926            }
6927        }
6928        return result;
6929    }
6930
6931    private ResolveInfo querySkipCurrentProfileIntents(
6932            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6933            int flags, int sourceUserId) {
6934        if (matchingFilters != null) {
6935            int size = matchingFilters.size();
6936            for (int i = 0; i < size; i ++) {
6937                CrossProfileIntentFilter filter = matchingFilters.get(i);
6938                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6939                    // Checking if there are activities in the target user that can handle the
6940                    // intent.
6941                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6942                            resolvedType, flags, sourceUserId);
6943                    if (resolveInfo != null) {
6944                        return resolveInfo;
6945                    }
6946                }
6947            }
6948        }
6949        return null;
6950    }
6951
6952    // Return matching ResolveInfo in target user if any.
6953    private ResolveInfo queryCrossProfileIntents(
6954            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6955            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6956        if (matchingFilters != null) {
6957            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6958            // match the same intent. For performance reasons, it is better not to
6959            // run queryIntent twice for the same userId
6960            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6961            int size = matchingFilters.size();
6962            for (int i = 0; i < size; i++) {
6963                CrossProfileIntentFilter filter = matchingFilters.get(i);
6964                int targetUserId = filter.getTargetUserId();
6965                boolean skipCurrentProfile =
6966                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6967                boolean skipCurrentProfileIfNoMatchFound =
6968                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6969                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6970                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6971                    // Checking if there are activities in the target user that can handle the
6972                    // intent.
6973                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6974                            resolvedType, flags, sourceUserId);
6975                    if (resolveInfo != null) return resolveInfo;
6976                    alreadyTriedUserIds.put(targetUserId, true);
6977                }
6978            }
6979        }
6980        return null;
6981    }
6982
6983    /**
6984     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6985     * will forward the intent to the filter's target user.
6986     * Otherwise, returns null.
6987     */
6988    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6989            String resolvedType, int flags, int sourceUserId) {
6990        int targetUserId = filter.getTargetUserId();
6991        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6992                resolvedType, flags, targetUserId);
6993        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6994            // If all the matches in the target profile are suspended, return null.
6995            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6996                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6997                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6998                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6999                            targetUserId);
7000                }
7001            }
7002        }
7003        return null;
7004    }
7005
7006    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7007            int sourceUserId, int targetUserId) {
7008        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7009        long ident = Binder.clearCallingIdentity();
7010        boolean targetIsProfile;
7011        try {
7012            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7013        } finally {
7014            Binder.restoreCallingIdentity(ident);
7015        }
7016        String className;
7017        if (targetIsProfile) {
7018            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7019        } else {
7020            className = FORWARD_INTENT_TO_PARENT;
7021        }
7022        ComponentName forwardingActivityComponentName = new ComponentName(
7023                mAndroidApplication.packageName, className);
7024        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7025                sourceUserId);
7026        if (!targetIsProfile) {
7027            forwardingActivityInfo.showUserIcon = targetUserId;
7028            forwardingResolveInfo.noResourceId = true;
7029        }
7030        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7031        forwardingResolveInfo.priority = 0;
7032        forwardingResolveInfo.preferredOrder = 0;
7033        forwardingResolveInfo.match = 0;
7034        forwardingResolveInfo.isDefault = true;
7035        forwardingResolveInfo.filter = filter;
7036        forwardingResolveInfo.targetUserId = targetUserId;
7037        return forwardingResolveInfo;
7038    }
7039
7040    @Override
7041    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7042            Intent[] specifics, String[] specificTypes, Intent intent,
7043            String resolvedType, int flags, int userId) {
7044        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7045                specificTypes, intent, resolvedType, flags, userId));
7046    }
7047
7048    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7049            Intent[] specifics, String[] specificTypes, Intent intent,
7050            String resolvedType, int flags, int userId) {
7051        if (!sUserManager.exists(userId)) return Collections.emptyList();
7052        final int callingUid = Binder.getCallingUid();
7053        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7054                false /*includeInstantApps*/);
7055        enforceCrossUserPermission(callingUid, userId,
7056                false /*requireFullPermission*/, false /*checkShell*/,
7057                "query intent activity options");
7058        final String resultsAction = intent.getAction();
7059
7060        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7061                | PackageManager.GET_RESOLVED_FILTER, userId);
7062
7063        if (DEBUG_INTENT_MATCHING) {
7064            Log.v(TAG, "Query " + intent + ": " + results);
7065        }
7066
7067        int specificsPos = 0;
7068        int N;
7069
7070        // todo: note that the algorithm used here is O(N^2).  This
7071        // isn't a problem in our current environment, but if we start running
7072        // into situations where we have more than 5 or 10 matches then this
7073        // should probably be changed to something smarter...
7074
7075        // First we go through and resolve each of the specific items
7076        // that were supplied, taking care of removing any corresponding
7077        // duplicate items in the generic resolve list.
7078        if (specifics != null) {
7079            for (int i=0; i<specifics.length; i++) {
7080                final Intent sintent = specifics[i];
7081                if (sintent == null) {
7082                    continue;
7083                }
7084
7085                if (DEBUG_INTENT_MATCHING) {
7086                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7087                }
7088
7089                String action = sintent.getAction();
7090                if (resultsAction != null && resultsAction.equals(action)) {
7091                    // If this action was explicitly requested, then don't
7092                    // remove things that have it.
7093                    action = null;
7094                }
7095
7096                ResolveInfo ri = null;
7097                ActivityInfo ai = null;
7098
7099                ComponentName comp = sintent.getComponent();
7100                if (comp == null) {
7101                    ri = resolveIntent(
7102                        sintent,
7103                        specificTypes != null ? specificTypes[i] : null,
7104                            flags, userId);
7105                    if (ri == null) {
7106                        continue;
7107                    }
7108                    if (ri == mResolveInfo) {
7109                        // ACK!  Must do something better with this.
7110                    }
7111                    ai = ri.activityInfo;
7112                    comp = new ComponentName(ai.applicationInfo.packageName,
7113                            ai.name);
7114                } else {
7115                    ai = getActivityInfo(comp, flags, userId);
7116                    if (ai == null) {
7117                        continue;
7118                    }
7119                }
7120
7121                // Look for any generic query activities that are duplicates
7122                // of this specific one, and remove them from the results.
7123                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7124                N = results.size();
7125                int j;
7126                for (j=specificsPos; j<N; j++) {
7127                    ResolveInfo sri = results.get(j);
7128                    if ((sri.activityInfo.name.equals(comp.getClassName())
7129                            && sri.activityInfo.applicationInfo.packageName.equals(
7130                                    comp.getPackageName()))
7131                        || (action != null && sri.filter.matchAction(action))) {
7132                        results.remove(j);
7133                        if (DEBUG_INTENT_MATCHING) Log.v(
7134                            TAG, "Removing duplicate item from " + j
7135                            + " due to specific " + specificsPos);
7136                        if (ri == null) {
7137                            ri = sri;
7138                        }
7139                        j--;
7140                        N--;
7141                    }
7142                }
7143
7144                // Add this specific item to its proper place.
7145                if (ri == null) {
7146                    ri = new ResolveInfo();
7147                    ri.activityInfo = ai;
7148                }
7149                results.add(specificsPos, ri);
7150                ri.specificIndex = i;
7151                specificsPos++;
7152            }
7153        }
7154
7155        // Now we go through the remaining generic results and remove any
7156        // duplicate actions that are found here.
7157        N = results.size();
7158        for (int i=specificsPos; i<N-1; i++) {
7159            final ResolveInfo rii = results.get(i);
7160            if (rii.filter == null) {
7161                continue;
7162            }
7163
7164            // Iterate over all of the actions of this result's intent
7165            // filter...  typically this should be just one.
7166            final Iterator<String> it = rii.filter.actionsIterator();
7167            if (it == null) {
7168                continue;
7169            }
7170            while (it.hasNext()) {
7171                final String action = it.next();
7172                if (resultsAction != null && resultsAction.equals(action)) {
7173                    // If this action was explicitly requested, then don't
7174                    // remove things that have it.
7175                    continue;
7176                }
7177                for (int j=i+1; j<N; j++) {
7178                    final ResolveInfo rij = results.get(j);
7179                    if (rij.filter != null && rij.filter.hasAction(action)) {
7180                        results.remove(j);
7181                        if (DEBUG_INTENT_MATCHING) Log.v(
7182                            TAG, "Removing duplicate item from " + j
7183                            + " due to action " + action + " at " + i);
7184                        j--;
7185                        N--;
7186                    }
7187                }
7188            }
7189
7190            // If the caller didn't request filter information, drop it now
7191            // so we don't have to marshall/unmarshall it.
7192            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7193                rii.filter = null;
7194            }
7195        }
7196
7197        // Filter out the caller activity if so requested.
7198        if (caller != null) {
7199            N = results.size();
7200            for (int i=0; i<N; i++) {
7201                ActivityInfo ainfo = results.get(i).activityInfo;
7202                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7203                        && caller.getClassName().equals(ainfo.name)) {
7204                    results.remove(i);
7205                    break;
7206                }
7207            }
7208        }
7209
7210        // If the caller didn't request filter information,
7211        // drop them now so we don't have to
7212        // marshall/unmarshall it.
7213        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7214            N = results.size();
7215            for (int i=0; i<N; i++) {
7216                results.get(i).filter = null;
7217            }
7218        }
7219
7220        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7221        return results;
7222    }
7223
7224    @Override
7225    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7226            String resolvedType, int flags, int userId) {
7227        return new ParceledListSlice<>(
7228                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7229    }
7230
7231    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7232            String resolvedType, int flags, int userId) {
7233        if (!sUserManager.exists(userId)) return Collections.emptyList();
7234        final int callingUid = Binder.getCallingUid();
7235        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7236                false /*includeInstantApps*/);
7237        ComponentName comp = intent.getComponent();
7238        if (comp == null) {
7239            if (intent.getSelector() != null) {
7240                intent = intent.getSelector();
7241                comp = intent.getComponent();
7242            }
7243        }
7244        if (comp != null) {
7245            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7246            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7247            if (ai != null) {
7248                ResolveInfo ri = new ResolveInfo();
7249                ri.activityInfo = ai;
7250                list.add(ri);
7251            }
7252            return list;
7253        }
7254
7255        // reader
7256        synchronized (mPackages) {
7257            String pkgName = intent.getPackage();
7258            if (pkgName == null) {
7259                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7260            }
7261            final PackageParser.Package pkg = mPackages.get(pkgName);
7262            if (pkg != null) {
7263                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7264                        userId);
7265            }
7266            return Collections.emptyList();
7267        }
7268    }
7269
7270    @Override
7271    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7272        final int callingUid = Binder.getCallingUid();
7273        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7274    }
7275
7276    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7277            int userId, int callingUid) {
7278        if (!sUserManager.exists(userId)) return null;
7279        flags = updateFlagsForResolve(
7280                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7281        List<ResolveInfo> query = queryIntentServicesInternal(
7282                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7283        if (query != null) {
7284            if (query.size() >= 1) {
7285                // If there is more than one service with the same priority,
7286                // just arbitrarily pick the first one.
7287                return query.get(0);
7288            }
7289        }
7290        return null;
7291    }
7292
7293    @Override
7294    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7295            String resolvedType, int flags, int userId) {
7296        final int callingUid = Binder.getCallingUid();
7297        return new ParceledListSlice<>(queryIntentServicesInternal(
7298                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7299    }
7300
7301    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7302            String resolvedType, int flags, int userId, int callingUid,
7303            boolean includeInstantApps) {
7304        if (!sUserManager.exists(userId)) return Collections.emptyList();
7305        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7306        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7307        ComponentName comp = intent.getComponent();
7308        if (comp == null) {
7309            if (intent.getSelector() != null) {
7310                intent = intent.getSelector();
7311                comp = intent.getComponent();
7312            }
7313        }
7314        if (comp != null) {
7315            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7316            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7317            if (si != null) {
7318                // When specifying an explicit component, we prevent the service from being
7319                // used when either 1) the service is in an instant application and the
7320                // caller is not the same instant application or 2) the calling package is
7321                // ephemeral and the activity is not visible to ephemeral applications.
7322                final boolean matchInstantApp =
7323                        (flags & PackageManager.MATCH_INSTANT) != 0;
7324                final boolean matchVisibleToInstantAppOnly =
7325                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7326                final boolean isCallerInstantApp =
7327                        instantAppPkgName != null;
7328                final boolean isTargetSameInstantApp =
7329                        comp.getPackageName().equals(instantAppPkgName);
7330                final boolean isTargetInstantApp =
7331                        (si.applicationInfo.privateFlags
7332                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7333                final boolean isTargetHiddenFromInstantApp =
7334                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7335                final boolean blockResolution =
7336                        !isTargetSameInstantApp
7337                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7338                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7339                                        && isTargetHiddenFromInstantApp));
7340                if (!blockResolution) {
7341                    final ResolveInfo ri = new ResolveInfo();
7342                    ri.serviceInfo = si;
7343                    list.add(ri);
7344                }
7345            }
7346            return list;
7347        }
7348
7349        // reader
7350        synchronized (mPackages) {
7351            String pkgName = intent.getPackage();
7352            if (pkgName == null) {
7353                return applyPostServiceResolutionFilter(
7354                        mServices.queryIntent(intent, resolvedType, flags, userId),
7355                        instantAppPkgName);
7356            }
7357            final PackageParser.Package pkg = mPackages.get(pkgName);
7358            if (pkg != null) {
7359                return applyPostServiceResolutionFilter(
7360                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7361                                userId),
7362                        instantAppPkgName);
7363            }
7364            return Collections.emptyList();
7365        }
7366    }
7367
7368    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7369            String instantAppPkgName) {
7370        // TODO: When adding on-demand split support for non-instant apps, remove this check
7371        // and always apply post filtering
7372        if (instantAppPkgName == null) {
7373            return resolveInfos;
7374        }
7375        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7376            final ResolveInfo info = resolveInfos.get(i);
7377            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7378            // allow services that are defined in the provided package
7379            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7380                if (info.serviceInfo.splitName != null
7381                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7382                                info.serviceInfo.splitName)) {
7383                    // requested service is defined in a split that hasn't been installed yet.
7384                    // add the installer to the resolve list
7385                    if (DEBUG_EPHEMERAL) {
7386                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7387                    }
7388                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7389                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7390                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7391                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7392                    // make sure this resolver is the default
7393                    installerInfo.isDefault = true;
7394                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7395                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7396                    // add a non-generic filter
7397                    installerInfo.filter = new IntentFilter();
7398                    // load resources from the correct package
7399                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7400                    resolveInfos.set(i, installerInfo);
7401                }
7402                continue;
7403            }
7404            // allow services that have been explicitly exposed to ephemeral apps
7405            if (!isEphemeralApp
7406                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7407                continue;
7408            }
7409            resolveInfos.remove(i);
7410        }
7411        return resolveInfos;
7412    }
7413
7414    @Override
7415    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7416            String resolvedType, int flags, int userId) {
7417        return new ParceledListSlice<>(
7418                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7419    }
7420
7421    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7422            Intent intent, String resolvedType, int flags, int userId) {
7423        if (!sUserManager.exists(userId)) return Collections.emptyList();
7424        final int callingUid = Binder.getCallingUid();
7425        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7426        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7427                false /*includeInstantApps*/);
7428        ComponentName comp = intent.getComponent();
7429        if (comp == null) {
7430            if (intent.getSelector() != null) {
7431                intent = intent.getSelector();
7432                comp = intent.getComponent();
7433            }
7434        }
7435        if (comp != null) {
7436            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7437            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7438            if (pi != null) {
7439                // When specifying an explicit component, we prevent the provider from being
7440                // used when either 1) the provider is in an instant application and the
7441                // caller is not the same instant application or 2) the calling package is an
7442                // instant application and the provider is not visible to instant applications.
7443                final boolean matchInstantApp =
7444                        (flags & PackageManager.MATCH_INSTANT) != 0;
7445                final boolean matchVisibleToInstantAppOnly =
7446                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7447                final boolean isCallerInstantApp =
7448                        instantAppPkgName != null;
7449                final boolean isTargetSameInstantApp =
7450                        comp.getPackageName().equals(instantAppPkgName);
7451                final boolean isTargetInstantApp =
7452                        (pi.applicationInfo.privateFlags
7453                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7454                final boolean isTargetHiddenFromInstantApp =
7455                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7456                final boolean blockResolution =
7457                        !isTargetSameInstantApp
7458                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7459                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7460                                        && isTargetHiddenFromInstantApp));
7461                if (!blockResolution) {
7462                    final ResolveInfo ri = new ResolveInfo();
7463                    ri.providerInfo = pi;
7464                    list.add(ri);
7465                }
7466            }
7467            return list;
7468        }
7469
7470        // reader
7471        synchronized (mPackages) {
7472            String pkgName = intent.getPackage();
7473            if (pkgName == null) {
7474                return applyPostContentProviderResolutionFilter(
7475                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7476                        instantAppPkgName);
7477            }
7478            final PackageParser.Package pkg = mPackages.get(pkgName);
7479            if (pkg != null) {
7480                return applyPostContentProviderResolutionFilter(
7481                        mProviders.queryIntentForPackage(
7482                        intent, resolvedType, flags, pkg.providers, userId),
7483                        instantAppPkgName);
7484            }
7485            return Collections.emptyList();
7486        }
7487    }
7488
7489    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7490            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7491        // TODO: When adding on-demand split support for non-instant applications, remove
7492        // this check and always apply post filtering
7493        if (instantAppPkgName == null) {
7494            return resolveInfos;
7495        }
7496        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7497            final ResolveInfo info = resolveInfos.get(i);
7498            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7499            // allow providers that are defined in the provided package
7500            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7501                if (info.providerInfo.splitName != null
7502                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7503                                info.providerInfo.splitName)) {
7504                    // requested provider is defined in a split that hasn't been installed yet.
7505                    // add the installer to the resolve list
7506                    if (DEBUG_EPHEMERAL) {
7507                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7508                    }
7509                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7510                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7511                            info.providerInfo.packageName, info.providerInfo.splitName,
7512                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
7513                    // make sure this resolver is the default
7514                    installerInfo.isDefault = true;
7515                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7516                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7517                    // add a non-generic filter
7518                    installerInfo.filter = new IntentFilter();
7519                    // load resources from the correct package
7520                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7521                    resolveInfos.set(i, installerInfo);
7522                }
7523                continue;
7524            }
7525            // allow providers that have been explicitly exposed to instant applications
7526            if (!isEphemeralApp
7527                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7528                continue;
7529            }
7530            resolveInfos.remove(i);
7531        }
7532        return resolveInfos;
7533    }
7534
7535    @Override
7536    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7537        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7538        flags = updateFlagsForPackage(flags, userId, null);
7539        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7540        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7541                true /* requireFullPermission */, false /* checkShell */,
7542                "get installed packages");
7543
7544        // writer
7545        synchronized (mPackages) {
7546            ArrayList<PackageInfo> list;
7547            if (listUninstalled) {
7548                list = new ArrayList<>(mSettings.mPackages.size());
7549                for (PackageSetting ps : mSettings.mPackages.values()) {
7550                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7551                        continue;
7552                    }
7553                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7554                    if (pi != null) {
7555                        list.add(pi);
7556                    }
7557                }
7558            } else {
7559                list = new ArrayList<>(mPackages.size());
7560                for (PackageParser.Package p : mPackages.values()) {
7561                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7562                            Binder.getCallingUid(), userId)) {
7563                        continue;
7564                    }
7565                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7566                            p.mExtras, flags, userId);
7567                    if (pi != null) {
7568                        list.add(pi);
7569                    }
7570                }
7571            }
7572
7573            return new ParceledListSlice<>(list);
7574        }
7575    }
7576
7577    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7578            String[] permissions, boolean[] tmp, int flags, int userId) {
7579        int numMatch = 0;
7580        final PermissionsState permissionsState = ps.getPermissionsState();
7581        for (int i=0; i<permissions.length; i++) {
7582            final String permission = permissions[i];
7583            if (permissionsState.hasPermission(permission, userId)) {
7584                tmp[i] = true;
7585                numMatch++;
7586            } else {
7587                tmp[i] = false;
7588            }
7589        }
7590        if (numMatch == 0) {
7591            return;
7592        }
7593        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7594
7595        // The above might return null in cases of uninstalled apps or install-state
7596        // skew across users/profiles.
7597        if (pi != null) {
7598            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7599                if (numMatch == permissions.length) {
7600                    pi.requestedPermissions = permissions;
7601                } else {
7602                    pi.requestedPermissions = new String[numMatch];
7603                    numMatch = 0;
7604                    for (int i=0; i<permissions.length; i++) {
7605                        if (tmp[i]) {
7606                            pi.requestedPermissions[numMatch] = permissions[i];
7607                            numMatch++;
7608                        }
7609                    }
7610                }
7611            }
7612            list.add(pi);
7613        }
7614    }
7615
7616    @Override
7617    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7618            String[] permissions, int flags, int userId) {
7619        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7620        flags = updateFlagsForPackage(flags, userId, permissions);
7621        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7622                true /* requireFullPermission */, false /* checkShell */,
7623                "get packages holding permissions");
7624        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7625
7626        // writer
7627        synchronized (mPackages) {
7628            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7629            boolean[] tmpBools = new boolean[permissions.length];
7630            if (listUninstalled) {
7631                for (PackageSetting ps : mSettings.mPackages.values()) {
7632                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7633                            userId);
7634                }
7635            } else {
7636                for (PackageParser.Package pkg : mPackages.values()) {
7637                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7638                    if (ps != null) {
7639                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7640                                userId);
7641                    }
7642                }
7643            }
7644
7645            return new ParceledListSlice<PackageInfo>(list);
7646        }
7647    }
7648
7649    @Override
7650    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7651        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7652        flags = updateFlagsForApplication(flags, userId, null);
7653        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7654
7655        // writer
7656        synchronized (mPackages) {
7657            ArrayList<ApplicationInfo> list;
7658            if (listUninstalled) {
7659                list = new ArrayList<>(mSettings.mPackages.size());
7660                for (PackageSetting ps : mSettings.mPackages.values()) {
7661                    ApplicationInfo ai;
7662                    int effectiveFlags = flags;
7663                    if (ps.isSystem()) {
7664                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7665                    }
7666                    if (ps.pkg != null) {
7667                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7668                            continue;
7669                        }
7670                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7671                                ps.readUserState(userId), userId);
7672                        if (ai != null) {
7673                            rebaseEnabledOverlays(ai, userId);
7674                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7675                        }
7676                    } else {
7677                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7678                        // and already converts to externally visible package name
7679                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7680                                Binder.getCallingUid(), effectiveFlags, userId);
7681                    }
7682                    if (ai != null) {
7683                        list.add(ai);
7684                    }
7685                }
7686            } else {
7687                list = new ArrayList<>(mPackages.size());
7688                for (PackageParser.Package p : mPackages.values()) {
7689                    if (p.mExtras != null) {
7690                        PackageSetting ps = (PackageSetting) p.mExtras;
7691                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7692                            continue;
7693                        }
7694                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7695                                ps.readUserState(userId), userId);
7696                        if (ai != null) {
7697                            rebaseEnabledOverlays(ai, userId);
7698                            ai.packageName = resolveExternalPackageNameLPr(p);
7699                            list.add(ai);
7700                        }
7701                    }
7702                }
7703            }
7704
7705            return new ParceledListSlice<>(list);
7706        }
7707    }
7708
7709    @Override
7710    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7711        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7712            return null;
7713        }
7714
7715        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7716                "getEphemeralApplications");
7717        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7718                true /* requireFullPermission */, false /* checkShell */,
7719                "getEphemeralApplications");
7720        synchronized (mPackages) {
7721            List<InstantAppInfo> instantApps = mInstantAppRegistry
7722                    .getInstantAppsLPr(userId);
7723            if (instantApps != null) {
7724                return new ParceledListSlice<>(instantApps);
7725            }
7726        }
7727        return null;
7728    }
7729
7730    @Override
7731    public boolean isInstantApp(String packageName, int userId) {
7732        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7733                true /* requireFullPermission */, false /* checkShell */,
7734                "isInstantApp");
7735        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7736            return false;
7737        }
7738        int uid = Binder.getCallingUid();
7739        if (Process.isIsolated(uid)) {
7740            uid = mIsolatedOwners.get(uid);
7741        }
7742
7743        synchronized (mPackages) {
7744            final PackageSetting ps = mSettings.mPackages.get(packageName);
7745            PackageParser.Package pkg = mPackages.get(packageName);
7746            final boolean returnAllowed =
7747                    ps != null
7748                    && (isCallerSameApp(packageName, uid)
7749                            || mContext.checkCallingOrSelfPermission(
7750                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7751                                            == PERMISSION_GRANTED
7752                            || mInstantAppRegistry.isInstantAccessGranted(
7753                                    userId, UserHandle.getAppId(uid), ps.appId));
7754            if (returnAllowed) {
7755                return ps.getInstantApp(userId);
7756            }
7757        }
7758        return false;
7759    }
7760
7761    @Override
7762    public byte[] getInstantAppCookie(String packageName, int userId) {
7763        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7764            return null;
7765        }
7766
7767        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7768                true /* requireFullPermission */, false /* checkShell */,
7769                "getInstantAppCookie");
7770        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7771            return null;
7772        }
7773        synchronized (mPackages) {
7774            return mInstantAppRegistry.getInstantAppCookieLPw(
7775                    packageName, userId);
7776        }
7777    }
7778
7779    @Override
7780    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7781        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7782            return true;
7783        }
7784
7785        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7786                true /* requireFullPermission */, true /* checkShell */,
7787                "setInstantAppCookie");
7788        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7789            return false;
7790        }
7791        synchronized (mPackages) {
7792            return mInstantAppRegistry.setInstantAppCookieLPw(
7793                    packageName, cookie, userId);
7794        }
7795    }
7796
7797    @Override
7798    public Bitmap getInstantAppIcon(String packageName, int userId) {
7799        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7800            return null;
7801        }
7802
7803        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7804                "getInstantAppIcon");
7805
7806        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7807                true /* requireFullPermission */, false /* checkShell */,
7808                "getInstantAppIcon");
7809
7810        synchronized (mPackages) {
7811            return mInstantAppRegistry.getInstantAppIconLPw(
7812                    packageName, userId);
7813        }
7814    }
7815
7816    private boolean isCallerSameApp(String packageName, int uid) {
7817        PackageParser.Package pkg = mPackages.get(packageName);
7818        return pkg != null
7819                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7820    }
7821
7822    @Override
7823    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7824        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7825    }
7826
7827    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7828        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7829
7830        // reader
7831        synchronized (mPackages) {
7832            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7833            final int userId = UserHandle.getCallingUserId();
7834            while (i.hasNext()) {
7835                final PackageParser.Package p = i.next();
7836                if (p.applicationInfo == null) continue;
7837
7838                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7839                        && !p.applicationInfo.isDirectBootAware();
7840                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7841                        && p.applicationInfo.isDirectBootAware();
7842
7843                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7844                        && (!mSafeMode || isSystemApp(p))
7845                        && (matchesUnaware || matchesAware)) {
7846                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7847                    if (ps != null) {
7848                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7849                                ps.readUserState(userId), userId);
7850                        if (ai != null) {
7851                            rebaseEnabledOverlays(ai, userId);
7852                            finalList.add(ai);
7853                        }
7854                    }
7855                }
7856            }
7857        }
7858
7859        return finalList;
7860    }
7861
7862    @Override
7863    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7864        if (!sUserManager.exists(userId)) return null;
7865        flags = updateFlagsForComponent(flags, userId, name);
7866        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7867        // reader
7868        synchronized (mPackages) {
7869            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7870            PackageSetting ps = provider != null
7871                    ? mSettings.mPackages.get(provider.owner.packageName)
7872                    : null;
7873            if (ps != null) {
7874                final boolean isInstantApp = ps.getInstantApp(userId);
7875                // normal application; filter out instant application provider
7876                if (instantAppPkgName == null && isInstantApp) {
7877                    return null;
7878                }
7879                // instant application; filter out other instant applications
7880                if (instantAppPkgName != null
7881                        && isInstantApp
7882                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7883                    return null;
7884                }
7885                // instant application; filter out non-exposed provider
7886                if (instantAppPkgName != null
7887                        && !isInstantApp
7888                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
7889                    return null;
7890                }
7891                // provider not enabled
7892                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7893                    return null;
7894                }
7895                return PackageParser.generateProviderInfo(
7896                        provider, flags, ps.readUserState(userId), userId);
7897            }
7898            return null;
7899        }
7900    }
7901
7902    /**
7903     * @deprecated
7904     */
7905    @Deprecated
7906    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7907        // reader
7908        synchronized (mPackages) {
7909            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7910                    .entrySet().iterator();
7911            final int userId = UserHandle.getCallingUserId();
7912            while (i.hasNext()) {
7913                Map.Entry<String, PackageParser.Provider> entry = i.next();
7914                PackageParser.Provider p = entry.getValue();
7915                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7916
7917                if (ps != null && p.syncable
7918                        && (!mSafeMode || (p.info.applicationInfo.flags
7919                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7920                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7921                            ps.readUserState(userId), userId);
7922                    if (info != null) {
7923                        outNames.add(entry.getKey());
7924                        outInfo.add(info);
7925                    }
7926                }
7927            }
7928        }
7929    }
7930
7931    @Override
7932    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7933            int uid, int flags, String metaDataKey) {
7934        final int userId = processName != null ? UserHandle.getUserId(uid)
7935                : UserHandle.getCallingUserId();
7936        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7937        flags = updateFlagsForComponent(flags, userId, processName);
7938
7939        ArrayList<ProviderInfo> finalList = null;
7940        // reader
7941        synchronized (mPackages) {
7942            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7943            while (i.hasNext()) {
7944                final PackageParser.Provider p = i.next();
7945                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7946                if (ps != null && p.info.authority != null
7947                        && (processName == null
7948                                || (p.info.processName.equals(processName)
7949                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7950                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7951
7952                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7953                    // parameter.
7954                    if (metaDataKey != null
7955                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7956                        continue;
7957                    }
7958
7959                    if (finalList == null) {
7960                        finalList = new ArrayList<ProviderInfo>(3);
7961                    }
7962                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7963                            ps.readUserState(userId), userId);
7964                    if (info != null) {
7965                        finalList.add(info);
7966                    }
7967                }
7968            }
7969        }
7970
7971        if (finalList != null) {
7972            Collections.sort(finalList, mProviderInitOrderSorter);
7973            return new ParceledListSlice<ProviderInfo>(finalList);
7974        }
7975
7976        return ParceledListSlice.emptyList();
7977    }
7978
7979    @Override
7980    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7981        // reader
7982        synchronized (mPackages) {
7983            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7984            return PackageParser.generateInstrumentationInfo(i, flags);
7985        }
7986    }
7987
7988    @Override
7989    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7990            String targetPackage, int flags) {
7991        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7992    }
7993
7994    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7995            int flags) {
7996        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7997
7998        // reader
7999        synchronized (mPackages) {
8000            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8001            while (i.hasNext()) {
8002                final PackageParser.Instrumentation p = i.next();
8003                if (targetPackage == null
8004                        || targetPackage.equals(p.info.targetPackage)) {
8005                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8006                            flags);
8007                    if (ii != null) {
8008                        finalList.add(ii);
8009                    }
8010                }
8011            }
8012        }
8013
8014        return finalList;
8015    }
8016
8017    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8018        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8019        try {
8020            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8021        } finally {
8022            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8023        }
8024    }
8025
8026    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8027        final File[] files = dir.listFiles();
8028        if (ArrayUtils.isEmpty(files)) {
8029            Log.d(TAG, "No files in app dir " + dir);
8030            return;
8031        }
8032
8033        if (DEBUG_PACKAGE_SCANNING) {
8034            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8035                    + " flags=0x" + Integer.toHexString(parseFlags));
8036        }
8037        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8038                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8039                mParallelPackageParserCallback);
8040
8041        // Submit files for parsing in parallel
8042        int fileCount = 0;
8043        for (File file : files) {
8044            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8045                    && !PackageInstallerService.isStageName(file.getName());
8046            if (!isPackage) {
8047                // Ignore entries which are not packages
8048                continue;
8049            }
8050            parallelPackageParser.submit(file, parseFlags);
8051            fileCount++;
8052        }
8053
8054        // Process results one by one
8055        for (; fileCount > 0; fileCount--) {
8056            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8057            Throwable throwable = parseResult.throwable;
8058            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8059
8060            if (throwable == null) {
8061                // Static shared libraries have synthetic package names
8062                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8063                    renameStaticSharedLibraryPackage(parseResult.pkg);
8064                }
8065                try {
8066                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8067                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8068                                currentTime, null);
8069                    }
8070                } catch (PackageManagerException e) {
8071                    errorCode = e.error;
8072                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8073                }
8074            } else if (throwable instanceof PackageParser.PackageParserException) {
8075                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8076                        throwable;
8077                errorCode = e.error;
8078                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8079            } else {
8080                throw new IllegalStateException("Unexpected exception occurred while parsing "
8081                        + parseResult.scanFile, throwable);
8082            }
8083
8084            // Delete invalid userdata apps
8085            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8086                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8087                logCriticalInfo(Log.WARN,
8088                        "Deleting invalid package at " + parseResult.scanFile);
8089                removeCodePathLI(parseResult.scanFile);
8090            }
8091        }
8092        parallelPackageParser.close();
8093    }
8094
8095    private static File getSettingsProblemFile() {
8096        File dataDir = Environment.getDataDirectory();
8097        File systemDir = new File(dataDir, "system");
8098        File fname = new File(systemDir, "uiderrors.txt");
8099        return fname;
8100    }
8101
8102    static void reportSettingsProblem(int priority, String msg) {
8103        logCriticalInfo(priority, msg);
8104    }
8105
8106    public static void logCriticalInfo(int priority, String msg) {
8107        Slog.println(priority, TAG, msg);
8108        EventLogTags.writePmCriticalInfo(msg);
8109        try {
8110            File fname = getSettingsProblemFile();
8111            FileOutputStream out = new FileOutputStream(fname, true);
8112            PrintWriter pw = new FastPrintWriter(out);
8113            SimpleDateFormat formatter = new SimpleDateFormat();
8114            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8115            pw.println(dateString + ": " + msg);
8116            pw.close();
8117            FileUtils.setPermissions(
8118                    fname.toString(),
8119                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8120                    -1, -1);
8121        } catch (java.io.IOException e) {
8122        }
8123    }
8124
8125    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8126        if (srcFile.isDirectory()) {
8127            final File baseFile = new File(pkg.baseCodePath);
8128            long maxModifiedTime = baseFile.lastModified();
8129            if (pkg.splitCodePaths != null) {
8130                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8131                    final File splitFile = new File(pkg.splitCodePaths[i]);
8132                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8133                }
8134            }
8135            return maxModifiedTime;
8136        }
8137        return srcFile.lastModified();
8138    }
8139
8140    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8141            final int policyFlags) throws PackageManagerException {
8142        // When upgrading from pre-N MR1, verify the package time stamp using the package
8143        // directory and not the APK file.
8144        final long lastModifiedTime = mIsPreNMR1Upgrade
8145                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8146        if (ps != null
8147                && ps.codePath.equals(srcFile)
8148                && ps.timeStamp == lastModifiedTime
8149                && !isCompatSignatureUpdateNeeded(pkg)
8150                && !isRecoverSignatureUpdateNeeded(pkg)) {
8151            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8152            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8153            ArraySet<PublicKey> signingKs;
8154            synchronized (mPackages) {
8155                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8156            }
8157            if (ps.signatures.mSignatures != null
8158                    && ps.signatures.mSignatures.length != 0
8159                    && signingKs != null) {
8160                // Optimization: reuse the existing cached certificates
8161                // if the package appears to be unchanged.
8162                pkg.mSignatures = ps.signatures.mSignatures;
8163                pkg.mSigningKeys = signingKs;
8164                return;
8165            }
8166
8167            Slog.w(TAG, "PackageSetting for " + ps.name
8168                    + " is missing signatures.  Collecting certs again to recover them.");
8169        } else {
8170            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8171        }
8172
8173        try {
8174            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8175            PackageParser.collectCertificates(pkg, policyFlags);
8176        } catch (PackageParserException e) {
8177            throw PackageManagerException.from(e);
8178        } finally {
8179            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8180        }
8181    }
8182
8183    /**
8184     *  Traces a package scan.
8185     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8186     */
8187    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8188            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8189        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8190        try {
8191            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8192        } finally {
8193            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8194        }
8195    }
8196
8197    /**
8198     *  Scans a package and returns the newly parsed package.
8199     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8200     */
8201    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8202            long currentTime, UserHandle user) throws PackageManagerException {
8203        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8204        PackageParser pp = new PackageParser();
8205        pp.setSeparateProcesses(mSeparateProcesses);
8206        pp.setOnlyCoreApps(mOnlyCore);
8207        pp.setDisplayMetrics(mMetrics);
8208        pp.setCallback(mPackageParserCallback);
8209
8210        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8211            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8212        }
8213
8214        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8215        final PackageParser.Package pkg;
8216        try {
8217            pkg = pp.parsePackage(scanFile, parseFlags);
8218        } catch (PackageParserException e) {
8219            throw PackageManagerException.from(e);
8220        } finally {
8221            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8222        }
8223
8224        // Static shared libraries have synthetic package names
8225        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8226            renameStaticSharedLibraryPackage(pkg);
8227        }
8228
8229        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8230    }
8231
8232    /**
8233     *  Scans a package and returns the newly parsed package.
8234     *  @throws PackageManagerException on a parse error.
8235     */
8236    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8237            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8238            throws PackageManagerException {
8239        // If the package has children and this is the first dive in the function
8240        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8241        // packages (parent and children) would be successfully scanned before the
8242        // actual scan since scanning mutates internal state and we want to atomically
8243        // install the package and its children.
8244        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8245            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8246                scanFlags |= SCAN_CHECK_ONLY;
8247            }
8248        } else {
8249            scanFlags &= ~SCAN_CHECK_ONLY;
8250        }
8251
8252        // Scan the parent
8253        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8254                scanFlags, currentTime, user);
8255
8256        // Scan the children
8257        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8258        for (int i = 0; i < childCount; i++) {
8259            PackageParser.Package childPackage = pkg.childPackages.get(i);
8260            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8261                    currentTime, user);
8262        }
8263
8264
8265        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8266            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8267        }
8268
8269        return scannedPkg;
8270    }
8271
8272    /**
8273     *  Scans a package and returns the newly parsed package.
8274     *  @throws PackageManagerException on a parse error.
8275     */
8276    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8277            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8278            throws PackageManagerException {
8279        PackageSetting ps = null;
8280        PackageSetting updatedPkg;
8281        // reader
8282        synchronized (mPackages) {
8283            // Look to see if we already know about this package.
8284            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8285            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8286                // This package has been renamed to its original name.  Let's
8287                // use that.
8288                ps = mSettings.getPackageLPr(oldName);
8289            }
8290            // If there was no original package, see one for the real package name.
8291            if (ps == null) {
8292                ps = mSettings.getPackageLPr(pkg.packageName);
8293            }
8294            // Check to see if this package could be hiding/updating a system
8295            // package.  Must look for it either under the original or real
8296            // package name depending on our state.
8297            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8298            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8299
8300            // If this is a package we don't know about on the system partition, we
8301            // may need to remove disabled child packages on the system partition
8302            // or may need to not add child packages if the parent apk is updated
8303            // on the data partition and no longer defines this child package.
8304            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8305                // If this is a parent package for an updated system app and this system
8306                // app got an OTA update which no longer defines some of the child packages
8307                // we have to prune them from the disabled system packages.
8308                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8309                if (disabledPs != null) {
8310                    final int scannedChildCount = (pkg.childPackages != null)
8311                            ? pkg.childPackages.size() : 0;
8312                    final int disabledChildCount = disabledPs.childPackageNames != null
8313                            ? disabledPs.childPackageNames.size() : 0;
8314                    for (int i = 0; i < disabledChildCount; i++) {
8315                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8316                        boolean disabledPackageAvailable = false;
8317                        for (int j = 0; j < scannedChildCount; j++) {
8318                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8319                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8320                                disabledPackageAvailable = true;
8321                                break;
8322                            }
8323                         }
8324                         if (!disabledPackageAvailable) {
8325                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8326                         }
8327                    }
8328                }
8329            }
8330        }
8331
8332        boolean updatedPkgBetter = false;
8333        // First check if this is a system package that may involve an update
8334        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8335            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8336            // it needs to drop FLAG_PRIVILEGED.
8337            if (locationIsPrivileged(scanFile)) {
8338                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8339            } else {
8340                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8341            }
8342
8343            if (ps != null && !ps.codePath.equals(scanFile)) {
8344                // The path has changed from what was last scanned...  check the
8345                // version of the new path against what we have stored to determine
8346                // what to do.
8347                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8348                if (pkg.mVersionCode <= ps.versionCode) {
8349                    // The system package has been updated and the code path does not match
8350                    // Ignore entry. Skip it.
8351                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8352                            + " ignored: updated version " + ps.versionCode
8353                            + " better than this " + pkg.mVersionCode);
8354                    if (!updatedPkg.codePath.equals(scanFile)) {
8355                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8356                                + ps.name + " changing from " + updatedPkg.codePathString
8357                                + " to " + scanFile);
8358                        updatedPkg.codePath = scanFile;
8359                        updatedPkg.codePathString = scanFile.toString();
8360                        updatedPkg.resourcePath = scanFile;
8361                        updatedPkg.resourcePathString = scanFile.toString();
8362                    }
8363                    updatedPkg.pkg = pkg;
8364                    updatedPkg.versionCode = pkg.mVersionCode;
8365
8366                    // Update the disabled system child packages to point to the package too.
8367                    final int childCount = updatedPkg.childPackageNames != null
8368                            ? updatedPkg.childPackageNames.size() : 0;
8369                    for (int i = 0; i < childCount; i++) {
8370                        String childPackageName = updatedPkg.childPackageNames.get(i);
8371                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8372                                childPackageName);
8373                        if (updatedChildPkg != null) {
8374                            updatedChildPkg.pkg = pkg;
8375                            updatedChildPkg.versionCode = pkg.mVersionCode;
8376                        }
8377                    }
8378
8379                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8380                            + scanFile + " ignored: updated version " + ps.versionCode
8381                            + " better than this " + pkg.mVersionCode);
8382                } else {
8383                    // The current app on the system partition is better than
8384                    // what we have updated to on the data partition; switch
8385                    // back to the system partition version.
8386                    // At this point, its safely assumed that package installation for
8387                    // apps in system partition will go through. If not there won't be a working
8388                    // version of the app
8389                    // writer
8390                    synchronized (mPackages) {
8391                        // Just remove the loaded entries from package lists.
8392                        mPackages.remove(ps.name);
8393                    }
8394
8395                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8396                            + " reverting from " + ps.codePathString
8397                            + ": new version " + pkg.mVersionCode
8398                            + " better than installed " + ps.versionCode);
8399
8400                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8401                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8402                    synchronized (mInstallLock) {
8403                        args.cleanUpResourcesLI();
8404                    }
8405                    synchronized (mPackages) {
8406                        mSettings.enableSystemPackageLPw(ps.name);
8407                    }
8408                    updatedPkgBetter = true;
8409                }
8410            }
8411        }
8412
8413        if (updatedPkg != null) {
8414            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8415            // initially
8416            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8417
8418            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8419            // flag set initially
8420            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8421                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8422            }
8423        }
8424
8425        // Verify certificates against what was last scanned
8426        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8427
8428        /*
8429         * A new system app appeared, but we already had a non-system one of the
8430         * same name installed earlier.
8431         */
8432        boolean shouldHideSystemApp = false;
8433        if (updatedPkg == null && ps != null
8434                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8435            /*
8436             * Check to make sure the signatures match first. If they don't,
8437             * wipe the installed application and its data.
8438             */
8439            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8440                    != PackageManager.SIGNATURE_MATCH) {
8441                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8442                        + " signatures don't match existing userdata copy; removing");
8443                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8444                        "scanPackageInternalLI")) {
8445                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8446                }
8447                ps = null;
8448            } else {
8449                /*
8450                 * If the newly-added system app is an older version than the
8451                 * already installed version, hide it. It will be scanned later
8452                 * and re-added like an update.
8453                 */
8454                if (pkg.mVersionCode <= ps.versionCode) {
8455                    shouldHideSystemApp = true;
8456                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8457                            + " but new version " + pkg.mVersionCode + " better than installed "
8458                            + ps.versionCode + "; hiding system");
8459                } else {
8460                    /*
8461                     * The newly found system app is a newer version that the
8462                     * one previously installed. Simply remove the
8463                     * already-installed application and replace it with our own
8464                     * while keeping the application data.
8465                     */
8466                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8467                            + " reverting from " + ps.codePathString + ": new version "
8468                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8469                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8470                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8471                    synchronized (mInstallLock) {
8472                        args.cleanUpResourcesLI();
8473                    }
8474                }
8475            }
8476        }
8477
8478        // The apk is forward locked (not public) if its code and resources
8479        // are kept in different files. (except for app in either system or
8480        // vendor path).
8481        // TODO grab this value from PackageSettings
8482        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8483            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8484                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8485            }
8486        }
8487
8488        // TODO: extend to support forward-locked splits
8489        String resourcePath = null;
8490        String baseResourcePath = null;
8491        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8492            if (ps != null && ps.resourcePathString != null) {
8493                resourcePath = ps.resourcePathString;
8494                baseResourcePath = ps.resourcePathString;
8495            } else {
8496                // Should not happen at all. Just log an error.
8497                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8498            }
8499        } else {
8500            resourcePath = pkg.codePath;
8501            baseResourcePath = pkg.baseCodePath;
8502        }
8503
8504        // Set application objects path explicitly.
8505        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8506        pkg.setApplicationInfoCodePath(pkg.codePath);
8507        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8508        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8509        pkg.setApplicationInfoResourcePath(resourcePath);
8510        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8511        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8512
8513        final int userId = ((user == null) ? 0 : user.getIdentifier());
8514        if (ps != null && ps.getInstantApp(userId)) {
8515            scanFlags |= SCAN_AS_INSTANT_APP;
8516        }
8517
8518        // Note that we invoke the following method only if we are about to unpack an application
8519        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8520                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8521
8522        /*
8523         * If the system app should be overridden by a previously installed
8524         * data, hide the system app now and let the /data/app scan pick it up
8525         * again.
8526         */
8527        if (shouldHideSystemApp) {
8528            synchronized (mPackages) {
8529                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8530            }
8531        }
8532
8533        return scannedPkg;
8534    }
8535
8536    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8537        // Derive the new package synthetic package name
8538        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8539                + pkg.staticSharedLibVersion);
8540    }
8541
8542    private static String fixProcessName(String defProcessName,
8543            String processName) {
8544        if (processName == null) {
8545            return defProcessName;
8546        }
8547        return processName;
8548    }
8549
8550    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8551            throws PackageManagerException {
8552        if (pkgSetting.signatures.mSignatures != null) {
8553            // Already existing package. Make sure signatures match
8554            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8555                    == PackageManager.SIGNATURE_MATCH;
8556            if (!match) {
8557                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8558                        == PackageManager.SIGNATURE_MATCH;
8559            }
8560            if (!match) {
8561                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8562                        == PackageManager.SIGNATURE_MATCH;
8563            }
8564            if (!match) {
8565                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8566                        + pkg.packageName + " signatures do not match the "
8567                        + "previously installed version; ignoring!");
8568            }
8569        }
8570
8571        // Check for shared user signatures
8572        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8573            // Already existing package. Make sure signatures match
8574            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8575                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8576            if (!match) {
8577                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8578                        == PackageManager.SIGNATURE_MATCH;
8579            }
8580            if (!match) {
8581                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8582                        == PackageManager.SIGNATURE_MATCH;
8583            }
8584            if (!match) {
8585                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8586                        "Package " + pkg.packageName
8587                        + " has no signatures that match those in shared user "
8588                        + pkgSetting.sharedUser.name + "; ignoring!");
8589            }
8590        }
8591    }
8592
8593    /**
8594     * Enforces that only the system UID or root's UID can call a method exposed
8595     * via Binder.
8596     *
8597     * @param message used as message if SecurityException is thrown
8598     * @throws SecurityException if the caller is not system or root
8599     */
8600    private static final void enforceSystemOrRoot(String message) {
8601        final int uid = Binder.getCallingUid();
8602        if (uid != Process.SYSTEM_UID && uid != 0) {
8603            throw new SecurityException(message);
8604        }
8605    }
8606
8607    @Override
8608    public void performFstrimIfNeeded() {
8609        enforceSystemOrRoot("Only the system can request fstrim");
8610
8611        // Before everything else, see whether we need to fstrim.
8612        try {
8613            IStorageManager sm = PackageHelper.getStorageManager();
8614            if (sm != null) {
8615                boolean doTrim = false;
8616                final long interval = android.provider.Settings.Global.getLong(
8617                        mContext.getContentResolver(),
8618                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8619                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8620                if (interval > 0) {
8621                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8622                    if (timeSinceLast > interval) {
8623                        doTrim = true;
8624                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8625                                + "; running immediately");
8626                    }
8627                }
8628                if (doTrim) {
8629                    final boolean dexOptDialogShown;
8630                    synchronized (mPackages) {
8631                        dexOptDialogShown = mDexOptDialogShown;
8632                    }
8633                    if (!isFirstBoot() && dexOptDialogShown) {
8634                        try {
8635                            ActivityManager.getService().showBootMessage(
8636                                    mContext.getResources().getString(
8637                                            R.string.android_upgrading_fstrim), true);
8638                        } catch (RemoteException e) {
8639                        }
8640                    }
8641                    sm.runMaintenance();
8642                }
8643            } else {
8644                Slog.e(TAG, "storageManager service unavailable!");
8645            }
8646        } catch (RemoteException e) {
8647            // Can't happen; StorageManagerService is local
8648        }
8649    }
8650
8651    @Override
8652    public void updatePackagesIfNeeded() {
8653        enforceSystemOrRoot("Only the system can request package update");
8654
8655        // We need to re-extract after an OTA.
8656        boolean causeUpgrade = isUpgrade();
8657
8658        // First boot or factory reset.
8659        // Note: we also handle devices that are upgrading to N right now as if it is their
8660        //       first boot, as they do not have profile data.
8661        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8662
8663        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8664        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8665
8666        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8667            return;
8668        }
8669
8670        List<PackageParser.Package> pkgs;
8671        synchronized (mPackages) {
8672            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8673        }
8674
8675        final long startTime = System.nanoTime();
8676        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8677                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8678
8679        final int elapsedTimeSeconds =
8680                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8681
8682        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8683        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8684        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8685        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8686        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8687    }
8688
8689    /**
8690     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8691     * containing statistics about the invocation. The array consists of three elements,
8692     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8693     * and {@code numberOfPackagesFailed}.
8694     */
8695    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8696            String compilerFilter) {
8697
8698        int numberOfPackagesVisited = 0;
8699        int numberOfPackagesOptimized = 0;
8700        int numberOfPackagesSkipped = 0;
8701        int numberOfPackagesFailed = 0;
8702        final int numberOfPackagesToDexopt = pkgs.size();
8703
8704        for (PackageParser.Package pkg : pkgs) {
8705            numberOfPackagesVisited++;
8706
8707            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8708                if (DEBUG_DEXOPT) {
8709                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8710                }
8711                numberOfPackagesSkipped++;
8712                continue;
8713            }
8714
8715            if (DEBUG_DEXOPT) {
8716                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8717                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8718            }
8719
8720            if (showDialog) {
8721                try {
8722                    ActivityManager.getService().showBootMessage(
8723                            mContext.getResources().getString(R.string.android_upgrading_apk,
8724                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8725                } catch (RemoteException e) {
8726                }
8727                synchronized (mPackages) {
8728                    mDexOptDialogShown = true;
8729                }
8730            }
8731
8732            // If the OTA updates a system app which was previously preopted to a non-preopted state
8733            // the app might end up being verified at runtime. That's because by default the apps
8734            // are verify-profile but for preopted apps there's no profile.
8735            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8736            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8737            // filter (by default 'quicken').
8738            // Note that at this stage unused apps are already filtered.
8739            if (isSystemApp(pkg) &&
8740                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8741                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8742                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8743            }
8744
8745            // checkProfiles is false to avoid merging profiles during boot which
8746            // might interfere with background compilation (b/28612421).
8747            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8748            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8749            // trade-off worth doing to save boot time work.
8750            int dexOptStatus = performDexOptTraced(pkg.packageName,
8751                    false /* checkProfiles */,
8752                    compilerFilter,
8753                    false /* force */);
8754            switch (dexOptStatus) {
8755                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8756                    numberOfPackagesOptimized++;
8757                    break;
8758                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8759                    numberOfPackagesSkipped++;
8760                    break;
8761                case PackageDexOptimizer.DEX_OPT_FAILED:
8762                    numberOfPackagesFailed++;
8763                    break;
8764                default:
8765                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8766                    break;
8767            }
8768        }
8769
8770        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8771                numberOfPackagesFailed };
8772    }
8773
8774    @Override
8775    public void notifyPackageUse(String packageName, int reason) {
8776        synchronized (mPackages) {
8777            PackageParser.Package p = mPackages.get(packageName);
8778            if (p == null) {
8779                return;
8780            }
8781            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8782        }
8783    }
8784
8785    @Override
8786    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8787        int userId = UserHandle.getCallingUserId();
8788        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8789        if (ai == null) {
8790            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8791                + loadingPackageName + ", user=" + userId);
8792            return;
8793        }
8794        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8795    }
8796
8797    @Override
8798    public boolean performDexOpt(String packageName,
8799            boolean checkProfiles, int compileReason, boolean force) {
8800        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8801                getCompilerFilterForReason(compileReason), force);
8802        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8803    }
8804
8805    @Override
8806    public boolean performDexOptMode(String packageName,
8807            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8808        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8809                targetCompilerFilter, force);
8810        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8811    }
8812
8813    private int performDexOptTraced(String packageName,
8814                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8815        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8816        try {
8817            return performDexOptInternal(packageName, checkProfiles,
8818                    targetCompilerFilter, force);
8819        } finally {
8820            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8821        }
8822    }
8823
8824    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8825    // if the package can now be considered up to date for the given filter.
8826    private int performDexOptInternal(String packageName,
8827                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8828        PackageParser.Package p;
8829        synchronized (mPackages) {
8830            p = mPackages.get(packageName);
8831            if (p == null) {
8832                // Package could not be found. Report failure.
8833                return PackageDexOptimizer.DEX_OPT_FAILED;
8834            }
8835            mPackageUsage.maybeWriteAsync(mPackages);
8836            mCompilerStats.maybeWriteAsync();
8837        }
8838        long callingId = Binder.clearCallingIdentity();
8839        try {
8840            synchronized (mInstallLock) {
8841                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8842                        targetCompilerFilter, force);
8843            }
8844        } finally {
8845            Binder.restoreCallingIdentity(callingId);
8846        }
8847    }
8848
8849    public ArraySet<String> getOptimizablePackages() {
8850        ArraySet<String> pkgs = new ArraySet<String>();
8851        synchronized (mPackages) {
8852            for (PackageParser.Package p : mPackages.values()) {
8853                if (PackageDexOptimizer.canOptimizePackage(p)) {
8854                    pkgs.add(p.packageName);
8855                }
8856            }
8857        }
8858        return pkgs;
8859    }
8860
8861    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8862            boolean checkProfiles, String targetCompilerFilter,
8863            boolean force) {
8864        // Select the dex optimizer based on the force parameter.
8865        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8866        //       allocate an object here.
8867        PackageDexOptimizer pdo = force
8868                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8869                : mPackageDexOptimizer;
8870
8871        // Dexopt all dependencies first. Note: we ignore the return value and march on
8872        // on errors.
8873        // Note that we are going to call performDexOpt on those libraries as many times as
8874        // they are referenced in packages. When we do a batch of performDexOpt (for example
8875        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8876        // and the first package that uses the library will dexopt it. The
8877        // others will see that the compiled code for the library is up to date.
8878        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8879        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8880        if (!deps.isEmpty()) {
8881            for (PackageParser.Package depPackage : deps) {
8882                // TODO: Analyze and investigate if we (should) profile libraries.
8883                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8884                        false /* checkProfiles */,
8885                        targetCompilerFilter,
8886                        getOrCreateCompilerPackageStats(depPackage),
8887                        true /* isUsedByOtherApps */);
8888            }
8889        }
8890        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8891                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8892                mDexManager.isUsedByOtherApps(p.packageName));
8893    }
8894
8895    // Performs dexopt on the used secondary dex files belonging to the given package.
8896    // Returns true if all dex files were process successfully (which could mean either dexopt or
8897    // skip). Returns false if any of the files caused errors.
8898    @Override
8899    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8900            boolean force) {
8901        mDexManager.reconcileSecondaryDexFiles(packageName);
8902        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8903    }
8904
8905    public boolean performDexOptSecondary(String packageName, int compileReason,
8906            boolean force) {
8907        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8908    }
8909
8910    /**
8911     * Reconcile the information we have about the secondary dex files belonging to
8912     * {@code packagName} and the actual dex files. For all dex files that were
8913     * deleted, update the internal records and delete the generated oat files.
8914     */
8915    @Override
8916    public void reconcileSecondaryDexFiles(String packageName) {
8917        mDexManager.reconcileSecondaryDexFiles(packageName);
8918    }
8919
8920    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8921    // a reference there.
8922    /*package*/ DexManager getDexManager() {
8923        return mDexManager;
8924    }
8925
8926    /**
8927     * Execute the background dexopt job immediately.
8928     */
8929    @Override
8930    public boolean runBackgroundDexoptJob() {
8931        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8932    }
8933
8934    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8935        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8936                || p.usesStaticLibraries != null) {
8937            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8938            Set<String> collectedNames = new HashSet<>();
8939            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8940
8941            retValue.remove(p);
8942
8943            return retValue;
8944        } else {
8945            return Collections.emptyList();
8946        }
8947    }
8948
8949    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8950            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8951        if (!collectedNames.contains(p.packageName)) {
8952            collectedNames.add(p.packageName);
8953            collected.add(p);
8954
8955            if (p.usesLibraries != null) {
8956                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8957                        null, collected, collectedNames);
8958            }
8959            if (p.usesOptionalLibraries != null) {
8960                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8961                        null, collected, collectedNames);
8962            }
8963            if (p.usesStaticLibraries != null) {
8964                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8965                        p.usesStaticLibrariesVersions, collected, collectedNames);
8966            }
8967        }
8968    }
8969
8970    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8971            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8972        final int libNameCount = libs.size();
8973        for (int i = 0; i < libNameCount; i++) {
8974            String libName = libs.get(i);
8975            int version = (versions != null && versions.length == libNameCount)
8976                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8977            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8978            if (libPkg != null) {
8979                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8980            }
8981        }
8982    }
8983
8984    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8985        synchronized (mPackages) {
8986            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8987            if (libEntry != null) {
8988                return mPackages.get(libEntry.apk);
8989            }
8990            return null;
8991        }
8992    }
8993
8994    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8995        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8996        if (versionedLib == null) {
8997            return null;
8998        }
8999        return versionedLib.get(version);
9000    }
9001
9002    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9003        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9004                pkg.staticSharedLibName);
9005        if (versionedLib == null) {
9006            return null;
9007        }
9008        int previousLibVersion = -1;
9009        final int versionCount = versionedLib.size();
9010        for (int i = 0; i < versionCount; i++) {
9011            final int libVersion = versionedLib.keyAt(i);
9012            if (libVersion < pkg.staticSharedLibVersion) {
9013                previousLibVersion = Math.max(previousLibVersion, libVersion);
9014            }
9015        }
9016        if (previousLibVersion >= 0) {
9017            return versionedLib.get(previousLibVersion);
9018        }
9019        return null;
9020    }
9021
9022    public void shutdown() {
9023        mPackageUsage.writeNow(mPackages);
9024        mCompilerStats.writeNow();
9025    }
9026
9027    @Override
9028    public void dumpProfiles(String packageName) {
9029        PackageParser.Package pkg;
9030        synchronized (mPackages) {
9031            pkg = mPackages.get(packageName);
9032            if (pkg == null) {
9033                throw new IllegalArgumentException("Unknown package: " + packageName);
9034            }
9035        }
9036        /* Only the shell, root, or the app user should be able to dump profiles. */
9037        int callingUid = Binder.getCallingUid();
9038        if (callingUid != Process.SHELL_UID &&
9039            callingUid != Process.ROOT_UID &&
9040            callingUid != pkg.applicationInfo.uid) {
9041            throw new SecurityException("dumpProfiles");
9042        }
9043
9044        synchronized (mInstallLock) {
9045            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9046            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9047            try {
9048                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9049                String codePaths = TextUtils.join(";", allCodePaths);
9050                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9051            } catch (InstallerException e) {
9052                Slog.w(TAG, "Failed to dump profiles", e);
9053            }
9054            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9055        }
9056    }
9057
9058    @Override
9059    public void forceDexOpt(String packageName) {
9060        enforceSystemOrRoot("forceDexOpt");
9061
9062        PackageParser.Package pkg;
9063        synchronized (mPackages) {
9064            pkg = mPackages.get(packageName);
9065            if (pkg == null) {
9066                throw new IllegalArgumentException("Unknown package: " + packageName);
9067            }
9068        }
9069
9070        synchronized (mInstallLock) {
9071            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9072
9073            // Whoever is calling forceDexOpt wants a compiled package.
9074            // Don't use profiles since that may cause compilation to be skipped.
9075            final int res = performDexOptInternalWithDependenciesLI(pkg,
9076                    false /* checkProfiles */, getDefaultCompilerFilter(),
9077                    true /* force */);
9078
9079            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9080            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9081                throw new IllegalStateException("Failed to dexopt: " + res);
9082            }
9083        }
9084    }
9085
9086    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9087        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9088            Slog.w(TAG, "Unable to update from " + oldPkg.name
9089                    + " to " + newPkg.packageName
9090                    + ": old package not in system partition");
9091            return false;
9092        } else if (mPackages.get(oldPkg.name) != null) {
9093            Slog.w(TAG, "Unable to update from " + oldPkg.name
9094                    + " to " + newPkg.packageName
9095                    + ": old package still exists");
9096            return false;
9097        }
9098        return true;
9099    }
9100
9101    void removeCodePathLI(File codePath) {
9102        if (codePath.isDirectory()) {
9103            try {
9104                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9105            } catch (InstallerException e) {
9106                Slog.w(TAG, "Failed to remove code path", e);
9107            }
9108        } else {
9109            codePath.delete();
9110        }
9111    }
9112
9113    private int[] resolveUserIds(int userId) {
9114        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9115    }
9116
9117    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9118        if (pkg == null) {
9119            Slog.wtf(TAG, "Package was null!", new Throwable());
9120            return;
9121        }
9122        clearAppDataLeafLIF(pkg, userId, flags);
9123        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9124        for (int i = 0; i < childCount; i++) {
9125            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9126        }
9127    }
9128
9129    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9130        final PackageSetting ps;
9131        synchronized (mPackages) {
9132            ps = mSettings.mPackages.get(pkg.packageName);
9133        }
9134        for (int realUserId : resolveUserIds(userId)) {
9135            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9136            try {
9137                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9138                        ceDataInode);
9139            } catch (InstallerException e) {
9140                Slog.w(TAG, String.valueOf(e));
9141            }
9142        }
9143    }
9144
9145    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9146        if (pkg == null) {
9147            Slog.wtf(TAG, "Package was null!", new Throwable());
9148            return;
9149        }
9150        destroyAppDataLeafLIF(pkg, userId, flags);
9151        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9152        for (int i = 0; i < childCount; i++) {
9153            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9154        }
9155    }
9156
9157    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9158        final PackageSetting ps;
9159        synchronized (mPackages) {
9160            ps = mSettings.mPackages.get(pkg.packageName);
9161        }
9162        for (int realUserId : resolveUserIds(userId)) {
9163            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9164            try {
9165                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9166                        ceDataInode);
9167            } catch (InstallerException e) {
9168                Slog.w(TAG, String.valueOf(e));
9169            }
9170            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9171        }
9172    }
9173
9174    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9175        if (pkg == null) {
9176            Slog.wtf(TAG, "Package was null!", new Throwable());
9177            return;
9178        }
9179        destroyAppProfilesLeafLIF(pkg);
9180        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9181        for (int i = 0; i < childCount; i++) {
9182            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9183        }
9184    }
9185
9186    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9187        try {
9188            mInstaller.destroyAppProfiles(pkg.packageName);
9189        } catch (InstallerException e) {
9190            Slog.w(TAG, String.valueOf(e));
9191        }
9192    }
9193
9194    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9195        if (pkg == null) {
9196            Slog.wtf(TAG, "Package was null!", new Throwable());
9197            return;
9198        }
9199        clearAppProfilesLeafLIF(pkg);
9200        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9201        for (int i = 0; i < childCount; i++) {
9202            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9203        }
9204    }
9205
9206    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9207        try {
9208            mInstaller.clearAppProfiles(pkg.packageName);
9209        } catch (InstallerException e) {
9210            Slog.w(TAG, String.valueOf(e));
9211        }
9212    }
9213
9214    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9215            long lastUpdateTime) {
9216        // Set parent install/update time
9217        PackageSetting ps = (PackageSetting) pkg.mExtras;
9218        if (ps != null) {
9219            ps.firstInstallTime = firstInstallTime;
9220            ps.lastUpdateTime = lastUpdateTime;
9221        }
9222        // Set children install/update time
9223        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9224        for (int i = 0; i < childCount; i++) {
9225            PackageParser.Package childPkg = pkg.childPackages.get(i);
9226            ps = (PackageSetting) childPkg.mExtras;
9227            if (ps != null) {
9228                ps.firstInstallTime = firstInstallTime;
9229                ps.lastUpdateTime = lastUpdateTime;
9230            }
9231        }
9232    }
9233
9234    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9235            PackageParser.Package changingLib) {
9236        if (file.path != null) {
9237            usesLibraryFiles.add(file.path);
9238            return;
9239        }
9240        PackageParser.Package p = mPackages.get(file.apk);
9241        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9242            // If we are doing this while in the middle of updating a library apk,
9243            // then we need to make sure to use that new apk for determining the
9244            // dependencies here.  (We haven't yet finished committing the new apk
9245            // to the package manager state.)
9246            if (p == null || p.packageName.equals(changingLib.packageName)) {
9247                p = changingLib;
9248            }
9249        }
9250        if (p != null) {
9251            usesLibraryFiles.addAll(p.getAllCodePaths());
9252        }
9253    }
9254
9255    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9256            PackageParser.Package changingLib) throws PackageManagerException {
9257        if (pkg == null) {
9258            return;
9259        }
9260        ArraySet<String> usesLibraryFiles = null;
9261        if (pkg.usesLibraries != null) {
9262            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9263                    null, null, pkg.packageName, changingLib, true, null);
9264        }
9265        if (pkg.usesStaticLibraries != null) {
9266            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9267                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9268                    pkg.packageName, changingLib, true, usesLibraryFiles);
9269        }
9270        if (pkg.usesOptionalLibraries != null) {
9271            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9272                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9273        }
9274        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9275            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9276        } else {
9277            pkg.usesLibraryFiles = null;
9278        }
9279    }
9280
9281    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9282            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9283            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9284            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9285            throws PackageManagerException {
9286        final int libCount = requestedLibraries.size();
9287        for (int i = 0; i < libCount; i++) {
9288            final String libName = requestedLibraries.get(i);
9289            final int libVersion = requiredVersions != null ? requiredVersions[i]
9290                    : SharedLibraryInfo.VERSION_UNDEFINED;
9291            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9292            if (libEntry == null) {
9293                if (required) {
9294                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9295                            "Package " + packageName + " requires unavailable shared library "
9296                                    + libName + "; failing!");
9297                } else {
9298                    Slog.w(TAG, "Package " + packageName
9299                            + " desires unavailable shared library "
9300                            + libName + "; ignoring!");
9301                }
9302            } else {
9303                if (requiredVersions != null && requiredCertDigests != null) {
9304                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9305                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9306                            "Package " + packageName + " requires unavailable static shared"
9307                                    + " library " + libName + " version "
9308                                    + libEntry.info.getVersion() + "; failing!");
9309                    }
9310
9311                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9312                    if (libPkg == null) {
9313                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9314                                "Package " + packageName + " requires unavailable static shared"
9315                                        + " library; failing!");
9316                    }
9317
9318                    String expectedCertDigest = requiredCertDigests[i];
9319                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9320                                libPkg.mSignatures[0]);
9321                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9322                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9323                                "Package " + packageName + " requires differently signed" +
9324                                        " static shared library; failing!");
9325                    }
9326                }
9327
9328                if (outUsedLibraries == null) {
9329                    outUsedLibraries = new ArraySet<>();
9330                }
9331                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9332            }
9333        }
9334        return outUsedLibraries;
9335    }
9336
9337    private static boolean hasString(List<String> list, List<String> which) {
9338        if (list == null) {
9339            return false;
9340        }
9341        for (int i=list.size()-1; i>=0; i--) {
9342            for (int j=which.size()-1; j>=0; j--) {
9343                if (which.get(j).equals(list.get(i))) {
9344                    return true;
9345                }
9346            }
9347        }
9348        return false;
9349    }
9350
9351    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9352            PackageParser.Package changingPkg) {
9353        ArrayList<PackageParser.Package> res = null;
9354        for (PackageParser.Package pkg : mPackages.values()) {
9355            if (changingPkg != null
9356                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9357                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9358                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9359                            changingPkg.staticSharedLibName)) {
9360                return null;
9361            }
9362            if (res == null) {
9363                res = new ArrayList<>();
9364            }
9365            res.add(pkg);
9366            try {
9367                updateSharedLibrariesLPr(pkg, changingPkg);
9368            } catch (PackageManagerException e) {
9369                // If a system app update or an app and a required lib missing we
9370                // delete the package and for updated system apps keep the data as
9371                // it is better for the user to reinstall than to be in an limbo
9372                // state. Also libs disappearing under an app should never happen
9373                // - just in case.
9374                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9375                    final int flags = pkg.isUpdatedSystemApp()
9376                            ? PackageManager.DELETE_KEEP_DATA : 0;
9377                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9378                            flags , null, true, null);
9379                }
9380                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9381            }
9382        }
9383        return res;
9384    }
9385
9386    /**
9387     * Derive the value of the {@code cpuAbiOverride} based on the provided
9388     * value and an optional stored value from the package settings.
9389     */
9390    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9391        String cpuAbiOverride = null;
9392
9393        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9394            cpuAbiOverride = null;
9395        } else if (abiOverride != null) {
9396            cpuAbiOverride = abiOverride;
9397        } else if (settings != null) {
9398            cpuAbiOverride = settings.cpuAbiOverrideString;
9399        }
9400
9401        return cpuAbiOverride;
9402    }
9403
9404    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9405            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9406                    throws PackageManagerException {
9407        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9408        // If the package has children and this is the first dive in the function
9409        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9410        // whether all packages (parent and children) would be successfully scanned
9411        // before the actual scan since scanning mutates internal state and we want
9412        // to atomically install the package and its children.
9413        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9414            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9415                scanFlags |= SCAN_CHECK_ONLY;
9416            }
9417        } else {
9418            scanFlags &= ~SCAN_CHECK_ONLY;
9419        }
9420
9421        final PackageParser.Package scannedPkg;
9422        try {
9423            // Scan the parent
9424            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9425            // Scan the children
9426            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9427            for (int i = 0; i < childCount; i++) {
9428                PackageParser.Package childPkg = pkg.childPackages.get(i);
9429                scanPackageLI(childPkg, policyFlags,
9430                        scanFlags, currentTime, user);
9431            }
9432        } finally {
9433            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9434        }
9435
9436        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9437            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9438        }
9439
9440        return scannedPkg;
9441    }
9442
9443    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9444            int scanFlags, long currentTime, @Nullable UserHandle user)
9445                    throws PackageManagerException {
9446        boolean success = false;
9447        try {
9448            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9449                    currentTime, user);
9450            success = true;
9451            return res;
9452        } finally {
9453            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9454                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9455                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9456                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9457                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9458            }
9459        }
9460    }
9461
9462    /**
9463     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9464     */
9465    private static boolean apkHasCode(String fileName) {
9466        StrictJarFile jarFile = null;
9467        try {
9468            jarFile = new StrictJarFile(fileName,
9469                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9470            return jarFile.findEntry("classes.dex") != null;
9471        } catch (IOException ignore) {
9472        } finally {
9473            try {
9474                if (jarFile != null) {
9475                    jarFile.close();
9476                }
9477            } catch (IOException ignore) {}
9478        }
9479        return false;
9480    }
9481
9482    /**
9483     * Enforces code policy for the package. This ensures that if an APK has
9484     * declared hasCode="true" in its manifest that the APK actually contains
9485     * code.
9486     *
9487     * @throws PackageManagerException If bytecode could not be found when it should exist
9488     */
9489    private static void assertCodePolicy(PackageParser.Package pkg)
9490            throws PackageManagerException {
9491        final boolean shouldHaveCode =
9492                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9493        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9494            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9495                    "Package " + pkg.baseCodePath + " code is missing");
9496        }
9497
9498        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9499            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9500                final boolean splitShouldHaveCode =
9501                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9502                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9503                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9504                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9505                }
9506            }
9507        }
9508    }
9509
9510    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9511            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9512                    throws PackageManagerException {
9513        if (DEBUG_PACKAGE_SCANNING) {
9514            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9515                Log.d(TAG, "Scanning package " + pkg.packageName);
9516        }
9517
9518        applyPolicy(pkg, policyFlags);
9519
9520        assertPackageIsValid(pkg, policyFlags, scanFlags);
9521
9522        // Initialize package source and resource directories
9523        final File scanFile = new File(pkg.codePath);
9524        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9525        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9526
9527        SharedUserSetting suid = null;
9528        PackageSetting pkgSetting = null;
9529
9530        // Getting the package setting may have a side-effect, so if we
9531        // are only checking if scan would succeed, stash a copy of the
9532        // old setting to restore at the end.
9533        PackageSetting nonMutatedPs = null;
9534
9535        // We keep references to the derived CPU Abis from settings in oder to reuse
9536        // them in the case where we're not upgrading or booting for the first time.
9537        String primaryCpuAbiFromSettings = null;
9538        String secondaryCpuAbiFromSettings = null;
9539
9540        // writer
9541        synchronized (mPackages) {
9542            if (pkg.mSharedUserId != null) {
9543                // SIDE EFFECTS; may potentially allocate a new shared user
9544                suid = mSettings.getSharedUserLPw(
9545                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9546                if (DEBUG_PACKAGE_SCANNING) {
9547                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9548                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9549                                + "): packages=" + suid.packages);
9550                }
9551            }
9552
9553            // Check if we are renaming from an original package name.
9554            PackageSetting origPackage = null;
9555            String realName = null;
9556            if (pkg.mOriginalPackages != null) {
9557                // This package may need to be renamed to a previously
9558                // installed name.  Let's check on that...
9559                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9560                if (pkg.mOriginalPackages.contains(renamed)) {
9561                    // This package had originally been installed as the
9562                    // original name, and we have already taken care of
9563                    // transitioning to the new one.  Just update the new
9564                    // one to continue using the old name.
9565                    realName = pkg.mRealPackage;
9566                    if (!pkg.packageName.equals(renamed)) {
9567                        // Callers into this function may have already taken
9568                        // care of renaming the package; only do it here if
9569                        // it is not already done.
9570                        pkg.setPackageName(renamed);
9571                    }
9572                } else {
9573                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9574                        if ((origPackage = mSettings.getPackageLPr(
9575                                pkg.mOriginalPackages.get(i))) != null) {
9576                            // We do have the package already installed under its
9577                            // original name...  should we use it?
9578                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9579                                // New package is not compatible with original.
9580                                origPackage = null;
9581                                continue;
9582                            } else if (origPackage.sharedUser != null) {
9583                                // Make sure uid is compatible between packages.
9584                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9585                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9586                                            + " to " + pkg.packageName + ": old uid "
9587                                            + origPackage.sharedUser.name
9588                                            + " differs from " + pkg.mSharedUserId);
9589                                    origPackage = null;
9590                                    continue;
9591                                }
9592                                // TODO: Add case when shared user id is added [b/28144775]
9593                            } else {
9594                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9595                                        + pkg.packageName + " to old name " + origPackage.name);
9596                            }
9597                            break;
9598                        }
9599                    }
9600                }
9601            }
9602
9603            if (mTransferedPackages.contains(pkg.packageName)) {
9604                Slog.w(TAG, "Package " + pkg.packageName
9605                        + " was transferred to another, but its .apk remains");
9606            }
9607
9608            // See comments in nonMutatedPs declaration
9609            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9610                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9611                if (foundPs != null) {
9612                    nonMutatedPs = new PackageSetting(foundPs);
9613                }
9614            }
9615
9616            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9617                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9618                if (foundPs != null) {
9619                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9620                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9621                }
9622            }
9623
9624            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9625            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9626                PackageManagerService.reportSettingsProblem(Log.WARN,
9627                        "Package " + pkg.packageName + " shared user changed from "
9628                                + (pkgSetting.sharedUser != null
9629                                        ? pkgSetting.sharedUser.name : "<nothing>")
9630                                + " to "
9631                                + (suid != null ? suid.name : "<nothing>")
9632                                + "; replacing with new");
9633                pkgSetting = null;
9634            }
9635            final PackageSetting oldPkgSetting =
9636                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9637            final PackageSetting disabledPkgSetting =
9638                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9639
9640            String[] usesStaticLibraries = null;
9641            if (pkg.usesStaticLibraries != null) {
9642                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9643                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9644            }
9645
9646            if (pkgSetting == null) {
9647                final String parentPackageName = (pkg.parentPackage != null)
9648                        ? pkg.parentPackage.packageName : null;
9649                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9650                // REMOVE SharedUserSetting from method; update in a separate call
9651                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9652                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9653                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9654                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9655                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9656                        true /*allowInstall*/, instantApp, parentPackageName,
9657                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9658                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9659                // SIDE EFFECTS; updates system state; move elsewhere
9660                if (origPackage != null) {
9661                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9662                }
9663                mSettings.addUserToSettingLPw(pkgSetting);
9664            } else {
9665                // REMOVE SharedUserSetting from method; update in a separate call.
9666                //
9667                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9668                // secondaryCpuAbi are not known at this point so we always update them
9669                // to null here, only to reset them at a later point.
9670                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9671                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9672                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9673                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9674                        UserManagerService.getInstance(), usesStaticLibraries,
9675                        pkg.usesStaticLibrariesVersions);
9676            }
9677            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9678            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9679
9680            // SIDE EFFECTS; modifies system state; move elsewhere
9681            if (pkgSetting.origPackage != null) {
9682                // If we are first transitioning from an original package,
9683                // fix up the new package's name now.  We need to do this after
9684                // looking up the package under its new name, so getPackageLP
9685                // can take care of fiddling things correctly.
9686                pkg.setPackageName(origPackage.name);
9687
9688                // File a report about this.
9689                String msg = "New package " + pkgSetting.realName
9690                        + " renamed to replace old package " + pkgSetting.name;
9691                reportSettingsProblem(Log.WARN, msg);
9692
9693                // Make a note of it.
9694                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9695                    mTransferedPackages.add(origPackage.name);
9696                }
9697
9698                // No longer need to retain this.
9699                pkgSetting.origPackage = null;
9700            }
9701
9702            // SIDE EFFECTS; modifies system state; move elsewhere
9703            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9704                // Make a note of it.
9705                mTransferedPackages.add(pkg.packageName);
9706            }
9707
9708            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9709                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9710            }
9711
9712            if ((scanFlags & SCAN_BOOTING) == 0
9713                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9714                // Check all shared libraries and map to their actual file path.
9715                // We only do this here for apps not on a system dir, because those
9716                // are the only ones that can fail an install due to this.  We
9717                // will take care of the system apps by updating all of their
9718                // library paths after the scan is done. Also during the initial
9719                // scan don't update any libs as we do this wholesale after all
9720                // apps are scanned to avoid dependency based scanning.
9721                updateSharedLibrariesLPr(pkg, null);
9722            }
9723
9724            if (mFoundPolicyFile) {
9725                SELinuxMMAC.assignSeInfoValue(pkg);
9726            }
9727            pkg.applicationInfo.uid = pkgSetting.appId;
9728            pkg.mExtras = pkgSetting;
9729
9730
9731            // Static shared libs have same package with different versions where
9732            // we internally use a synthetic package name to allow multiple versions
9733            // of the same package, therefore we need to compare signatures against
9734            // the package setting for the latest library version.
9735            PackageSetting signatureCheckPs = pkgSetting;
9736            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9737                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9738                if (libraryEntry != null) {
9739                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9740                }
9741            }
9742
9743            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9744                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9745                    // We just determined the app is signed correctly, so bring
9746                    // over the latest parsed certs.
9747                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9748                } else {
9749                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9750                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9751                                "Package " + pkg.packageName + " upgrade keys do not match the "
9752                                + "previously installed version");
9753                    } else {
9754                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9755                        String msg = "System package " + pkg.packageName
9756                                + " signature changed; retaining data.";
9757                        reportSettingsProblem(Log.WARN, msg);
9758                    }
9759                }
9760            } else {
9761                try {
9762                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9763                    verifySignaturesLP(signatureCheckPs, pkg);
9764                    // We just determined the app is signed correctly, so bring
9765                    // over the latest parsed certs.
9766                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9767                } catch (PackageManagerException e) {
9768                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9769                        throw e;
9770                    }
9771                    // The signature has changed, but this package is in the system
9772                    // image...  let's recover!
9773                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9774                    // However...  if this package is part of a shared user, but it
9775                    // doesn't match the signature of the shared user, let's fail.
9776                    // What this means is that you can't change the signatures
9777                    // associated with an overall shared user, which doesn't seem all
9778                    // that unreasonable.
9779                    if (signatureCheckPs.sharedUser != null) {
9780                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9781                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9782                            throw new PackageManagerException(
9783                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9784                                    "Signature mismatch for shared user: "
9785                                            + pkgSetting.sharedUser);
9786                        }
9787                    }
9788                    // File a report about this.
9789                    String msg = "System package " + pkg.packageName
9790                            + " signature changed; retaining data.";
9791                    reportSettingsProblem(Log.WARN, msg);
9792                }
9793            }
9794
9795            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9796                // This package wants to adopt ownership of permissions from
9797                // another package.
9798                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9799                    final String origName = pkg.mAdoptPermissions.get(i);
9800                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9801                    if (orig != null) {
9802                        if (verifyPackageUpdateLPr(orig, pkg)) {
9803                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9804                                    + pkg.packageName);
9805                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9806                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9807                        }
9808                    }
9809                }
9810            }
9811        }
9812
9813        pkg.applicationInfo.processName = fixProcessName(
9814                pkg.applicationInfo.packageName,
9815                pkg.applicationInfo.processName);
9816
9817        if (pkg != mPlatformPackage) {
9818            // Get all of our default paths setup
9819            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9820        }
9821
9822        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9823
9824        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9825            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9826                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9827                derivePackageAbi(
9828                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9829                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9830
9831                // Some system apps still use directory structure for native libraries
9832                // in which case we might end up not detecting abi solely based on apk
9833                // structure. Try to detect abi based on directory structure.
9834                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9835                        pkg.applicationInfo.primaryCpuAbi == null) {
9836                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9837                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9838                }
9839            } else {
9840                // This is not a first boot or an upgrade, don't bother deriving the
9841                // ABI during the scan. Instead, trust the value that was stored in the
9842                // package setting.
9843                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9844                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9845
9846                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9847
9848                if (DEBUG_ABI_SELECTION) {
9849                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9850                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9851                        pkg.applicationInfo.secondaryCpuAbi);
9852                }
9853            }
9854        } else {
9855            if ((scanFlags & SCAN_MOVE) != 0) {
9856                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9857                // but we already have this packages package info in the PackageSetting. We just
9858                // use that and derive the native library path based on the new codepath.
9859                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9860                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9861            }
9862
9863            // Set native library paths again. For moves, the path will be updated based on the
9864            // ABIs we've determined above. For non-moves, the path will be updated based on the
9865            // ABIs we determined during compilation, but the path will depend on the final
9866            // package path (after the rename away from the stage path).
9867            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9868        }
9869
9870        // This is a special case for the "system" package, where the ABI is
9871        // dictated by the zygote configuration (and init.rc). We should keep track
9872        // of this ABI so that we can deal with "normal" applications that run under
9873        // the same UID correctly.
9874        if (mPlatformPackage == pkg) {
9875            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9876                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9877        }
9878
9879        // If there's a mismatch between the abi-override in the package setting
9880        // and the abiOverride specified for the install. Warn about this because we
9881        // would've already compiled the app without taking the package setting into
9882        // account.
9883        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9884            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9885                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9886                        " for package " + pkg.packageName);
9887            }
9888        }
9889
9890        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9891        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9892        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9893
9894        // Copy the derived override back to the parsed package, so that we can
9895        // update the package settings accordingly.
9896        pkg.cpuAbiOverride = cpuAbiOverride;
9897
9898        if (DEBUG_ABI_SELECTION) {
9899            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9900                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9901                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9902        }
9903
9904        // Push the derived path down into PackageSettings so we know what to
9905        // clean up at uninstall time.
9906        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9907
9908        if (DEBUG_ABI_SELECTION) {
9909            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9910                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9911                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9912        }
9913
9914        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9915        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9916            // We don't do this here during boot because we can do it all
9917            // at once after scanning all existing packages.
9918            //
9919            // We also do this *before* we perform dexopt on this package, so that
9920            // we can avoid redundant dexopts, and also to make sure we've got the
9921            // code and package path correct.
9922            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9923        }
9924
9925        if (mFactoryTest && pkg.requestedPermissions.contains(
9926                android.Manifest.permission.FACTORY_TEST)) {
9927            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9928        }
9929
9930        if (isSystemApp(pkg)) {
9931            pkgSetting.isOrphaned = true;
9932        }
9933
9934        // Take care of first install / last update times.
9935        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9936        if (currentTime != 0) {
9937            if (pkgSetting.firstInstallTime == 0) {
9938                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9939            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9940                pkgSetting.lastUpdateTime = currentTime;
9941            }
9942        } else if (pkgSetting.firstInstallTime == 0) {
9943            // We need *something*.  Take time time stamp of the file.
9944            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9945        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9946            if (scanFileTime != pkgSetting.timeStamp) {
9947                // A package on the system image has changed; consider this
9948                // to be an update.
9949                pkgSetting.lastUpdateTime = scanFileTime;
9950            }
9951        }
9952        pkgSetting.setTimeStamp(scanFileTime);
9953
9954        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9955            if (nonMutatedPs != null) {
9956                synchronized (mPackages) {
9957                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9958                }
9959            }
9960        } else {
9961            final int userId = user == null ? 0 : user.getIdentifier();
9962            // Modify state for the given package setting
9963            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9964                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9965            if (pkgSetting.getInstantApp(userId)) {
9966                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9967            }
9968        }
9969        return pkg;
9970    }
9971
9972    /**
9973     * Applies policy to the parsed package based upon the given policy flags.
9974     * Ensures the package is in a good state.
9975     * <p>
9976     * Implementation detail: This method must NOT have any side effect. It would
9977     * ideally be static, but, it requires locks to read system state.
9978     */
9979    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9980        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9981            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9982            if (pkg.applicationInfo.isDirectBootAware()) {
9983                // we're direct boot aware; set for all components
9984                for (PackageParser.Service s : pkg.services) {
9985                    s.info.encryptionAware = s.info.directBootAware = true;
9986                }
9987                for (PackageParser.Provider p : pkg.providers) {
9988                    p.info.encryptionAware = p.info.directBootAware = true;
9989                }
9990                for (PackageParser.Activity a : pkg.activities) {
9991                    a.info.encryptionAware = a.info.directBootAware = true;
9992                }
9993                for (PackageParser.Activity r : pkg.receivers) {
9994                    r.info.encryptionAware = r.info.directBootAware = true;
9995                }
9996            }
9997        } else {
9998            // Only allow system apps to be flagged as core apps.
9999            pkg.coreApp = false;
10000            // clear flags not applicable to regular apps
10001            pkg.applicationInfo.privateFlags &=
10002                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10003            pkg.applicationInfo.privateFlags &=
10004                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10005        }
10006        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10007
10008        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10009            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10010        }
10011
10012        if (!isSystemApp(pkg)) {
10013            // Only system apps can use these features.
10014            pkg.mOriginalPackages = null;
10015            pkg.mRealPackage = null;
10016            pkg.mAdoptPermissions = null;
10017        }
10018    }
10019
10020    /**
10021     * Asserts the parsed package is valid according to the given policy. If the
10022     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10023     * <p>
10024     * Implementation detail: This method must NOT have any side effects. It would
10025     * ideally be static, but, it requires locks to read system state.
10026     *
10027     * @throws PackageManagerException If the package fails any of the validation checks
10028     */
10029    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10030            throws PackageManagerException {
10031        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10032            assertCodePolicy(pkg);
10033        }
10034
10035        if (pkg.applicationInfo.getCodePath() == null ||
10036                pkg.applicationInfo.getResourcePath() == null) {
10037            // Bail out. The resource and code paths haven't been set.
10038            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10039                    "Code and resource paths haven't been set correctly");
10040        }
10041
10042        // Make sure we're not adding any bogus keyset info
10043        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10044        ksms.assertScannedPackageValid(pkg);
10045
10046        synchronized (mPackages) {
10047            // The special "android" package can only be defined once
10048            if (pkg.packageName.equals("android")) {
10049                if (mAndroidApplication != null) {
10050                    Slog.w(TAG, "*************************************************");
10051                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10052                    Slog.w(TAG, " codePath=" + pkg.codePath);
10053                    Slog.w(TAG, "*************************************************");
10054                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10055                            "Core android package being redefined.  Skipping.");
10056                }
10057            }
10058
10059            // A package name must be unique; don't allow duplicates
10060            if (mPackages.containsKey(pkg.packageName)) {
10061                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10062                        "Application package " + pkg.packageName
10063                        + " already installed.  Skipping duplicate.");
10064            }
10065
10066            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10067                // Static libs have a synthetic package name containing the version
10068                // but we still want the base name to be unique.
10069                if (mPackages.containsKey(pkg.manifestPackageName)) {
10070                    throw new PackageManagerException(
10071                            "Duplicate static shared lib provider package");
10072                }
10073
10074                // Static shared libraries should have at least O target SDK
10075                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10076                    throw new PackageManagerException(
10077                            "Packages declaring static-shared libs must target O SDK or higher");
10078                }
10079
10080                // Package declaring static a shared lib cannot be instant apps
10081                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10082                    throw new PackageManagerException(
10083                            "Packages declaring static-shared libs cannot be instant apps");
10084                }
10085
10086                // Package declaring static a shared lib cannot be renamed since the package
10087                // name is synthetic and apps can't code around package manager internals.
10088                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10089                    throw new PackageManagerException(
10090                            "Packages declaring static-shared libs cannot be renamed");
10091                }
10092
10093                // Package declaring static a shared lib cannot declare child packages
10094                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10095                    throw new PackageManagerException(
10096                            "Packages declaring static-shared libs cannot have child packages");
10097                }
10098
10099                // Package declaring static a shared lib cannot declare dynamic libs
10100                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10101                    throw new PackageManagerException(
10102                            "Packages declaring static-shared libs cannot declare dynamic libs");
10103                }
10104
10105                // Package declaring static a shared lib cannot declare shared users
10106                if (pkg.mSharedUserId != null) {
10107                    throw new PackageManagerException(
10108                            "Packages declaring static-shared libs cannot declare shared users");
10109                }
10110
10111                // Static shared libs cannot declare activities
10112                if (!pkg.activities.isEmpty()) {
10113                    throw new PackageManagerException(
10114                            "Static shared libs cannot declare activities");
10115                }
10116
10117                // Static shared libs cannot declare services
10118                if (!pkg.services.isEmpty()) {
10119                    throw new PackageManagerException(
10120                            "Static shared libs cannot declare services");
10121                }
10122
10123                // Static shared libs cannot declare providers
10124                if (!pkg.providers.isEmpty()) {
10125                    throw new PackageManagerException(
10126                            "Static shared libs cannot declare content providers");
10127                }
10128
10129                // Static shared libs cannot declare receivers
10130                if (!pkg.receivers.isEmpty()) {
10131                    throw new PackageManagerException(
10132                            "Static shared libs cannot declare broadcast receivers");
10133                }
10134
10135                // Static shared libs cannot declare permission groups
10136                if (!pkg.permissionGroups.isEmpty()) {
10137                    throw new PackageManagerException(
10138                            "Static shared libs cannot declare permission groups");
10139                }
10140
10141                // Static shared libs cannot declare permissions
10142                if (!pkg.permissions.isEmpty()) {
10143                    throw new PackageManagerException(
10144                            "Static shared libs cannot declare permissions");
10145                }
10146
10147                // Static shared libs cannot declare protected broadcasts
10148                if (pkg.protectedBroadcasts != null) {
10149                    throw new PackageManagerException(
10150                            "Static shared libs cannot declare protected broadcasts");
10151                }
10152
10153                // Static shared libs cannot be overlay targets
10154                if (pkg.mOverlayTarget != null) {
10155                    throw new PackageManagerException(
10156                            "Static shared libs cannot be overlay targets");
10157                }
10158
10159                // The version codes must be ordered as lib versions
10160                int minVersionCode = Integer.MIN_VALUE;
10161                int maxVersionCode = Integer.MAX_VALUE;
10162
10163                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10164                        pkg.staticSharedLibName);
10165                if (versionedLib != null) {
10166                    final int versionCount = versionedLib.size();
10167                    for (int i = 0; i < versionCount; i++) {
10168                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10169                        // TODO: We will change version code to long, so in the new API it is long
10170                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
10171                                .getVersionCode();
10172                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10173                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10174                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10175                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10176                        } else {
10177                            minVersionCode = maxVersionCode = libVersionCode;
10178                            break;
10179                        }
10180                    }
10181                }
10182                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10183                    throw new PackageManagerException("Static shared"
10184                            + " lib version codes must be ordered as lib versions");
10185                }
10186            }
10187
10188            // Only privileged apps and updated privileged apps can add child packages.
10189            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10190                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10191                    throw new PackageManagerException("Only privileged apps can add child "
10192                            + "packages. Ignoring package " + pkg.packageName);
10193                }
10194                final int childCount = pkg.childPackages.size();
10195                for (int i = 0; i < childCount; i++) {
10196                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10197                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10198                            childPkg.packageName)) {
10199                        throw new PackageManagerException("Can't override child of "
10200                                + "another disabled app. Ignoring package " + pkg.packageName);
10201                    }
10202                }
10203            }
10204
10205            // If we're only installing presumed-existing packages, require that the
10206            // scanned APK is both already known and at the path previously established
10207            // for it.  Previously unknown packages we pick up normally, but if we have an
10208            // a priori expectation about this package's install presence, enforce it.
10209            // With a singular exception for new system packages. When an OTA contains
10210            // a new system package, we allow the codepath to change from a system location
10211            // to the user-installed location. If we don't allow this change, any newer,
10212            // user-installed version of the application will be ignored.
10213            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10214                if (mExpectingBetter.containsKey(pkg.packageName)) {
10215                    logCriticalInfo(Log.WARN,
10216                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10217                } else {
10218                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10219                    if (known != null) {
10220                        if (DEBUG_PACKAGE_SCANNING) {
10221                            Log.d(TAG, "Examining " + pkg.codePath
10222                                    + " and requiring known paths " + known.codePathString
10223                                    + " & " + known.resourcePathString);
10224                        }
10225                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10226                                || !pkg.applicationInfo.getResourcePath().equals(
10227                                        known.resourcePathString)) {
10228                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10229                                    "Application package " + pkg.packageName
10230                                    + " found at " + pkg.applicationInfo.getCodePath()
10231                                    + " but expected at " + known.codePathString
10232                                    + "; ignoring.");
10233                        }
10234                    }
10235                }
10236            }
10237
10238            // Verify that this new package doesn't have any content providers
10239            // that conflict with existing packages.  Only do this if the
10240            // package isn't already installed, since we don't want to break
10241            // things that are installed.
10242            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10243                final int N = pkg.providers.size();
10244                int i;
10245                for (i=0; i<N; i++) {
10246                    PackageParser.Provider p = pkg.providers.get(i);
10247                    if (p.info.authority != null) {
10248                        String names[] = p.info.authority.split(";");
10249                        for (int j = 0; j < names.length; j++) {
10250                            if (mProvidersByAuthority.containsKey(names[j])) {
10251                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10252                                final String otherPackageName =
10253                                        ((other != null && other.getComponentName() != null) ?
10254                                                other.getComponentName().getPackageName() : "?");
10255                                throw new PackageManagerException(
10256                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10257                                        "Can't install because provider name " + names[j]
10258                                                + " (in package " + pkg.applicationInfo.packageName
10259                                                + ") is already used by " + otherPackageName);
10260                            }
10261                        }
10262                    }
10263                }
10264            }
10265        }
10266    }
10267
10268    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10269            int type, String declaringPackageName, int declaringVersionCode) {
10270        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10271        if (versionedLib == null) {
10272            versionedLib = new SparseArray<>();
10273            mSharedLibraries.put(name, versionedLib);
10274            if (type == SharedLibraryInfo.TYPE_STATIC) {
10275                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10276            }
10277        } else if (versionedLib.indexOfKey(version) >= 0) {
10278            return false;
10279        }
10280        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10281                version, type, declaringPackageName, declaringVersionCode);
10282        versionedLib.put(version, libEntry);
10283        return true;
10284    }
10285
10286    private boolean removeSharedLibraryLPw(String name, int version) {
10287        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10288        if (versionedLib == null) {
10289            return false;
10290        }
10291        final int libIdx = versionedLib.indexOfKey(version);
10292        if (libIdx < 0) {
10293            return false;
10294        }
10295        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10296        versionedLib.remove(version);
10297        if (versionedLib.size() <= 0) {
10298            mSharedLibraries.remove(name);
10299            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10300                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10301                        .getPackageName());
10302            }
10303        }
10304        return true;
10305    }
10306
10307    /**
10308     * Adds a scanned package to the system. When this method is finished, the package will
10309     * be available for query, resolution, etc...
10310     */
10311    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10312            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10313        final String pkgName = pkg.packageName;
10314        if (mCustomResolverComponentName != null &&
10315                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10316            setUpCustomResolverActivity(pkg);
10317        }
10318
10319        if (pkg.packageName.equals("android")) {
10320            synchronized (mPackages) {
10321                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10322                    // Set up information for our fall-back user intent resolution activity.
10323                    mPlatformPackage = pkg;
10324                    pkg.mVersionCode = mSdkVersion;
10325                    mAndroidApplication = pkg.applicationInfo;
10326                    if (!mResolverReplaced) {
10327                        mResolveActivity.applicationInfo = mAndroidApplication;
10328                        mResolveActivity.name = ResolverActivity.class.getName();
10329                        mResolveActivity.packageName = mAndroidApplication.packageName;
10330                        mResolveActivity.processName = "system:ui";
10331                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10332                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10333                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10334                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10335                        mResolveActivity.exported = true;
10336                        mResolveActivity.enabled = true;
10337                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10338                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10339                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10340                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10341                                | ActivityInfo.CONFIG_ORIENTATION
10342                                | ActivityInfo.CONFIG_KEYBOARD
10343                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10344                        mResolveInfo.activityInfo = mResolveActivity;
10345                        mResolveInfo.priority = 0;
10346                        mResolveInfo.preferredOrder = 0;
10347                        mResolveInfo.match = 0;
10348                        mResolveComponentName = new ComponentName(
10349                                mAndroidApplication.packageName, mResolveActivity.name);
10350                    }
10351                }
10352            }
10353        }
10354
10355        ArrayList<PackageParser.Package> clientLibPkgs = null;
10356        // writer
10357        synchronized (mPackages) {
10358            boolean hasStaticSharedLibs = false;
10359
10360            // Any app can add new static shared libraries
10361            if (pkg.staticSharedLibName != null) {
10362                // Static shared libs don't allow renaming as they have synthetic package
10363                // names to allow install of multiple versions, so use name from manifest.
10364                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10365                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10366                        pkg.manifestPackageName, pkg.mVersionCode)) {
10367                    hasStaticSharedLibs = true;
10368                } else {
10369                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10370                                + pkg.staticSharedLibName + " already exists; skipping");
10371                }
10372                // Static shared libs cannot be updated once installed since they
10373                // use synthetic package name which includes the version code, so
10374                // not need to update other packages's shared lib dependencies.
10375            }
10376
10377            if (!hasStaticSharedLibs
10378                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10379                // Only system apps can add new dynamic shared libraries.
10380                if (pkg.libraryNames != null) {
10381                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10382                        String name = pkg.libraryNames.get(i);
10383                        boolean allowed = false;
10384                        if (pkg.isUpdatedSystemApp()) {
10385                            // New library entries can only be added through the
10386                            // system image.  This is important to get rid of a lot
10387                            // of nasty edge cases: for example if we allowed a non-
10388                            // system update of the app to add a library, then uninstalling
10389                            // the update would make the library go away, and assumptions
10390                            // we made such as through app install filtering would now
10391                            // have allowed apps on the device which aren't compatible
10392                            // with it.  Better to just have the restriction here, be
10393                            // conservative, and create many fewer cases that can negatively
10394                            // impact the user experience.
10395                            final PackageSetting sysPs = mSettings
10396                                    .getDisabledSystemPkgLPr(pkg.packageName);
10397                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10398                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10399                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10400                                        allowed = true;
10401                                        break;
10402                                    }
10403                                }
10404                            }
10405                        } else {
10406                            allowed = true;
10407                        }
10408                        if (allowed) {
10409                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10410                                    SharedLibraryInfo.VERSION_UNDEFINED,
10411                                    SharedLibraryInfo.TYPE_DYNAMIC,
10412                                    pkg.packageName, pkg.mVersionCode)) {
10413                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10414                                        + name + " already exists; skipping");
10415                            }
10416                        } else {
10417                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10418                                    + name + " that is not declared on system image; skipping");
10419                        }
10420                    }
10421
10422                    if ((scanFlags & SCAN_BOOTING) == 0) {
10423                        // If we are not booting, we need to update any applications
10424                        // that are clients of our shared library.  If we are booting,
10425                        // this will all be done once the scan is complete.
10426                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10427                    }
10428                }
10429            }
10430        }
10431
10432        if ((scanFlags & SCAN_BOOTING) != 0) {
10433            // No apps can run during boot scan, so they don't need to be frozen
10434        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10435            // Caller asked to not kill app, so it's probably not frozen
10436        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10437            // Caller asked us to ignore frozen check for some reason; they
10438            // probably didn't know the package name
10439        } else {
10440            // We're doing major surgery on this package, so it better be frozen
10441            // right now to keep it from launching
10442            checkPackageFrozen(pkgName);
10443        }
10444
10445        // Also need to kill any apps that are dependent on the library.
10446        if (clientLibPkgs != null) {
10447            for (int i=0; i<clientLibPkgs.size(); i++) {
10448                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10449                killApplication(clientPkg.applicationInfo.packageName,
10450                        clientPkg.applicationInfo.uid, "update lib");
10451            }
10452        }
10453
10454        // writer
10455        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10456
10457        synchronized (mPackages) {
10458            // We don't expect installation to fail beyond this point
10459
10460            // Add the new setting to mSettings
10461            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10462            // Add the new setting to mPackages
10463            mPackages.put(pkg.applicationInfo.packageName, pkg);
10464            // Make sure we don't accidentally delete its data.
10465            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10466            while (iter.hasNext()) {
10467                PackageCleanItem item = iter.next();
10468                if (pkgName.equals(item.packageName)) {
10469                    iter.remove();
10470                }
10471            }
10472
10473            // Add the package's KeySets to the global KeySetManagerService
10474            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10475            ksms.addScannedPackageLPw(pkg);
10476
10477            int N = pkg.providers.size();
10478            StringBuilder r = null;
10479            int i;
10480            for (i=0; i<N; i++) {
10481                PackageParser.Provider p = pkg.providers.get(i);
10482                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10483                        p.info.processName);
10484                mProviders.addProvider(p);
10485                p.syncable = p.info.isSyncable;
10486                if (p.info.authority != null) {
10487                    String names[] = p.info.authority.split(";");
10488                    p.info.authority = null;
10489                    for (int j = 0; j < names.length; j++) {
10490                        if (j == 1 && p.syncable) {
10491                            // We only want the first authority for a provider to possibly be
10492                            // syncable, so if we already added this provider using a different
10493                            // authority clear the syncable flag. We copy the provider before
10494                            // changing it because the mProviders object contains a reference
10495                            // to a provider that we don't want to change.
10496                            // Only do this for the second authority since the resulting provider
10497                            // object can be the same for all future authorities for this provider.
10498                            p = new PackageParser.Provider(p);
10499                            p.syncable = false;
10500                        }
10501                        if (!mProvidersByAuthority.containsKey(names[j])) {
10502                            mProvidersByAuthority.put(names[j], p);
10503                            if (p.info.authority == null) {
10504                                p.info.authority = names[j];
10505                            } else {
10506                                p.info.authority = p.info.authority + ";" + names[j];
10507                            }
10508                            if (DEBUG_PACKAGE_SCANNING) {
10509                                if (chatty)
10510                                    Log.d(TAG, "Registered content provider: " + names[j]
10511                                            + ", className = " + p.info.name + ", isSyncable = "
10512                                            + p.info.isSyncable);
10513                            }
10514                        } else {
10515                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10516                            Slog.w(TAG, "Skipping provider name " + names[j] +
10517                                    " (in package " + pkg.applicationInfo.packageName +
10518                                    "): name already used by "
10519                                    + ((other != null && other.getComponentName() != null)
10520                                            ? other.getComponentName().getPackageName() : "?"));
10521                        }
10522                    }
10523                }
10524                if (chatty) {
10525                    if (r == null) {
10526                        r = new StringBuilder(256);
10527                    } else {
10528                        r.append(' ');
10529                    }
10530                    r.append(p.info.name);
10531                }
10532            }
10533            if (r != null) {
10534                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10535            }
10536
10537            N = pkg.services.size();
10538            r = null;
10539            for (i=0; i<N; i++) {
10540                PackageParser.Service s = pkg.services.get(i);
10541                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10542                        s.info.processName);
10543                mServices.addService(s);
10544                if (chatty) {
10545                    if (r == null) {
10546                        r = new StringBuilder(256);
10547                    } else {
10548                        r.append(' ');
10549                    }
10550                    r.append(s.info.name);
10551                }
10552            }
10553            if (r != null) {
10554                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10555            }
10556
10557            N = pkg.receivers.size();
10558            r = null;
10559            for (i=0; i<N; i++) {
10560                PackageParser.Activity a = pkg.receivers.get(i);
10561                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10562                        a.info.processName);
10563                mReceivers.addActivity(a, "receiver");
10564                if (chatty) {
10565                    if (r == null) {
10566                        r = new StringBuilder(256);
10567                    } else {
10568                        r.append(' ');
10569                    }
10570                    r.append(a.info.name);
10571                }
10572            }
10573            if (r != null) {
10574                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10575            }
10576
10577            N = pkg.activities.size();
10578            r = null;
10579            for (i=0; i<N; i++) {
10580                PackageParser.Activity a = pkg.activities.get(i);
10581                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10582                        a.info.processName);
10583                mActivities.addActivity(a, "activity");
10584                if (chatty) {
10585                    if (r == null) {
10586                        r = new StringBuilder(256);
10587                    } else {
10588                        r.append(' ');
10589                    }
10590                    r.append(a.info.name);
10591                }
10592            }
10593            if (r != null) {
10594                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10595            }
10596
10597            N = pkg.permissionGroups.size();
10598            r = null;
10599            for (i=0; i<N; i++) {
10600                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10601                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10602                final String curPackageName = cur == null ? null : cur.info.packageName;
10603                // Dont allow ephemeral apps to define new permission groups.
10604                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10605                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10606                            + pg.info.packageName
10607                            + " ignored: instant apps cannot define new permission groups.");
10608                    continue;
10609                }
10610                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10611                if (cur == null || isPackageUpdate) {
10612                    mPermissionGroups.put(pg.info.name, pg);
10613                    if (chatty) {
10614                        if (r == null) {
10615                            r = new StringBuilder(256);
10616                        } else {
10617                            r.append(' ');
10618                        }
10619                        if (isPackageUpdate) {
10620                            r.append("UPD:");
10621                        }
10622                        r.append(pg.info.name);
10623                    }
10624                } else {
10625                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10626                            + pg.info.packageName + " ignored: original from "
10627                            + cur.info.packageName);
10628                    if (chatty) {
10629                        if (r == null) {
10630                            r = new StringBuilder(256);
10631                        } else {
10632                            r.append(' ');
10633                        }
10634                        r.append("DUP:");
10635                        r.append(pg.info.name);
10636                    }
10637                }
10638            }
10639            if (r != null) {
10640                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10641            }
10642
10643            N = pkg.permissions.size();
10644            r = null;
10645            for (i=0; i<N; i++) {
10646                PackageParser.Permission p = pkg.permissions.get(i);
10647
10648                // Dont allow ephemeral apps to define new permissions.
10649                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10650                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10651                            + p.info.packageName
10652                            + " ignored: instant apps cannot define new permissions.");
10653                    continue;
10654                }
10655
10656                // Assume by default that we did not install this permission into the system.
10657                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10658
10659                // Now that permission groups have a special meaning, we ignore permission
10660                // groups for legacy apps to prevent unexpected behavior. In particular,
10661                // permissions for one app being granted to someone just becase they happen
10662                // to be in a group defined by another app (before this had no implications).
10663                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10664                    p.group = mPermissionGroups.get(p.info.group);
10665                    // Warn for a permission in an unknown group.
10666                    if (p.info.group != null && p.group == null) {
10667                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10668                                + p.info.packageName + " in an unknown group " + p.info.group);
10669                    }
10670                }
10671
10672                ArrayMap<String, BasePermission> permissionMap =
10673                        p.tree ? mSettings.mPermissionTrees
10674                                : mSettings.mPermissions;
10675                BasePermission bp = permissionMap.get(p.info.name);
10676
10677                // Allow system apps to redefine non-system permissions
10678                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10679                    final boolean currentOwnerIsSystem = (bp.perm != null
10680                            && isSystemApp(bp.perm.owner));
10681                    if (isSystemApp(p.owner)) {
10682                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10683                            // It's a built-in permission and no owner, take ownership now
10684                            bp.packageSetting = pkgSetting;
10685                            bp.perm = p;
10686                            bp.uid = pkg.applicationInfo.uid;
10687                            bp.sourcePackage = p.info.packageName;
10688                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10689                        } else if (!currentOwnerIsSystem) {
10690                            String msg = "New decl " + p.owner + " of permission  "
10691                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10692                            reportSettingsProblem(Log.WARN, msg);
10693                            bp = null;
10694                        }
10695                    }
10696                }
10697
10698                if (bp == null) {
10699                    bp = new BasePermission(p.info.name, p.info.packageName,
10700                            BasePermission.TYPE_NORMAL);
10701                    permissionMap.put(p.info.name, bp);
10702                }
10703
10704                if (bp.perm == null) {
10705                    if (bp.sourcePackage == null
10706                            || bp.sourcePackage.equals(p.info.packageName)) {
10707                        BasePermission tree = findPermissionTreeLP(p.info.name);
10708                        if (tree == null
10709                                || tree.sourcePackage.equals(p.info.packageName)) {
10710                            bp.packageSetting = pkgSetting;
10711                            bp.perm = p;
10712                            bp.uid = pkg.applicationInfo.uid;
10713                            bp.sourcePackage = p.info.packageName;
10714                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10715                            if (chatty) {
10716                                if (r == null) {
10717                                    r = new StringBuilder(256);
10718                                } else {
10719                                    r.append(' ');
10720                                }
10721                                r.append(p.info.name);
10722                            }
10723                        } else {
10724                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10725                                    + p.info.packageName + " ignored: base tree "
10726                                    + tree.name + " is from package "
10727                                    + tree.sourcePackage);
10728                        }
10729                    } else {
10730                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10731                                + p.info.packageName + " ignored: original from "
10732                                + bp.sourcePackage);
10733                    }
10734                } else if (chatty) {
10735                    if (r == null) {
10736                        r = new StringBuilder(256);
10737                    } else {
10738                        r.append(' ');
10739                    }
10740                    r.append("DUP:");
10741                    r.append(p.info.name);
10742                }
10743                if (bp.perm == p) {
10744                    bp.protectionLevel = p.info.protectionLevel;
10745                }
10746            }
10747
10748            if (r != null) {
10749                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10750            }
10751
10752            N = pkg.instrumentation.size();
10753            r = null;
10754            for (i=0; i<N; i++) {
10755                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10756                a.info.packageName = pkg.applicationInfo.packageName;
10757                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10758                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10759                a.info.splitNames = pkg.splitNames;
10760                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10761                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10762                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10763                a.info.dataDir = pkg.applicationInfo.dataDir;
10764                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10765                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10766                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10767                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10768                mInstrumentation.put(a.getComponentName(), a);
10769                if (chatty) {
10770                    if (r == null) {
10771                        r = new StringBuilder(256);
10772                    } else {
10773                        r.append(' ');
10774                    }
10775                    r.append(a.info.name);
10776                }
10777            }
10778            if (r != null) {
10779                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10780            }
10781
10782            if (pkg.protectedBroadcasts != null) {
10783                N = pkg.protectedBroadcasts.size();
10784                for (i=0; i<N; i++) {
10785                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10786                }
10787            }
10788        }
10789
10790        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10791    }
10792
10793    /**
10794     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10795     * is derived purely on the basis of the contents of {@code scanFile} and
10796     * {@code cpuAbiOverride}.
10797     *
10798     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10799     */
10800    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10801                                 String cpuAbiOverride, boolean extractLibs,
10802                                 File appLib32InstallDir)
10803            throws PackageManagerException {
10804        // Give ourselves some initial paths; we'll come back for another
10805        // pass once we've determined ABI below.
10806        setNativeLibraryPaths(pkg, appLib32InstallDir);
10807
10808        // We would never need to extract libs for forward-locked and external packages,
10809        // since the container service will do it for us. We shouldn't attempt to
10810        // extract libs from system app when it was not updated.
10811        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10812                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10813            extractLibs = false;
10814        }
10815
10816        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10817        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10818
10819        NativeLibraryHelper.Handle handle = null;
10820        try {
10821            handle = NativeLibraryHelper.Handle.create(pkg);
10822            // TODO(multiArch): This can be null for apps that didn't go through the
10823            // usual installation process. We can calculate it again, like we
10824            // do during install time.
10825            //
10826            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10827            // unnecessary.
10828            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10829
10830            // Null out the abis so that they can be recalculated.
10831            pkg.applicationInfo.primaryCpuAbi = null;
10832            pkg.applicationInfo.secondaryCpuAbi = null;
10833            if (isMultiArch(pkg.applicationInfo)) {
10834                // Warn if we've set an abiOverride for multi-lib packages..
10835                // By definition, we need to copy both 32 and 64 bit libraries for
10836                // such packages.
10837                if (pkg.cpuAbiOverride != null
10838                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10839                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10840                }
10841
10842                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10843                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10844                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10845                    if (extractLibs) {
10846                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10847                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10848                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10849                                useIsaSpecificSubdirs);
10850                    } else {
10851                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10852                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10853                    }
10854                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10855                }
10856
10857                maybeThrowExceptionForMultiArchCopy(
10858                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10859
10860                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10861                    if (extractLibs) {
10862                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10863                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10864                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10865                                useIsaSpecificSubdirs);
10866                    } else {
10867                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10868                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10869                    }
10870                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10871                }
10872
10873                maybeThrowExceptionForMultiArchCopy(
10874                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10875
10876                if (abi64 >= 0) {
10877                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10878                }
10879
10880                if (abi32 >= 0) {
10881                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10882                    if (abi64 >= 0) {
10883                        if (pkg.use32bitAbi) {
10884                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10885                            pkg.applicationInfo.primaryCpuAbi = abi;
10886                        } else {
10887                            pkg.applicationInfo.secondaryCpuAbi = abi;
10888                        }
10889                    } else {
10890                        pkg.applicationInfo.primaryCpuAbi = abi;
10891                    }
10892                }
10893
10894            } else {
10895                String[] abiList = (cpuAbiOverride != null) ?
10896                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10897
10898                // Enable gross and lame hacks for apps that are built with old
10899                // SDK tools. We must scan their APKs for renderscript bitcode and
10900                // not launch them if it's present. Don't bother checking on devices
10901                // that don't have 64 bit support.
10902                boolean needsRenderScriptOverride = false;
10903                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10904                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10905                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10906                    needsRenderScriptOverride = true;
10907                }
10908
10909                final int copyRet;
10910                if (extractLibs) {
10911                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10912                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10913                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10914                } else {
10915                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10916                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10917                }
10918                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10919
10920                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10921                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10922                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10923                }
10924
10925                if (copyRet >= 0) {
10926                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10927                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10928                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10929                } else if (needsRenderScriptOverride) {
10930                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10931                }
10932            }
10933        } catch (IOException ioe) {
10934            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10935        } finally {
10936            IoUtils.closeQuietly(handle);
10937        }
10938
10939        // Now that we've calculated the ABIs and determined if it's an internal app,
10940        // we will go ahead and populate the nativeLibraryPath.
10941        setNativeLibraryPaths(pkg, appLib32InstallDir);
10942    }
10943
10944    /**
10945     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10946     * i.e, so that all packages can be run inside a single process if required.
10947     *
10948     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10949     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10950     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10951     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10952     * updating a package that belongs to a shared user.
10953     *
10954     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10955     * adds unnecessary complexity.
10956     */
10957    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10958            PackageParser.Package scannedPackage) {
10959        String requiredInstructionSet = null;
10960        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10961            requiredInstructionSet = VMRuntime.getInstructionSet(
10962                     scannedPackage.applicationInfo.primaryCpuAbi);
10963        }
10964
10965        PackageSetting requirer = null;
10966        for (PackageSetting ps : packagesForUser) {
10967            // If packagesForUser contains scannedPackage, we skip it. This will happen
10968            // when scannedPackage is an update of an existing package. Without this check,
10969            // we will never be able to change the ABI of any package belonging to a shared
10970            // user, even if it's compatible with other packages.
10971            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10972                if (ps.primaryCpuAbiString == null) {
10973                    continue;
10974                }
10975
10976                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10977                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10978                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10979                    // this but there's not much we can do.
10980                    String errorMessage = "Instruction set mismatch, "
10981                            + ((requirer == null) ? "[caller]" : requirer)
10982                            + " requires " + requiredInstructionSet + " whereas " + ps
10983                            + " requires " + instructionSet;
10984                    Slog.w(TAG, errorMessage);
10985                }
10986
10987                if (requiredInstructionSet == null) {
10988                    requiredInstructionSet = instructionSet;
10989                    requirer = ps;
10990                }
10991            }
10992        }
10993
10994        if (requiredInstructionSet != null) {
10995            String adjustedAbi;
10996            if (requirer != null) {
10997                // requirer != null implies that either scannedPackage was null or that scannedPackage
10998                // did not require an ABI, in which case we have to adjust scannedPackage to match
10999                // the ABI of the set (which is the same as requirer's ABI)
11000                adjustedAbi = requirer.primaryCpuAbiString;
11001                if (scannedPackage != null) {
11002                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11003                }
11004            } else {
11005                // requirer == null implies that we're updating all ABIs in the set to
11006                // match scannedPackage.
11007                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11008            }
11009
11010            for (PackageSetting ps : packagesForUser) {
11011                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11012                    if (ps.primaryCpuAbiString != null) {
11013                        continue;
11014                    }
11015
11016                    ps.primaryCpuAbiString = adjustedAbi;
11017                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11018                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11019                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11020                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11021                                + " (requirer="
11022                                + (requirer != null ? requirer.pkg : "null")
11023                                + ", scannedPackage="
11024                                + (scannedPackage != null ? scannedPackage : "null")
11025                                + ")");
11026                        try {
11027                            mInstaller.rmdex(ps.codePathString,
11028                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11029                        } catch (InstallerException ignored) {
11030                        }
11031                    }
11032                }
11033            }
11034        }
11035    }
11036
11037    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11038        synchronized (mPackages) {
11039            mResolverReplaced = true;
11040            // Set up information for custom user intent resolution activity.
11041            mResolveActivity.applicationInfo = pkg.applicationInfo;
11042            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11043            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11044            mResolveActivity.processName = pkg.applicationInfo.packageName;
11045            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11046            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11047                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11048            mResolveActivity.theme = 0;
11049            mResolveActivity.exported = true;
11050            mResolveActivity.enabled = true;
11051            mResolveInfo.activityInfo = mResolveActivity;
11052            mResolveInfo.priority = 0;
11053            mResolveInfo.preferredOrder = 0;
11054            mResolveInfo.match = 0;
11055            mResolveComponentName = mCustomResolverComponentName;
11056            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11057                    mResolveComponentName);
11058        }
11059    }
11060
11061    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11062        if (installerActivity == null) {
11063            if (DEBUG_EPHEMERAL) {
11064                Slog.d(TAG, "Clear ephemeral installer activity");
11065            }
11066            mInstantAppInstallerActivity = null;
11067            return;
11068        }
11069
11070        if (DEBUG_EPHEMERAL) {
11071            Slog.d(TAG, "Set ephemeral installer activity: "
11072                    + installerActivity.getComponentName());
11073        }
11074        // Set up information for ephemeral installer activity
11075        mInstantAppInstallerActivity = installerActivity;
11076        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11077                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11078        mInstantAppInstallerActivity.exported = true;
11079        mInstantAppInstallerActivity.enabled = true;
11080        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11081        mInstantAppInstallerInfo.priority = 0;
11082        mInstantAppInstallerInfo.preferredOrder = 1;
11083        mInstantAppInstallerInfo.isDefault = true;
11084        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11085                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11086    }
11087
11088    private static String calculateBundledApkRoot(final String codePathString) {
11089        final File codePath = new File(codePathString);
11090        final File codeRoot;
11091        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11092            codeRoot = Environment.getRootDirectory();
11093        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11094            codeRoot = Environment.getOemDirectory();
11095        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11096            codeRoot = Environment.getVendorDirectory();
11097        } else {
11098            // Unrecognized code path; take its top real segment as the apk root:
11099            // e.g. /something/app/blah.apk => /something
11100            try {
11101                File f = codePath.getCanonicalFile();
11102                File parent = f.getParentFile();    // non-null because codePath is a file
11103                File tmp;
11104                while ((tmp = parent.getParentFile()) != null) {
11105                    f = parent;
11106                    parent = tmp;
11107                }
11108                codeRoot = f;
11109                Slog.w(TAG, "Unrecognized code path "
11110                        + codePath + " - using " + codeRoot);
11111            } catch (IOException e) {
11112                // Can't canonicalize the code path -- shenanigans?
11113                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11114                return Environment.getRootDirectory().getPath();
11115            }
11116        }
11117        return codeRoot.getPath();
11118    }
11119
11120    /**
11121     * Derive and set the location of native libraries for the given package,
11122     * which varies depending on where and how the package was installed.
11123     */
11124    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11125        final ApplicationInfo info = pkg.applicationInfo;
11126        final String codePath = pkg.codePath;
11127        final File codeFile = new File(codePath);
11128        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11129        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11130
11131        info.nativeLibraryRootDir = null;
11132        info.nativeLibraryRootRequiresIsa = false;
11133        info.nativeLibraryDir = null;
11134        info.secondaryNativeLibraryDir = null;
11135
11136        if (isApkFile(codeFile)) {
11137            // Monolithic install
11138            if (bundledApp) {
11139                // If "/system/lib64/apkname" exists, assume that is the per-package
11140                // native library directory to use; otherwise use "/system/lib/apkname".
11141                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11142                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11143                        getPrimaryInstructionSet(info));
11144
11145                // This is a bundled system app so choose the path based on the ABI.
11146                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11147                // is just the default path.
11148                final String apkName = deriveCodePathName(codePath);
11149                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11150                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11151                        apkName).getAbsolutePath();
11152
11153                if (info.secondaryCpuAbi != null) {
11154                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11155                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11156                            secondaryLibDir, apkName).getAbsolutePath();
11157                }
11158            } else if (asecApp) {
11159                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11160                        .getAbsolutePath();
11161            } else {
11162                final String apkName = deriveCodePathName(codePath);
11163                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11164                        .getAbsolutePath();
11165            }
11166
11167            info.nativeLibraryRootRequiresIsa = false;
11168            info.nativeLibraryDir = info.nativeLibraryRootDir;
11169        } else {
11170            // Cluster install
11171            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11172            info.nativeLibraryRootRequiresIsa = true;
11173
11174            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11175                    getPrimaryInstructionSet(info)).getAbsolutePath();
11176
11177            if (info.secondaryCpuAbi != null) {
11178                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11179                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11180            }
11181        }
11182    }
11183
11184    /**
11185     * Calculate the abis and roots for a bundled app. These can uniquely
11186     * be determined from the contents of the system partition, i.e whether
11187     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11188     * of this information, and instead assume that the system was built
11189     * sensibly.
11190     */
11191    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11192                                           PackageSetting pkgSetting) {
11193        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11194
11195        // If "/system/lib64/apkname" exists, assume that is the per-package
11196        // native library directory to use; otherwise use "/system/lib/apkname".
11197        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11198        setBundledAppAbi(pkg, apkRoot, apkName);
11199        // pkgSetting might be null during rescan following uninstall of updates
11200        // to a bundled app, so accommodate that possibility.  The settings in
11201        // that case will be established later from the parsed package.
11202        //
11203        // If the settings aren't null, sync them up with what we've just derived.
11204        // note that apkRoot isn't stored in the package settings.
11205        if (pkgSetting != null) {
11206            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11207            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11208        }
11209    }
11210
11211    /**
11212     * Deduces the ABI of a bundled app and sets the relevant fields on the
11213     * parsed pkg object.
11214     *
11215     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11216     *        under which system libraries are installed.
11217     * @param apkName the name of the installed package.
11218     */
11219    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11220        final File codeFile = new File(pkg.codePath);
11221
11222        final boolean has64BitLibs;
11223        final boolean has32BitLibs;
11224        if (isApkFile(codeFile)) {
11225            // Monolithic install
11226            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11227            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11228        } else {
11229            // Cluster install
11230            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11231            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11232                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11233                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11234                has64BitLibs = (new File(rootDir, isa)).exists();
11235            } else {
11236                has64BitLibs = false;
11237            }
11238            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11239                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11240                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11241                has32BitLibs = (new File(rootDir, isa)).exists();
11242            } else {
11243                has32BitLibs = false;
11244            }
11245        }
11246
11247        if (has64BitLibs && !has32BitLibs) {
11248            // The package has 64 bit libs, but not 32 bit libs. Its primary
11249            // ABI should be 64 bit. We can safely assume here that the bundled
11250            // native libraries correspond to the most preferred ABI in the list.
11251
11252            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11253            pkg.applicationInfo.secondaryCpuAbi = null;
11254        } else if (has32BitLibs && !has64BitLibs) {
11255            // The package has 32 bit libs but not 64 bit libs. Its primary
11256            // ABI should be 32 bit.
11257
11258            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11259            pkg.applicationInfo.secondaryCpuAbi = null;
11260        } else if (has32BitLibs && has64BitLibs) {
11261            // The application has both 64 and 32 bit bundled libraries. We check
11262            // here that the app declares multiArch support, and warn if it doesn't.
11263            //
11264            // We will be lenient here and record both ABIs. The primary will be the
11265            // ABI that's higher on the list, i.e, a device that's configured to prefer
11266            // 64 bit apps will see a 64 bit primary ABI,
11267
11268            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11269                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11270            }
11271
11272            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11273                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11274                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11275            } else {
11276                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11277                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11278            }
11279        } else {
11280            pkg.applicationInfo.primaryCpuAbi = null;
11281            pkg.applicationInfo.secondaryCpuAbi = null;
11282        }
11283    }
11284
11285    private void killApplication(String pkgName, int appId, String reason) {
11286        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11287    }
11288
11289    private void killApplication(String pkgName, int appId, int userId, String reason) {
11290        // Request the ActivityManager to kill the process(only for existing packages)
11291        // so that we do not end up in a confused state while the user is still using the older
11292        // version of the application while the new one gets installed.
11293        final long token = Binder.clearCallingIdentity();
11294        try {
11295            IActivityManager am = ActivityManager.getService();
11296            if (am != null) {
11297                try {
11298                    am.killApplication(pkgName, appId, userId, reason);
11299                } catch (RemoteException e) {
11300                }
11301            }
11302        } finally {
11303            Binder.restoreCallingIdentity(token);
11304        }
11305    }
11306
11307    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11308        // Remove the parent package setting
11309        PackageSetting ps = (PackageSetting) pkg.mExtras;
11310        if (ps != null) {
11311            removePackageLI(ps, chatty);
11312        }
11313        // Remove the child package setting
11314        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11315        for (int i = 0; i < childCount; i++) {
11316            PackageParser.Package childPkg = pkg.childPackages.get(i);
11317            ps = (PackageSetting) childPkg.mExtras;
11318            if (ps != null) {
11319                removePackageLI(ps, chatty);
11320            }
11321        }
11322    }
11323
11324    void removePackageLI(PackageSetting ps, boolean chatty) {
11325        if (DEBUG_INSTALL) {
11326            if (chatty)
11327                Log.d(TAG, "Removing package " + ps.name);
11328        }
11329
11330        // writer
11331        synchronized (mPackages) {
11332            mPackages.remove(ps.name);
11333            final PackageParser.Package pkg = ps.pkg;
11334            if (pkg != null) {
11335                cleanPackageDataStructuresLILPw(pkg, chatty);
11336            }
11337        }
11338    }
11339
11340    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11341        if (DEBUG_INSTALL) {
11342            if (chatty)
11343                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11344        }
11345
11346        // writer
11347        synchronized (mPackages) {
11348            // Remove the parent package
11349            mPackages.remove(pkg.applicationInfo.packageName);
11350            cleanPackageDataStructuresLILPw(pkg, chatty);
11351
11352            // Remove the child packages
11353            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11354            for (int i = 0; i < childCount; i++) {
11355                PackageParser.Package childPkg = pkg.childPackages.get(i);
11356                mPackages.remove(childPkg.applicationInfo.packageName);
11357                cleanPackageDataStructuresLILPw(childPkg, chatty);
11358            }
11359        }
11360    }
11361
11362    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11363        int N = pkg.providers.size();
11364        StringBuilder r = null;
11365        int i;
11366        for (i=0; i<N; i++) {
11367            PackageParser.Provider p = pkg.providers.get(i);
11368            mProviders.removeProvider(p);
11369            if (p.info.authority == null) {
11370
11371                /* There was another ContentProvider with this authority when
11372                 * this app was installed so this authority is null,
11373                 * Ignore it as we don't have to unregister the provider.
11374                 */
11375                continue;
11376            }
11377            String names[] = p.info.authority.split(";");
11378            for (int j = 0; j < names.length; j++) {
11379                if (mProvidersByAuthority.get(names[j]) == p) {
11380                    mProvidersByAuthority.remove(names[j]);
11381                    if (DEBUG_REMOVE) {
11382                        if (chatty)
11383                            Log.d(TAG, "Unregistered content provider: " + names[j]
11384                                    + ", className = " + p.info.name + ", isSyncable = "
11385                                    + p.info.isSyncable);
11386                    }
11387                }
11388            }
11389            if (DEBUG_REMOVE && chatty) {
11390                if (r == null) {
11391                    r = new StringBuilder(256);
11392                } else {
11393                    r.append(' ');
11394                }
11395                r.append(p.info.name);
11396            }
11397        }
11398        if (r != null) {
11399            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11400        }
11401
11402        N = pkg.services.size();
11403        r = null;
11404        for (i=0; i<N; i++) {
11405            PackageParser.Service s = pkg.services.get(i);
11406            mServices.removeService(s);
11407            if (chatty) {
11408                if (r == null) {
11409                    r = new StringBuilder(256);
11410                } else {
11411                    r.append(' ');
11412                }
11413                r.append(s.info.name);
11414            }
11415        }
11416        if (r != null) {
11417            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11418        }
11419
11420        N = pkg.receivers.size();
11421        r = null;
11422        for (i=0; i<N; i++) {
11423            PackageParser.Activity a = pkg.receivers.get(i);
11424            mReceivers.removeActivity(a, "receiver");
11425            if (DEBUG_REMOVE && chatty) {
11426                if (r == null) {
11427                    r = new StringBuilder(256);
11428                } else {
11429                    r.append(' ');
11430                }
11431                r.append(a.info.name);
11432            }
11433        }
11434        if (r != null) {
11435            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11436        }
11437
11438        N = pkg.activities.size();
11439        r = null;
11440        for (i=0; i<N; i++) {
11441            PackageParser.Activity a = pkg.activities.get(i);
11442            mActivities.removeActivity(a, "activity");
11443            if (DEBUG_REMOVE && chatty) {
11444                if (r == null) {
11445                    r = new StringBuilder(256);
11446                } else {
11447                    r.append(' ');
11448                }
11449                r.append(a.info.name);
11450            }
11451        }
11452        if (r != null) {
11453            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11454        }
11455
11456        N = pkg.permissions.size();
11457        r = null;
11458        for (i=0; i<N; i++) {
11459            PackageParser.Permission p = pkg.permissions.get(i);
11460            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11461            if (bp == null) {
11462                bp = mSettings.mPermissionTrees.get(p.info.name);
11463            }
11464            if (bp != null && bp.perm == p) {
11465                bp.perm = null;
11466                if (DEBUG_REMOVE && chatty) {
11467                    if (r == null) {
11468                        r = new StringBuilder(256);
11469                    } else {
11470                        r.append(' ');
11471                    }
11472                    r.append(p.info.name);
11473                }
11474            }
11475            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11476                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11477                if (appOpPkgs != null) {
11478                    appOpPkgs.remove(pkg.packageName);
11479                }
11480            }
11481        }
11482        if (r != null) {
11483            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11484        }
11485
11486        N = pkg.requestedPermissions.size();
11487        r = null;
11488        for (i=0; i<N; i++) {
11489            String perm = pkg.requestedPermissions.get(i);
11490            BasePermission bp = mSettings.mPermissions.get(perm);
11491            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11492                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11493                if (appOpPkgs != null) {
11494                    appOpPkgs.remove(pkg.packageName);
11495                    if (appOpPkgs.isEmpty()) {
11496                        mAppOpPermissionPackages.remove(perm);
11497                    }
11498                }
11499            }
11500        }
11501        if (r != null) {
11502            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11503        }
11504
11505        N = pkg.instrumentation.size();
11506        r = null;
11507        for (i=0; i<N; i++) {
11508            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11509            mInstrumentation.remove(a.getComponentName());
11510            if (DEBUG_REMOVE && chatty) {
11511                if (r == null) {
11512                    r = new StringBuilder(256);
11513                } else {
11514                    r.append(' ');
11515                }
11516                r.append(a.info.name);
11517            }
11518        }
11519        if (r != null) {
11520            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11521        }
11522
11523        r = null;
11524        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11525            // Only system apps can hold shared libraries.
11526            if (pkg.libraryNames != null) {
11527                for (i = 0; i < pkg.libraryNames.size(); i++) {
11528                    String name = pkg.libraryNames.get(i);
11529                    if (removeSharedLibraryLPw(name, 0)) {
11530                        if (DEBUG_REMOVE && chatty) {
11531                            if (r == null) {
11532                                r = new StringBuilder(256);
11533                            } else {
11534                                r.append(' ');
11535                            }
11536                            r.append(name);
11537                        }
11538                    }
11539                }
11540            }
11541        }
11542
11543        r = null;
11544
11545        // Any package can hold static shared libraries.
11546        if (pkg.staticSharedLibName != null) {
11547            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11548                if (DEBUG_REMOVE && chatty) {
11549                    if (r == null) {
11550                        r = new StringBuilder(256);
11551                    } else {
11552                        r.append(' ');
11553                    }
11554                    r.append(pkg.staticSharedLibName);
11555                }
11556            }
11557        }
11558
11559        if (r != null) {
11560            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11561        }
11562    }
11563
11564    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11565        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11566            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11567                return true;
11568            }
11569        }
11570        return false;
11571    }
11572
11573    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11574    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11575    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11576
11577    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11578        // Update the parent permissions
11579        updatePermissionsLPw(pkg.packageName, pkg, flags);
11580        // Update the child permissions
11581        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11582        for (int i = 0; i < childCount; i++) {
11583            PackageParser.Package childPkg = pkg.childPackages.get(i);
11584            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11585        }
11586    }
11587
11588    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11589            int flags) {
11590        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11591        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11592    }
11593
11594    private void updatePermissionsLPw(String changingPkg,
11595            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11596        // Make sure there are no dangling permission trees.
11597        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11598        while (it.hasNext()) {
11599            final BasePermission bp = it.next();
11600            if (bp.packageSetting == null) {
11601                // We may not yet have parsed the package, so just see if
11602                // we still know about its settings.
11603                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11604            }
11605            if (bp.packageSetting == null) {
11606                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11607                        + " from package " + bp.sourcePackage);
11608                it.remove();
11609            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11610                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11611                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11612                            + " from package " + bp.sourcePackage);
11613                    flags |= UPDATE_PERMISSIONS_ALL;
11614                    it.remove();
11615                }
11616            }
11617        }
11618
11619        // Make sure all dynamic permissions have been assigned to a package,
11620        // and make sure there are no dangling permissions.
11621        it = mSettings.mPermissions.values().iterator();
11622        while (it.hasNext()) {
11623            final BasePermission bp = it.next();
11624            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11625                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11626                        + bp.name + " pkg=" + bp.sourcePackage
11627                        + " info=" + bp.pendingInfo);
11628                if (bp.packageSetting == null && bp.pendingInfo != null) {
11629                    final BasePermission tree = findPermissionTreeLP(bp.name);
11630                    if (tree != null && tree.perm != null) {
11631                        bp.packageSetting = tree.packageSetting;
11632                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11633                                new PermissionInfo(bp.pendingInfo));
11634                        bp.perm.info.packageName = tree.perm.info.packageName;
11635                        bp.perm.info.name = bp.name;
11636                        bp.uid = tree.uid;
11637                    }
11638                }
11639            }
11640            if (bp.packageSetting == null) {
11641                // We may not yet have parsed the package, so just see if
11642                // we still know about its settings.
11643                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11644            }
11645            if (bp.packageSetting == null) {
11646                Slog.w(TAG, "Removing dangling permission: " + bp.name
11647                        + " from package " + bp.sourcePackage);
11648                it.remove();
11649            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11650                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11651                    Slog.i(TAG, "Removing old permission: " + bp.name
11652                            + " from package " + bp.sourcePackage);
11653                    flags |= UPDATE_PERMISSIONS_ALL;
11654                    it.remove();
11655                }
11656            }
11657        }
11658
11659        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11660        // Now update the permissions for all packages, in particular
11661        // replace the granted permissions of the system packages.
11662        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11663            for (PackageParser.Package pkg : mPackages.values()) {
11664                if (pkg != pkgInfo) {
11665                    // Only replace for packages on requested volume
11666                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11667                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11668                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11669                    grantPermissionsLPw(pkg, replace, changingPkg);
11670                }
11671            }
11672        }
11673
11674        if (pkgInfo != null) {
11675            // Only replace for packages on requested volume
11676            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11677            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11678                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11679            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11680        }
11681        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11682    }
11683
11684    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11685            String packageOfInterest) {
11686        // IMPORTANT: There are two types of permissions: install and runtime.
11687        // Install time permissions are granted when the app is installed to
11688        // all device users and users added in the future. Runtime permissions
11689        // are granted at runtime explicitly to specific users. Normal and signature
11690        // protected permissions are install time permissions. Dangerous permissions
11691        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11692        // otherwise they are runtime permissions. This function does not manage
11693        // runtime permissions except for the case an app targeting Lollipop MR1
11694        // being upgraded to target a newer SDK, in which case dangerous permissions
11695        // are transformed from install time to runtime ones.
11696
11697        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11698        if (ps == null) {
11699            return;
11700        }
11701
11702        PermissionsState permissionsState = ps.getPermissionsState();
11703        PermissionsState origPermissions = permissionsState;
11704
11705        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11706
11707        boolean runtimePermissionsRevoked = false;
11708        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11709
11710        boolean changedInstallPermission = false;
11711
11712        if (replace) {
11713            ps.installPermissionsFixed = false;
11714            if (!ps.isSharedUser()) {
11715                origPermissions = new PermissionsState(permissionsState);
11716                permissionsState.reset();
11717            } else {
11718                // We need to know only about runtime permission changes since the
11719                // calling code always writes the install permissions state but
11720                // the runtime ones are written only if changed. The only cases of
11721                // changed runtime permissions here are promotion of an install to
11722                // runtime and revocation of a runtime from a shared user.
11723                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11724                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11725                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11726                    runtimePermissionsRevoked = true;
11727                }
11728            }
11729        }
11730
11731        permissionsState.setGlobalGids(mGlobalGids);
11732
11733        final int N = pkg.requestedPermissions.size();
11734        for (int i=0; i<N; i++) {
11735            final String name = pkg.requestedPermissions.get(i);
11736            final BasePermission bp = mSettings.mPermissions.get(name);
11737            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11738                    >= Build.VERSION_CODES.M;
11739
11740            if (DEBUG_INSTALL) {
11741                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11742            }
11743
11744            if (bp == null || bp.packageSetting == null) {
11745                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11746                    Slog.w(TAG, "Unknown permission " + name
11747                            + " in package " + pkg.packageName);
11748                }
11749                continue;
11750            }
11751
11752
11753            // Limit ephemeral apps to ephemeral allowed permissions.
11754            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11755                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11756                        + pkg.packageName);
11757                continue;
11758            }
11759
11760            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
11761                Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
11762                        + pkg.packageName);
11763                continue;
11764            }
11765
11766            final String perm = bp.name;
11767            boolean allowedSig = false;
11768            int grant = GRANT_DENIED;
11769
11770            // Keep track of app op permissions.
11771            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11772                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11773                if (pkgs == null) {
11774                    pkgs = new ArraySet<>();
11775                    mAppOpPermissionPackages.put(bp.name, pkgs);
11776                }
11777                pkgs.add(pkg.packageName);
11778            }
11779
11780            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11781            switch (level) {
11782                case PermissionInfo.PROTECTION_NORMAL: {
11783                    // For all apps normal permissions are install time ones.
11784                    grant = GRANT_INSTALL;
11785                } break;
11786
11787                case PermissionInfo.PROTECTION_DANGEROUS: {
11788                    // If a permission review is required for legacy apps we represent
11789                    // their permissions as always granted runtime ones since we need
11790                    // to keep the review required permission flag per user while an
11791                    // install permission's state is shared across all users.
11792                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11793                        // For legacy apps dangerous permissions are install time ones.
11794                        grant = GRANT_INSTALL;
11795                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11796                        // For legacy apps that became modern, install becomes runtime.
11797                        grant = GRANT_UPGRADE;
11798                    } else if (mPromoteSystemApps
11799                            && isSystemApp(ps)
11800                            && mExistingSystemPackages.contains(ps.name)) {
11801                        // For legacy system apps, install becomes runtime.
11802                        // We cannot check hasInstallPermission() for system apps since those
11803                        // permissions were granted implicitly and not persisted pre-M.
11804                        grant = GRANT_UPGRADE;
11805                    } else {
11806                        // For modern apps keep runtime permissions unchanged.
11807                        grant = GRANT_RUNTIME;
11808                    }
11809                } break;
11810
11811                case PermissionInfo.PROTECTION_SIGNATURE: {
11812                    // For all apps signature permissions are install time ones.
11813                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11814                    if (allowedSig) {
11815                        grant = GRANT_INSTALL;
11816                    }
11817                } break;
11818            }
11819
11820            if (DEBUG_INSTALL) {
11821                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11822            }
11823
11824            if (grant != GRANT_DENIED) {
11825                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11826                    // If this is an existing, non-system package, then
11827                    // we can't add any new permissions to it.
11828                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11829                        // Except...  if this is a permission that was added
11830                        // to the platform (note: need to only do this when
11831                        // updating the platform).
11832                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11833                            grant = GRANT_DENIED;
11834                        }
11835                    }
11836                }
11837
11838                switch (grant) {
11839                    case GRANT_INSTALL: {
11840                        // Revoke this as runtime permission to handle the case of
11841                        // a runtime permission being downgraded to an install one.
11842                        // Also in permission review mode we keep dangerous permissions
11843                        // for legacy apps
11844                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11845                            if (origPermissions.getRuntimePermissionState(
11846                                    bp.name, userId) != null) {
11847                                // Revoke the runtime permission and clear the flags.
11848                                origPermissions.revokeRuntimePermission(bp, userId);
11849                                origPermissions.updatePermissionFlags(bp, userId,
11850                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11851                                // If we revoked a permission permission, we have to write.
11852                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11853                                        changedRuntimePermissionUserIds, userId);
11854                            }
11855                        }
11856                        // Grant an install permission.
11857                        if (permissionsState.grantInstallPermission(bp) !=
11858                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11859                            changedInstallPermission = true;
11860                        }
11861                    } break;
11862
11863                    case GRANT_RUNTIME: {
11864                        // Grant previously granted runtime permissions.
11865                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11866                            PermissionState permissionState = origPermissions
11867                                    .getRuntimePermissionState(bp.name, userId);
11868                            int flags = permissionState != null
11869                                    ? permissionState.getFlags() : 0;
11870                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11871                                // Don't propagate the permission in a permission review mode if
11872                                // the former was revoked, i.e. marked to not propagate on upgrade.
11873                                // Note that in a permission review mode install permissions are
11874                                // represented as constantly granted runtime ones since we need to
11875                                // keep a per user state associated with the permission. Also the
11876                                // revoke on upgrade flag is no longer applicable and is reset.
11877                                final boolean revokeOnUpgrade = (flags & PackageManager
11878                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11879                                if (revokeOnUpgrade) {
11880                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11881                                    // Since we changed the flags, we have to write.
11882                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11883                                            changedRuntimePermissionUserIds, userId);
11884                                }
11885                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11886                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11887                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11888                                        // If we cannot put the permission as it was,
11889                                        // we have to write.
11890                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11891                                                changedRuntimePermissionUserIds, userId);
11892                                    }
11893                                }
11894
11895                                // If the app supports runtime permissions no need for a review.
11896                                if (mPermissionReviewRequired
11897                                        && appSupportsRuntimePermissions
11898                                        && (flags & PackageManager
11899                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11900                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11901                                    // Since we changed the flags, we have to write.
11902                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11903                                            changedRuntimePermissionUserIds, userId);
11904                                }
11905                            } else if (mPermissionReviewRequired
11906                                    && !appSupportsRuntimePermissions) {
11907                                // For legacy apps that need a permission review, every new
11908                                // runtime permission is granted but it is pending a review.
11909                                // We also need to review only platform defined runtime
11910                                // permissions as these are the only ones the platform knows
11911                                // how to disable the API to simulate revocation as legacy
11912                                // apps don't expect to run with revoked permissions.
11913                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11914                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11915                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11916                                        // We changed the flags, hence have to write.
11917                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11918                                                changedRuntimePermissionUserIds, userId);
11919                                    }
11920                                }
11921                                if (permissionsState.grantRuntimePermission(bp, userId)
11922                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11923                                    // We changed the permission, hence have to write.
11924                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11925                                            changedRuntimePermissionUserIds, userId);
11926                                }
11927                            }
11928                            // Propagate the permission flags.
11929                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11930                        }
11931                    } break;
11932
11933                    case GRANT_UPGRADE: {
11934                        // Grant runtime permissions for a previously held install permission.
11935                        PermissionState permissionState = origPermissions
11936                                .getInstallPermissionState(bp.name);
11937                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11938
11939                        if (origPermissions.revokeInstallPermission(bp)
11940                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11941                            // We will be transferring the permission flags, so clear them.
11942                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11943                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11944                            changedInstallPermission = true;
11945                        }
11946
11947                        // If the permission is not to be promoted to runtime we ignore it and
11948                        // also its other flags as they are not applicable to install permissions.
11949                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11950                            for (int userId : currentUserIds) {
11951                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11952                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11953                                    // Transfer the permission flags.
11954                                    permissionsState.updatePermissionFlags(bp, userId,
11955                                            flags, flags);
11956                                    // If we granted the permission, we have to write.
11957                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11958                                            changedRuntimePermissionUserIds, userId);
11959                                }
11960                            }
11961                        }
11962                    } break;
11963
11964                    default: {
11965                        if (packageOfInterest == null
11966                                || packageOfInterest.equals(pkg.packageName)) {
11967                            Slog.w(TAG, "Not granting permission " + perm
11968                                    + " to package " + pkg.packageName
11969                                    + " because it was previously installed without");
11970                        }
11971                    } break;
11972                }
11973            } else {
11974                if (permissionsState.revokeInstallPermission(bp) !=
11975                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11976                    // Also drop the permission flags.
11977                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11978                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11979                    changedInstallPermission = true;
11980                    Slog.i(TAG, "Un-granting permission " + perm
11981                            + " from package " + pkg.packageName
11982                            + " (protectionLevel=" + bp.protectionLevel
11983                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11984                            + ")");
11985                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11986                    // Don't print warning for app op permissions, since it is fine for them
11987                    // not to be granted, there is a UI for the user to decide.
11988                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11989                        Slog.w(TAG, "Not granting permission " + perm
11990                                + " to package " + pkg.packageName
11991                                + " (protectionLevel=" + bp.protectionLevel
11992                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11993                                + ")");
11994                    }
11995                }
11996            }
11997        }
11998
11999        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12000                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12001            // This is the first that we have heard about this package, so the
12002            // permissions we have now selected are fixed until explicitly
12003            // changed.
12004            ps.installPermissionsFixed = true;
12005        }
12006
12007        // Persist the runtime permissions state for users with changes. If permissions
12008        // were revoked because no app in the shared user declares them we have to
12009        // write synchronously to avoid losing runtime permissions state.
12010        for (int userId : changedRuntimePermissionUserIds) {
12011            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12012        }
12013    }
12014
12015    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12016        boolean allowed = false;
12017        final int NP = PackageParser.NEW_PERMISSIONS.length;
12018        for (int ip=0; ip<NP; ip++) {
12019            final PackageParser.NewPermissionInfo npi
12020                    = PackageParser.NEW_PERMISSIONS[ip];
12021            if (npi.name.equals(perm)
12022                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12023                allowed = true;
12024                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12025                        + pkg.packageName);
12026                break;
12027            }
12028        }
12029        return allowed;
12030    }
12031
12032    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12033            BasePermission bp, PermissionsState origPermissions) {
12034        boolean privilegedPermission = (bp.protectionLevel
12035                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12036        boolean privappPermissionsDisable =
12037                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12038        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12039        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12040        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12041                && !platformPackage && platformPermission) {
12042            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12043                    .getPrivAppPermissions(pkg.packageName);
12044            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12045            if (!whitelisted) {
12046                Slog.w(TAG, "Privileged permission " + perm + " for package "
12047                        + pkg.packageName + " - not in privapp-permissions whitelist");
12048                // Only report violations for apps on system image
12049                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12050                    if (mPrivappPermissionsViolations == null) {
12051                        mPrivappPermissionsViolations = new ArraySet<>();
12052                    }
12053                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12054                }
12055                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12056                    return false;
12057                }
12058            }
12059        }
12060        boolean allowed = (compareSignatures(
12061                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12062                        == PackageManager.SIGNATURE_MATCH)
12063                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12064                        == PackageManager.SIGNATURE_MATCH);
12065        if (!allowed && privilegedPermission) {
12066            if (isSystemApp(pkg)) {
12067                // For updated system applications, a system permission
12068                // is granted only if it had been defined by the original application.
12069                if (pkg.isUpdatedSystemApp()) {
12070                    final PackageSetting sysPs = mSettings
12071                            .getDisabledSystemPkgLPr(pkg.packageName);
12072                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12073                        // If the original was granted this permission, we take
12074                        // that grant decision as read and propagate it to the
12075                        // update.
12076                        if (sysPs.isPrivileged()) {
12077                            allowed = true;
12078                        }
12079                    } else {
12080                        // The system apk may have been updated with an older
12081                        // version of the one on the data partition, but which
12082                        // granted a new system permission that it didn't have
12083                        // before.  In this case we do want to allow the app to
12084                        // now get the new permission if the ancestral apk is
12085                        // privileged to get it.
12086                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12087                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12088                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12089                                    allowed = true;
12090                                    break;
12091                                }
12092                            }
12093                        }
12094                        // Also if a privileged parent package on the system image or any of
12095                        // its children requested a privileged permission, the updated child
12096                        // packages can also get the permission.
12097                        if (pkg.parentPackage != null) {
12098                            final PackageSetting disabledSysParentPs = mSettings
12099                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12100                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12101                                    && disabledSysParentPs.isPrivileged()) {
12102                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12103                                    allowed = true;
12104                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12105                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12106                                    for (int i = 0; i < count; i++) {
12107                                        PackageParser.Package disabledSysChildPkg =
12108                                                disabledSysParentPs.pkg.childPackages.get(i);
12109                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12110                                                perm)) {
12111                                            allowed = true;
12112                                            break;
12113                                        }
12114                                    }
12115                                }
12116                            }
12117                        }
12118                    }
12119                } else {
12120                    allowed = isPrivilegedApp(pkg);
12121                }
12122            }
12123        }
12124        if (!allowed) {
12125            if (!allowed && (bp.protectionLevel
12126                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12127                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12128                // If this was a previously normal/dangerous permission that got moved
12129                // to a system permission as part of the runtime permission redesign, then
12130                // we still want to blindly grant it to old apps.
12131                allowed = true;
12132            }
12133            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12134                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12135                // If this permission is to be granted to the system installer and
12136                // this app is an installer, then it gets the permission.
12137                allowed = true;
12138            }
12139            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12140                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12141                // If this permission is to be granted to the system verifier and
12142                // this app is a verifier, then it gets the permission.
12143                allowed = true;
12144            }
12145            if (!allowed && (bp.protectionLevel
12146                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12147                    && isSystemApp(pkg)) {
12148                // Any pre-installed system app is allowed to get this permission.
12149                allowed = true;
12150            }
12151            if (!allowed && (bp.protectionLevel
12152                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12153                // For development permissions, a development permission
12154                // is granted only if it was already granted.
12155                allowed = origPermissions.hasInstallPermission(perm);
12156            }
12157            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12158                    && pkg.packageName.equals(mSetupWizardPackage)) {
12159                // If this permission is to be granted to the system setup wizard and
12160                // this app is a setup wizard, then it gets the permission.
12161                allowed = true;
12162            }
12163        }
12164        return allowed;
12165    }
12166
12167    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12168        final int permCount = pkg.requestedPermissions.size();
12169        for (int j = 0; j < permCount; j++) {
12170            String requestedPermission = pkg.requestedPermissions.get(j);
12171            if (permission.equals(requestedPermission)) {
12172                return true;
12173            }
12174        }
12175        return false;
12176    }
12177
12178    final class ActivityIntentResolver
12179            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12180        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12181                boolean defaultOnly, int userId) {
12182            if (!sUserManager.exists(userId)) return null;
12183            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12184            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12185        }
12186
12187        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12188                int userId) {
12189            if (!sUserManager.exists(userId)) return null;
12190            mFlags = flags;
12191            return super.queryIntent(intent, resolvedType,
12192                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12193                    userId);
12194        }
12195
12196        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12197                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12198            if (!sUserManager.exists(userId)) return null;
12199            if (packageActivities == null) {
12200                return null;
12201            }
12202            mFlags = flags;
12203            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12204            final int N = packageActivities.size();
12205            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12206                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12207
12208            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12209            for (int i = 0; i < N; ++i) {
12210                intentFilters = packageActivities.get(i).intents;
12211                if (intentFilters != null && intentFilters.size() > 0) {
12212                    PackageParser.ActivityIntentInfo[] array =
12213                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12214                    intentFilters.toArray(array);
12215                    listCut.add(array);
12216                }
12217            }
12218            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12219        }
12220
12221        /**
12222         * Finds a privileged activity that matches the specified activity names.
12223         */
12224        private PackageParser.Activity findMatchingActivity(
12225                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12226            for (PackageParser.Activity sysActivity : activityList) {
12227                if (sysActivity.info.name.equals(activityInfo.name)) {
12228                    return sysActivity;
12229                }
12230                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12231                    return sysActivity;
12232                }
12233                if (sysActivity.info.targetActivity != null) {
12234                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12235                        return sysActivity;
12236                    }
12237                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12238                        return sysActivity;
12239                    }
12240                }
12241            }
12242            return null;
12243        }
12244
12245        public class IterGenerator<E> {
12246            public Iterator<E> generate(ActivityIntentInfo info) {
12247                return null;
12248            }
12249        }
12250
12251        public class ActionIterGenerator extends IterGenerator<String> {
12252            @Override
12253            public Iterator<String> generate(ActivityIntentInfo info) {
12254                return info.actionsIterator();
12255            }
12256        }
12257
12258        public class CategoriesIterGenerator extends IterGenerator<String> {
12259            @Override
12260            public Iterator<String> generate(ActivityIntentInfo info) {
12261                return info.categoriesIterator();
12262            }
12263        }
12264
12265        public class SchemesIterGenerator extends IterGenerator<String> {
12266            @Override
12267            public Iterator<String> generate(ActivityIntentInfo info) {
12268                return info.schemesIterator();
12269            }
12270        }
12271
12272        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12273            @Override
12274            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12275                return info.authoritiesIterator();
12276            }
12277        }
12278
12279        /**
12280         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12281         * MODIFIED. Do not pass in a list that should not be changed.
12282         */
12283        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12284                IterGenerator<T> generator, Iterator<T> searchIterator) {
12285            // loop through the set of actions; every one must be found in the intent filter
12286            while (searchIterator.hasNext()) {
12287                // we must have at least one filter in the list to consider a match
12288                if (intentList.size() == 0) {
12289                    break;
12290                }
12291
12292                final T searchAction = searchIterator.next();
12293
12294                // loop through the set of intent filters
12295                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12296                while (intentIter.hasNext()) {
12297                    final ActivityIntentInfo intentInfo = intentIter.next();
12298                    boolean selectionFound = false;
12299
12300                    // loop through the intent filter's selection criteria; at least one
12301                    // of them must match the searched criteria
12302                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12303                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12304                        final T intentSelection = intentSelectionIter.next();
12305                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12306                            selectionFound = true;
12307                            break;
12308                        }
12309                    }
12310
12311                    // the selection criteria wasn't found in this filter's set; this filter
12312                    // is not a potential match
12313                    if (!selectionFound) {
12314                        intentIter.remove();
12315                    }
12316                }
12317            }
12318        }
12319
12320        private boolean isProtectedAction(ActivityIntentInfo filter) {
12321            final Iterator<String> actionsIter = filter.actionsIterator();
12322            while (actionsIter != null && actionsIter.hasNext()) {
12323                final String filterAction = actionsIter.next();
12324                if (PROTECTED_ACTIONS.contains(filterAction)) {
12325                    return true;
12326                }
12327            }
12328            return false;
12329        }
12330
12331        /**
12332         * Adjusts the priority of the given intent filter according to policy.
12333         * <p>
12334         * <ul>
12335         * <li>The priority for non privileged applications is capped to '0'</li>
12336         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12337         * <li>The priority for unbundled updates to privileged applications is capped to the
12338         *      priority defined on the system partition</li>
12339         * </ul>
12340         * <p>
12341         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12342         * allowed to obtain any priority on any action.
12343         */
12344        private void adjustPriority(
12345                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12346            // nothing to do; priority is fine as-is
12347            if (intent.getPriority() <= 0) {
12348                return;
12349            }
12350
12351            final ActivityInfo activityInfo = intent.activity.info;
12352            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12353
12354            final boolean privilegedApp =
12355                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12356            if (!privilegedApp) {
12357                // non-privileged applications can never define a priority >0
12358                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
12359                        + " package: " + applicationInfo.packageName
12360                        + " activity: " + intent.activity.className
12361                        + " origPrio: " + intent.getPriority());
12362                intent.setPriority(0);
12363                return;
12364            }
12365
12366            if (systemActivities == null) {
12367                // the system package is not disabled; we're parsing the system partition
12368                if (isProtectedAction(intent)) {
12369                    if (mDeferProtectedFilters) {
12370                        // We can't deal with these just yet. No component should ever obtain a
12371                        // >0 priority for a protected actions, with ONE exception -- the setup
12372                        // wizard. The setup wizard, however, cannot be known until we're able to
12373                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12374                        // until all intent filters have been processed. Chicken, meet egg.
12375                        // Let the filter temporarily have a high priority and rectify the
12376                        // priorities after all system packages have been scanned.
12377                        mProtectedFilters.add(intent);
12378                        if (DEBUG_FILTERS) {
12379                            Slog.i(TAG, "Protected action; save for later;"
12380                                    + " package: " + applicationInfo.packageName
12381                                    + " activity: " + intent.activity.className
12382                                    + " origPrio: " + intent.getPriority());
12383                        }
12384                        return;
12385                    } else {
12386                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12387                            Slog.i(TAG, "No setup wizard;"
12388                                + " All protected intents capped to priority 0");
12389                        }
12390                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12391                            if (DEBUG_FILTERS) {
12392                                Slog.i(TAG, "Found setup wizard;"
12393                                    + " allow priority " + intent.getPriority() + ";"
12394                                    + " package: " + intent.activity.info.packageName
12395                                    + " activity: " + intent.activity.className
12396                                    + " priority: " + intent.getPriority());
12397                            }
12398                            // setup wizard gets whatever it wants
12399                            return;
12400                        }
12401                        Slog.w(TAG, "Protected action; cap priority to 0;"
12402                                + " package: " + intent.activity.info.packageName
12403                                + " activity: " + intent.activity.className
12404                                + " origPrio: " + intent.getPriority());
12405                        intent.setPriority(0);
12406                        return;
12407                    }
12408                }
12409                // privileged apps on the system image get whatever priority they request
12410                return;
12411            }
12412
12413            // privileged app unbundled update ... try to find the same activity
12414            final PackageParser.Activity foundActivity =
12415                    findMatchingActivity(systemActivities, activityInfo);
12416            if (foundActivity == null) {
12417                // this is a new activity; it cannot obtain >0 priority
12418                if (DEBUG_FILTERS) {
12419                    Slog.i(TAG, "New activity; cap priority to 0;"
12420                            + " package: " + applicationInfo.packageName
12421                            + " activity: " + intent.activity.className
12422                            + " origPrio: " + intent.getPriority());
12423                }
12424                intent.setPriority(0);
12425                return;
12426            }
12427
12428            // found activity, now check for filter equivalence
12429
12430            // a shallow copy is enough; we modify the list, not its contents
12431            final List<ActivityIntentInfo> intentListCopy =
12432                    new ArrayList<>(foundActivity.intents);
12433            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12434
12435            // find matching action subsets
12436            final Iterator<String> actionsIterator = intent.actionsIterator();
12437            if (actionsIterator != null) {
12438                getIntentListSubset(
12439                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12440                if (intentListCopy.size() == 0) {
12441                    // no more intents to match; we're not equivalent
12442                    if (DEBUG_FILTERS) {
12443                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12444                                + " package: " + applicationInfo.packageName
12445                                + " activity: " + intent.activity.className
12446                                + " origPrio: " + intent.getPriority());
12447                    }
12448                    intent.setPriority(0);
12449                    return;
12450                }
12451            }
12452
12453            // find matching category subsets
12454            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12455            if (categoriesIterator != null) {
12456                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12457                        categoriesIterator);
12458                if (intentListCopy.size() == 0) {
12459                    // no more intents to match; we're not equivalent
12460                    if (DEBUG_FILTERS) {
12461                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12462                                + " package: " + applicationInfo.packageName
12463                                + " activity: " + intent.activity.className
12464                                + " origPrio: " + intent.getPriority());
12465                    }
12466                    intent.setPriority(0);
12467                    return;
12468                }
12469            }
12470
12471            // find matching schemes subsets
12472            final Iterator<String> schemesIterator = intent.schemesIterator();
12473            if (schemesIterator != null) {
12474                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12475                        schemesIterator);
12476                if (intentListCopy.size() == 0) {
12477                    // no more intents to match; we're not equivalent
12478                    if (DEBUG_FILTERS) {
12479                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12480                                + " package: " + applicationInfo.packageName
12481                                + " activity: " + intent.activity.className
12482                                + " origPrio: " + intent.getPriority());
12483                    }
12484                    intent.setPriority(0);
12485                    return;
12486                }
12487            }
12488
12489            // find matching authorities subsets
12490            final Iterator<IntentFilter.AuthorityEntry>
12491                    authoritiesIterator = intent.authoritiesIterator();
12492            if (authoritiesIterator != null) {
12493                getIntentListSubset(intentListCopy,
12494                        new AuthoritiesIterGenerator(),
12495                        authoritiesIterator);
12496                if (intentListCopy.size() == 0) {
12497                    // no more intents to match; we're not equivalent
12498                    if (DEBUG_FILTERS) {
12499                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12500                                + " package: " + applicationInfo.packageName
12501                                + " activity: " + intent.activity.className
12502                                + " origPrio: " + intent.getPriority());
12503                    }
12504                    intent.setPriority(0);
12505                    return;
12506                }
12507            }
12508
12509            // we found matching filter(s); app gets the max priority of all intents
12510            int cappedPriority = 0;
12511            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12512                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12513            }
12514            if (intent.getPriority() > cappedPriority) {
12515                if (DEBUG_FILTERS) {
12516                    Slog.i(TAG, "Found matching filter(s);"
12517                            + " cap priority to " + cappedPriority + ";"
12518                            + " package: " + applicationInfo.packageName
12519                            + " activity: " + intent.activity.className
12520                            + " origPrio: " + intent.getPriority());
12521                }
12522                intent.setPriority(cappedPriority);
12523                return;
12524            }
12525            // all this for nothing; the requested priority was <= what was on the system
12526        }
12527
12528        public final void addActivity(PackageParser.Activity a, String type) {
12529            mActivities.put(a.getComponentName(), a);
12530            if (DEBUG_SHOW_INFO)
12531                Log.v(
12532                TAG, "  " + type + " " +
12533                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12534            if (DEBUG_SHOW_INFO)
12535                Log.v(TAG, "    Class=" + a.info.name);
12536            final int NI = a.intents.size();
12537            for (int j=0; j<NI; j++) {
12538                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12539                if ("activity".equals(type)) {
12540                    final PackageSetting ps =
12541                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12542                    final List<PackageParser.Activity> systemActivities =
12543                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12544                    adjustPriority(systemActivities, intent);
12545                }
12546                if (DEBUG_SHOW_INFO) {
12547                    Log.v(TAG, "    IntentFilter:");
12548                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12549                }
12550                if (!intent.debugCheck()) {
12551                    Log.w(TAG, "==> For Activity " + a.info.name);
12552                }
12553                addFilter(intent);
12554            }
12555        }
12556
12557        public final void removeActivity(PackageParser.Activity a, String type) {
12558            mActivities.remove(a.getComponentName());
12559            if (DEBUG_SHOW_INFO) {
12560                Log.v(TAG, "  " + type + " "
12561                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12562                                : a.info.name) + ":");
12563                Log.v(TAG, "    Class=" + a.info.name);
12564            }
12565            final int NI = a.intents.size();
12566            for (int j=0; j<NI; j++) {
12567                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12568                if (DEBUG_SHOW_INFO) {
12569                    Log.v(TAG, "    IntentFilter:");
12570                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12571                }
12572                removeFilter(intent);
12573            }
12574        }
12575
12576        @Override
12577        protected boolean allowFilterResult(
12578                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12579            ActivityInfo filterAi = filter.activity.info;
12580            for (int i=dest.size()-1; i>=0; i--) {
12581                ActivityInfo destAi = dest.get(i).activityInfo;
12582                if (destAi.name == filterAi.name
12583                        && destAi.packageName == filterAi.packageName) {
12584                    return false;
12585                }
12586            }
12587            return true;
12588        }
12589
12590        @Override
12591        protected ActivityIntentInfo[] newArray(int size) {
12592            return new ActivityIntentInfo[size];
12593        }
12594
12595        @Override
12596        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12597            if (!sUserManager.exists(userId)) return true;
12598            PackageParser.Package p = filter.activity.owner;
12599            if (p != null) {
12600                PackageSetting ps = (PackageSetting)p.mExtras;
12601                if (ps != null) {
12602                    // System apps are never considered stopped for purposes of
12603                    // filtering, because there may be no way for the user to
12604                    // actually re-launch them.
12605                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12606                            && ps.getStopped(userId);
12607                }
12608            }
12609            return false;
12610        }
12611
12612        @Override
12613        protected boolean isPackageForFilter(String packageName,
12614                PackageParser.ActivityIntentInfo info) {
12615            return packageName.equals(info.activity.owner.packageName);
12616        }
12617
12618        @Override
12619        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12620                int match, int userId) {
12621            if (!sUserManager.exists(userId)) return null;
12622            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12623                return null;
12624            }
12625            final PackageParser.Activity activity = info.activity;
12626            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12627            if (ps == null) {
12628                return null;
12629            }
12630            final PackageUserState userState = ps.readUserState(userId);
12631            ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId);
12632            if (ai == null) {
12633                return null;
12634            }
12635            final boolean matchExplicitlyVisibleOnly =
12636                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12637            final boolean matchVisibleToInstantApp =
12638                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12639            final boolean componentVisible =
12640                    matchVisibleToInstantApp
12641                    && info.isVisibleToInstantApp()
12642                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12643            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12644            // throw out filters that aren't visible to ephemeral apps
12645            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12646                return null;
12647            }
12648            // throw out instant app filters if we're not explicitly requesting them
12649            if (!matchInstantApp && userState.instantApp) {
12650                return null;
12651            }
12652            // throw out instant app filters if updates are available; will trigger
12653            // instant app resolution
12654            if (userState.instantApp && ps.isUpdateAvailable()) {
12655                return null;
12656            }
12657            final ResolveInfo res = new ResolveInfo();
12658            res.activityInfo = ai;
12659            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12660                res.filter = info;
12661            }
12662            if (info != null) {
12663                res.handleAllWebDataURI = info.handleAllWebDataURI();
12664            }
12665            res.priority = info.getPriority();
12666            res.preferredOrder = activity.owner.mPreferredOrder;
12667            //System.out.println("Result: " + res.activityInfo.className +
12668            //                   " = " + res.priority);
12669            res.match = match;
12670            res.isDefault = info.hasDefault;
12671            res.labelRes = info.labelRes;
12672            res.nonLocalizedLabel = info.nonLocalizedLabel;
12673            if (userNeedsBadging(userId)) {
12674                res.noResourceId = true;
12675            } else {
12676                res.icon = info.icon;
12677            }
12678            res.iconResourceId = info.icon;
12679            res.system = res.activityInfo.applicationInfo.isSystemApp();
12680            res.isInstantAppAvailable = userState.instantApp;
12681            return res;
12682        }
12683
12684        @Override
12685        protected void sortResults(List<ResolveInfo> results) {
12686            Collections.sort(results, mResolvePrioritySorter);
12687        }
12688
12689        @Override
12690        protected void dumpFilter(PrintWriter out, String prefix,
12691                PackageParser.ActivityIntentInfo filter) {
12692            out.print(prefix); out.print(
12693                    Integer.toHexString(System.identityHashCode(filter.activity)));
12694                    out.print(' ');
12695                    filter.activity.printComponentShortName(out);
12696                    out.print(" filter ");
12697                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12698        }
12699
12700        @Override
12701        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12702            return filter.activity;
12703        }
12704
12705        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12706            PackageParser.Activity activity = (PackageParser.Activity)label;
12707            out.print(prefix); out.print(
12708                    Integer.toHexString(System.identityHashCode(activity)));
12709                    out.print(' ');
12710                    activity.printComponentShortName(out);
12711            if (count > 1) {
12712                out.print(" ("); out.print(count); out.print(" filters)");
12713            }
12714            out.println();
12715        }
12716
12717        // Keys are String (activity class name), values are Activity.
12718        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12719                = new ArrayMap<ComponentName, PackageParser.Activity>();
12720        private int mFlags;
12721    }
12722
12723    private final class ServiceIntentResolver
12724            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12725        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12726                boolean defaultOnly, int userId) {
12727            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12728            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12729        }
12730
12731        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12732                int userId) {
12733            if (!sUserManager.exists(userId)) return null;
12734            mFlags = flags;
12735            return super.queryIntent(intent, resolvedType,
12736                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12737                    userId);
12738        }
12739
12740        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12741                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12742            if (!sUserManager.exists(userId)) return null;
12743            if (packageServices == null) {
12744                return null;
12745            }
12746            mFlags = flags;
12747            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12748            final int N = packageServices.size();
12749            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12750                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12751
12752            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12753            for (int i = 0; i < N; ++i) {
12754                intentFilters = packageServices.get(i).intents;
12755                if (intentFilters != null && intentFilters.size() > 0) {
12756                    PackageParser.ServiceIntentInfo[] array =
12757                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12758                    intentFilters.toArray(array);
12759                    listCut.add(array);
12760                }
12761            }
12762            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12763        }
12764
12765        public final void addService(PackageParser.Service s) {
12766            mServices.put(s.getComponentName(), s);
12767            if (DEBUG_SHOW_INFO) {
12768                Log.v(TAG, "  "
12769                        + (s.info.nonLocalizedLabel != null
12770                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12771                Log.v(TAG, "    Class=" + s.info.name);
12772            }
12773            final int NI = s.intents.size();
12774            int j;
12775            for (j=0; j<NI; j++) {
12776                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12777                if (DEBUG_SHOW_INFO) {
12778                    Log.v(TAG, "    IntentFilter:");
12779                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12780                }
12781                if (!intent.debugCheck()) {
12782                    Log.w(TAG, "==> For Service " + s.info.name);
12783                }
12784                addFilter(intent);
12785            }
12786        }
12787
12788        public final void removeService(PackageParser.Service s) {
12789            mServices.remove(s.getComponentName());
12790            if (DEBUG_SHOW_INFO) {
12791                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12792                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12793                Log.v(TAG, "    Class=" + s.info.name);
12794            }
12795            final int NI = s.intents.size();
12796            int j;
12797            for (j=0; j<NI; j++) {
12798                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12799                if (DEBUG_SHOW_INFO) {
12800                    Log.v(TAG, "    IntentFilter:");
12801                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12802                }
12803                removeFilter(intent);
12804            }
12805        }
12806
12807        @Override
12808        protected boolean allowFilterResult(
12809                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12810            ServiceInfo filterSi = filter.service.info;
12811            for (int i=dest.size()-1; i>=0; i--) {
12812                ServiceInfo destAi = dest.get(i).serviceInfo;
12813                if (destAi.name == filterSi.name
12814                        && destAi.packageName == filterSi.packageName) {
12815                    return false;
12816                }
12817            }
12818            return true;
12819        }
12820
12821        @Override
12822        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12823            return new PackageParser.ServiceIntentInfo[size];
12824        }
12825
12826        @Override
12827        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12828            if (!sUserManager.exists(userId)) return true;
12829            PackageParser.Package p = filter.service.owner;
12830            if (p != null) {
12831                PackageSetting ps = (PackageSetting)p.mExtras;
12832                if (ps != null) {
12833                    // System apps are never considered stopped for purposes of
12834                    // filtering, because there may be no way for the user to
12835                    // actually re-launch them.
12836                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12837                            && ps.getStopped(userId);
12838                }
12839            }
12840            return false;
12841        }
12842
12843        @Override
12844        protected boolean isPackageForFilter(String packageName,
12845                PackageParser.ServiceIntentInfo info) {
12846            return packageName.equals(info.service.owner.packageName);
12847        }
12848
12849        @Override
12850        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12851                int match, int userId) {
12852            if (!sUserManager.exists(userId)) return null;
12853            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12854            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12855                return null;
12856            }
12857            final PackageParser.Service service = info.service;
12858            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12859            if (ps == null) {
12860                return null;
12861            }
12862            final PackageUserState userState = ps.readUserState(userId);
12863            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12864                    userState, userId);
12865            if (si == null) {
12866                return null;
12867            }
12868            final boolean matchVisibleToInstantApp =
12869                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12870            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12871            // throw out filters that aren't visible to ephemeral apps
12872            if (matchVisibleToInstantApp
12873                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12874                return null;
12875            }
12876            // throw out ephemeral filters if we're not explicitly requesting them
12877            if (!isInstantApp && userState.instantApp) {
12878                return null;
12879            }
12880            // throw out instant app filters if updates are available; will trigger
12881            // instant app resolution
12882            if (userState.instantApp && ps.isUpdateAvailable()) {
12883                return null;
12884            }
12885            final ResolveInfo res = new ResolveInfo();
12886            res.serviceInfo = si;
12887            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12888                res.filter = filter;
12889            }
12890            res.priority = info.getPriority();
12891            res.preferredOrder = service.owner.mPreferredOrder;
12892            res.match = match;
12893            res.isDefault = info.hasDefault;
12894            res.labelRes = info.labelRes;
12895            res.nonLocalizedLabel = info.nonLocalizedLabel;
12896            res.icon = info.icon;
12897            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12898            return res;
12899        }
12900
12901        @Override
12902        protected void sortResults(List<ResolveInfo> results) {
12903            Collections.sort(results, mResolvePrioritySorter);
12904        }
12905
12906        @Override
12907        protected void dumpFilter(PrintWriter out, String prefix,
12908                PackageParser.ServiceIntentInfo filter) {
12909            out.print(prefix); out.print(
12910                    Integer.toHexString(System.identityHashCode(filter.service)));
12911                    out.print(' ');
12912                    filter.service.printComponentShortName(out);
12913                    out.print(" filter ");
12914                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12915        }
12916
12917        @Override
12918        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12919            return filter.service;
12920        }
12921
12922        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12923            PackageParser.Service service = (PackageParser.Service)label;
12924            out.print(prefix); out.print(
12925                    Integer.toHexString(System.identityHashCode(service)));
12926                    out.print(' ');
12927                    service.printComponentShortName(out);
12928            if (count > 1) {
12929                out.print(" ("); out.print(count); out.print(" filters)");
12930            }
12931            out.println();
12932        }
12933
12934//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12935//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12936//            final List<ResolveInfo> retList = Lists.newArrayList();
12937//            while (i.hasNext()) {
12938//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12939//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12940//                    retList.add(resolveInfo);
12941//                }
12942//            }
12943//            return retList;
12944//        }
12945
12946        // Keys are String (activity class name), values are Activity.
12947        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12948                = new ArrayMap<ComponentName, PackageParser.Service>();
12949        private int mFlags;
12950    }
12951
12952    private final class ProviderIntentResolver
12953            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12954        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12955                boolean defaultOnly, int userId) {
12956            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12957            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12958        }
12959
12960        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12961                int userId) {
12962            if (!sUserManager.exists(userId))
12963                return null;
12964            mFlags = flags;
12965            return super.queryIntent(intent, resolvedType,
12966                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12967                    userId);
12968        }
12969
12970        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12971                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12972            if (!sUserManager.exists(userId))
12973                return null;
12974            if (packageProviders == null) {
12975                return null;
12976            }
12977            mFlags = flags;
12978            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12979            final int N = packageProviders.size();
12980            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12981                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12982
12983            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12984            for (int i = 0; i < N; ++i) {
12985                intentFilters = packageProviders.get(i).intents;
12986                if (intentFilters != null && intentFilters.size() > 0) {
12987                    PackageParser.ProviderIntentInfo[] array =
12988                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12989                    intentFilters.toArray(array);
12990                    listCut.add(array);
12991                }
12992            }
12993            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12994        }
12995
12996        public final void addProvider(PackageParser.Provider p) {
12997            if (mProviders.containsKey(p.getComponentName())) {
12998                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12999                return;
13000            }
13001
13002            mProviders.put(p.getComponentName(), p);
13003            if (DEBUG_SHOW_INFO) {
13004                Log.v(TAG, "  "
13005                        + (p.info.nonLocalizedLabel != null
13006                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13007                Log.v(TAG, "    Class=" + p.info.name);
13008            }
13009            final int NI = p.intents.size();
13010            int j;
13011            for (j = 0; j < NI; j++) {
13012                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13013                if (DEBUG_SHOW_INFO) {
13014                    Log.v(TAG, "    IntentFilter:");
13015                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13016                }
13017                if (!intent.debugCheck()) {
13018                    Log.w(TAG, "==> For Provider " + p.info.name);
13019                }
13020                addFilter(intent);
13021            }
13022        }
13023
13024        public final void removeProvider(PackageParser.Provider p) {
13025            mProviders.remove(p.getComponentName());
13026            if (DEBUG_SHOW_INFO) {
13027                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13028                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13029                Log.v(TAG, "    Class=" + p.info.name);
13030            }
13031            final int NI = p.intents.size();
13032            int j;
13033            for (j = 0; j < NI; j++) {
13034                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13035                if (DEBUG_SHOW_INFO) {
13036                    Log.v(TAG, "    IntentFilter:");
13037                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13038                }
13039                removeFilter(intent);
13040            }
13041        }
13042
13043        @Override
13044        protected boolean allowFilterResult(
13045                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13046            ProviderInfo filterPi = filter.provider.info;
13047            for (int i = dest.size() - 1; i >= 0; i--) {
13048                ProviderInfo destPi = dest.get(i).providerInfo;
13049                if (destPi.name == filterPi.name
13050                        && destPi.packageName == filterPi.packageName) {
13051                    return false;
13052                }
13053            }
13054            return true;
13055        }
13056
13057        @Override
13058        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13059            return new PackageParser.ProviderIntentInfo[size];
13060        }
13061
13062        @Override
13063        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13064            if (!sUserManager.exists(userId))
13065                return true;
13066            PackageParser.Package p = filter.provider.owner;
13067            if (p != null) {
13068                PackageSetting ps = (PackageSetting) p.mExtras;
13069                if (ps != null) {
13070                    // System apps are never considered stopped for purposes of
13071                    // filtering, because there may be no way for the user to
13072                    // actually re-launch them.
13073                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13074                            && ps.getStopped(userId);
13075                }
13076            }
13077            return false;
13078        }
13079
13080        @Override
13081        protected boolean isPackageForFilter(String packageName,
13082                PackageParser.ProviderIntentInfo info) {
13083            return packageName.equals(info.provider.owner.packageName);
13084        }
13085
13086        @Override
13087        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13088                int match, int userId) {
13089            if (!sUserManager.exists(userId))
13090                return null;
13091            final PackageParser.ProviderIntentInfo info = filter;
13092            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13093                return null;
13094            }
13095            final PackageParser.Provider provider = info.provider;
13096            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13097            if (ps == null) {
13098                return null;
13099            }
13100            final PackageUserState userState = ps.readUserState(userId);
13101            final boolean matchVisibleToInstantApp =
13102                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13103            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13104            // throw out filters that aren't visible to instant applications
13105            if (matchVisibleToInstantApp
13106                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13107                return null;
13108            }
13109            // throw out instant application filters if we're not explicitly requesting them
13110            if (!isInstantApp && userState.instantApp) {
13111                return null;
13112            }
13113            // throw out instant application filters if updates are available; will trigger
13114            // instant application resolution
13115            if (userState.instantApp && ps.isUpdateAvailable()) {
13116                return null;
13117            }
13118            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13119                    userState, userId);
13120            if (pi == null) {
13121                return null;
13122            }
13123            final ResolveInfo res = new ResolveInfo();
13124            res.providerInfo = pi;
13125            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13126                res.filter = filter;
13127            }
13128            res.priority = info.getPriority();
13129            res.preferredOrder = provider.owner.mPreferredOrder;
13130            res.match = match;
13131            res.isDefault = info.hasDefault;
13132            res.labelRes = info.labelRes;
13133            res.nonLocalizedLabel = info.nonLocalizedLabel;
13134            res.icon = info.icon;
13135            res.system = res.providerInfo.applicationInfo.isSystemApp();
13136            return res;
13137        }
13138
13139        @Override
13140        protected void sortResults(List<ResolveInfo> results) {
13141            Collections.sort(results, mResolvePrioritySorter);
13142        }
13143
13144        @Override
13145        protected void dumpFilter(PrintWriter out, String prefix,
13146                PackageParser.ProviderIntentInfo filter) {
13147            out.print(prefix);
13148            out.print(
13149                    Integer.toHexString(System.identityHashCode(filter.provider)));
13150            out.print(' ');
13151            filter.provider.printComponentShortName(out);
13152            out.print(" filter ");
13153            out.println(Integer.toHexString(System.identityHashCode(filter)));
13154        }
13155
13156        @Override
13157        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13158            return filter.provider;
13159        }
13160
13161        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13162            PackageParser.Provider provider = (PackageParser.Provider)label;
13163            out.print(prefix); out.print(
13164                    Integer.toHexString(System.identityHashCode(provider)));
13165                    out.print(' ');
13166                    provider.printComponentShortName(out);
13167            if (count > 1) {
13168                out.print(" ("); out.print(count); out.print(" filters)");
13169            }
13170            out.println();
13171        }
13172
13173        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13174                = new ArrayMap<ComponentName, PackageParser.Provider>();
13175        private int mFlags;
13176    }
13177
13178    static final class EphemeralIntentResolver
13179            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13180        /**
13181         * The result that has the highest defined order. Ordering applies on a
13182         * per-package basis. Mapping is from package name to Pair of order and
13183         * EphemeralResolveInfo.
13184         * <p>
13185         * NOTE: This is implemented as a field variable for convenience and efficiency.
13186         * By having a field variable, we're able to track filter ordering as soon as
13187         * a non-zero order is defined. Otherwise, multiple loops across the result set
13188         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13189         * this needs to be contained entirely within {@link #filterResults}.
13190         */
13191        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13192
13193        @Override
13194        protected AuxiliaryResolveInfo[] newArray(int size) {
13195            return new AuxiliaryResolveInfo[size];
13196        }
13197
13198        @Override
13199        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13200            return true;
13201        }
13202
13203        @Override
13204        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13205                int userId) {
13206            if (!sUserManager.exists(userId)) {
13207                return null;
13208            }
13209            final String packageName = responseObj.resolveInfo.getPackageName();
13210            final Integer order = responseObj.getOrder();
13211            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13212                    mOrderResult.get(packageName);
13213            // ordering is enabled and this item's order isn't high enough
13214            if (lastOrderResult != null && lastOrderResult.first >= order) {
13215                return null;
13216            }
13217            final InstantAppResolveInfo res = responseObj.resolveInfo;
13218            if (order > 0) {
13219                // non-zero order, enable ordering
13220                mOrderResult.put(packageName, new Pair<>(order, res));
13221            }
13222            return responseObj;
13223        }
13224
13225        @Override
13226        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13227            // only do work if ordering is enabled [most of the time it won't be]
13228            if (mOrderResult.size() == 0) {
13229                return;
13230            }
13231            int resultSize = results.size();
13232            for (int i = 0; i < resultSize; i++) {
13233                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13234                final String packageName = info.getPackageName();
13235                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13236                if (savedInfo == null) {
13237                    // package doesn't having ordering
13238                    continue;
13239                }
13240                if (savedInfo.second == info) {
13241                    // circled back to the highest ordered item; remove from order list
13242                    mOrderResult.remove(savedInfo);
13243                    if (mOrderResult.size() == 0) {
13244                        // no more ordered items
13245                        break;
13246                    }
13247                    continue;
13248                }
13249                // item has a worse order, remove it from the result list
13250                results.remove(i);
13251                resultSize--;
13252                i--;
13253            }
13254        }
13255    }
13256
13257    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13258            new Comparator<ResolveInfo>() {
13259        public int compare(ResolveInfo r1, ResolveInfo r2) {
13260            int v1 = r1.priority;
13261            int v2 = r2.priority;
13262            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13263            if (v1 != v2) {
13264                return (v1 > v2) ? -1 : 1;
13265            }
13266            v1 = r1.preferredOrder;
13267            v2 = r2.preferredOrder;
13268            if (v1 != v2) {
13269                return (v1 > v2) ? -1 : 1;
13270            }
13271            if (r1.isDefault != r2.isDefault) {
13272                return r1.isDefault ? -1 : 1;
13273            }
13274            v1 = r1.match;
13275            v2 = r2.match;
13276            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13277            if (v1 != v2) {
13278                return (v1 > v2) ? -1 : 1;
13279            }
13280            if (r1.system != r2.system) {
13281                return r1.system ? -1 : 1;
13282            }
13283            if (r1.activityInfo != null) {
13284                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13285            }
13286            if (r1.serviceInfo != null) {
13287                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13288            }
13289            if (r1.providerInfo != null) {
13290                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13291            }
13292            return 0;
13293        }
13294    };
13295
13296    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13297            new Comparator<ProviderInfo>() {
13298        public int compare(ProviderInfo p1, ProviderInfo p2) {
13299            final int v1 = p1.initOrder;
13300            final int v2 = p2.initOrder;
13301            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13302        }
13303    };
13304
13305    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13306            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13307            final int[] userIds) {
13308        mHandler.post(new Runnable() {
13309            @Override
13310            public void run() {
13311                try {
13312                    final IActivityManager am = ActivityManager.getService();
13313                    if (am == null) return;
13314                    final int[] resolvedUserIds;
13315                    if (userIds == null) {
13316                        resolvedUserIds = am.getRunningUserIds();
13317                    } else {
13318                        resolvedUserIds = userIds;
13319                    }
13320                    for (int id : resolvedUserIds) {
13321                        final Intent intent = new Intent(action,
13322                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13323                        if (extras != null) {
13324                            intent.putExtras(extras);
13325                        }
13326                        if (targetPkg != null) {
13327                            intent.setPackage(targetPkg);
13328                        }
13329                        // Modify the UID when posting to other users
13330                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13331                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13332                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13333                            intent.putExtra(Intent.EXTRA_UID, uid);
13334                        }
13335                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13336                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13337                        if (DEBUG_BROADCASTS) {
13338                            RuntimeException here = new RuntimeException("here");
13339                            here.fillInStackTrace();
13340                            Slog.d(TAG, "Sending to user " + id + ": "
13341                                    + intent.toShortString(false, true, false, false)
13342                                    + " " + intent.getExtras(), here);
13343                        }
13344                        am.broadcastIntent(null, intent, null, finishedReceiver,
13345                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13346                                null, finishedReceiver != null, false, id);
13347                    }
13348                } catch (RemoteException ex) {
13349                }
13350            }
13351        });
13352    }
13353
13354    /**
13355     * Check if the external storage media is available. This is true if there
13356     * is a mounted external storage medium or if the external storage is
13357     * emulated.
13358     */
13359    private boolean isExternalMediaAvailable() {
13360        return mMediaMounted || Environment.isExternalStorageEmulated();
13361    }
13362
13363    @Override
13364    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13365        // writer
13366        synchronized (mPackages) {
13367            if (!isExternalMediaAvailable()) {
13368                // If the external storage is no longer mounted at this point,
13369                // the caller may not have been able to delete all of this
13370                // packages files and can not delete any more.  Bail.
13371                return null;
13372            }
13373            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13374            if (lastPackage != null) {
13375                pkgs.remove(lastPackage);
13376            }
13377            if (pkgs.size() > 0) {
13378                return pkgs.get(0);
13379            }
13380        }
13381        return null;
13382    }
13383
13384    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13385        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13386                userId, andCode ? 1 : 0, packageName);
13387        if (mSystemReady) {
13388            msg.sendToTarget();
13389        } else {
13390            if (mPostSystemReadyMessages == null) {
13391                mPostSystemReadyMessages = new ArrayList<>();
13392            }
13393            mPostSystemReadyMessages.add(msg);
13394        }
13395    }
13396
13397    void startCleaningPackages() {
13398        // reader
13399        if (!isExternalMediaAvailable()) {
13400            return;
13401        }
13402        synchronized (mPackages) {
13403            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13404                return;
13405            }
13406        }
13407        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13408        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13409        IActivityManager am = ActivityManager.getService();
13410        if (am != null) {
13411            int dcsUid = -1;
13412            synchronized (mPackages) {
13413                if (!mDefaultContainerWhitelisted) {
13414                    mDefaultContainerWhitelisted = true;
13415                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13416                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13417                }
13418            }
13419            try {
13420                if (dcsUid > 0) {
13421                    am.backgroundWhitelistUid(dcsUid);
13422                }
13423                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13424                        UserHandle.USER_SYSTEM);
13425            } catch (RemoteException e) {
13426            }
13427        }
13428    }
13429
13430    @Override
13431    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13432            int installFlags, String installerPackageName, int userId) {
13433        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13434
13435        final int callingUid = Binder.getCallingUid();
13436        enforceCrossUserPermission(callingUid, userId,
13437                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13438
13439        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13440            try {
13441                if (observer != null) {
13442                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13443                }
13444            } catch (RemoteException re) {
13445            }
13446            return;
13447        }
13448
13449        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13450            installFlags |= PackageManager.INSTALL_FROM_ADB;
13451
13452        } else {
13453            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13454            // about installerPackageName.
13455
13456            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13457            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13458        }
13459
13460        UserHandle user;
13461        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13462            user = UserHandle.ALL;
13463        } else {
13464            user = new UserHandle(userId);
13465        }
13466
13467        // Only system components can circumvent runtime permissions when installing.
13468        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13469                && mContext.checkCallingOrSelfPermission(Manifest.permission
13470                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13471            throw new SecurityException("You need the "
13472                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13473                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13474        }
13475
13476        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13477                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13478            throw new IllegalArgumentException(
13479                    "New installs into ASEC containers no longer supported");
13480        }
13481
13482        final File originFile = new File(originPath);
13483        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13484
13485        final Message msg = mHandler.obtainMessage(INIT_COPY);
13486        final VerificationInfo verificationInfo = new VerificationInfo(
13487                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13488        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13489                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13490                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13491                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13492        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13493        msg.obj = params;
13494
13495        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13496                System.identityHashCode(msg.obj));
13497        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13498                System.identityHashCode(msg.obj));
13499
13500        mHandler.sendMessage(msg);
13501    }
13502
13503
13504    /**
13505     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13506     * it is acting on behalf on an enterprise or the user).
13507     *
13508     * Note that the ordering of the conditionals in this method is important. The checks we perform
13509     * are as follows, in this order:
13510     *
13511     * 1) If the install is being performed by a system app, we can trust the app to have set the
13512     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13513     *    what it is.
13514     * 2) If the install is being performed by a device or profile owner app, the install reason
13515     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13516     *    set the install reason correctly. If the app targets an older SDK version where install
13517     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13518     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13519     * 3) In all other cases, the install is being performed by a regular app that is neither part
13520     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13521     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13522     *    set to enterprise policy and if so, change it to unknown instead.
13523     */
13524    private int fixUpInstallReason(String installerPackageName, int installerUid,
13525            int installReason) {
13526        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13527                == PERMISSION_GRANTED) {
13528            // If the install is being performed by a system app, we trust that app to have set the
13529            // install reason correctly.
13530            return installReason;
13531        }
13532
13533        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13534            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13535        if (dpm != null) {
13536            ComponentName owner = null;
13537            try {
13538                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13539                if (owner == null) {
13540                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13541                }
13542            } catch (RemoteException e) {
13543            }
13544            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13545                // If the install is being performed by a device or profile owner, the install
13546                // reason should be enterprise policy.
13547                return PackageManager.INSTALL_REASON_POLICY;
13548            }
13549        }
13550
13551        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13552            // If the install is being performed by a regular app (i.e. neither system app nor
13553            // device or profile owner), we have no reason to believe that the app is acting on
13554            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13555            // change it to unknown instead.
13556            return PackageManager.INSTALL_REASON_UNKNOWN;
13557        }
13558
13559        // If the install is being performed by a regular app and the install reason was set to any
13560        // value but enterprise policy, leave the install reason unchanged.
13561        return installReason;
13562    }
13563
13564    void installStage(String packageName, File stagedDir, String stagedCid,
13565            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13566            String installerPackageName, int installerUid, UserHandle user,
13567            Certificate[][] certificates) {
13568        if (DEBUG_EPHEMERAL) {
13569            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13570                Slog.d(TAG, "Ephemeral install of " + packageName);
13571            }
13572        }
13573        final VerificationInfo verificationInfo = new VerificationInfo(
13574                sessionParams.originatingUri, sessionParams.referrerUri,
13575                sessionParams.originatingUid, installerUid);
13576
13577        final OriginInfo origin;
13578        if (stagedDir != null) {
13579            origin = OriginInfo.fromStagedFile(stagedDir);
13580        } else {
13581            origin = OriginInfo.fromStagedContainer(stagedCid);
13582        }
13583
13584        final Message msg = mHandler.obtainMessage(INIT_COPY);
13585        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13586                sessionParams.installReason);
13587        final InstallParams params = new InstallParams(origin, null, observer,
13588                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13589                verificationInfo, user, sessionParams.abiOverride,
13590                sessionParams.grantedRuntimePermissions, certificates, installReason);
13591        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13592        msg.obj = params;
13593
13594        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13595                System.identityHashCode(msg.obj));
13596        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13597                System.identityHashCode(msg.obj));
13598
13599        mHandler.sendMessage(msg);
13600    }
13601
13602    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13603            int userId) {
13604        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13605        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13606    }
13607
13608    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
13609        if (ArrayUtils.isEmpty(userIds)) {
13610            return;
13611        }
13612        Bundle extras = new Bundle(1);
13613        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13614        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13615
13616        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13617                packageName, extras, 0, null, null, userIds);
13618        if (isSystem) {
13619            mHandler.post(() -> {
13620                        for (int userId : userIds) {
13621                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13622                        }
13623                    }
13624            );
13625        }
13626    }
13627
13628    /**
13629     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13630     * automatically without needing an explicit launch.
13631     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13632     */
13633    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13634        // If user is not running, the app didn't miss any broadcast
13635        if (!mUserManagerInternal.isUserRunning(userId)) {
13636            return;
13637        }
13638        final IActivityManager am = ActivityManager.getService();
13639        try {
13640            // Deliver LOCKED_BOOT_COMPLETED first
13641            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13642                    .setPackage(packageName);
13643            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13644            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13645                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13646
13647            // Deliver BOOT_COMPLETED only if user is unlocked
13648            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13649                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13650                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13651                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13652            }
13653        } catch (RemoteException e) {
13654            throw e.rethrowFromSystemServer();
13655        }
13656    }
13657
13658    @Override
13659    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13660            int userId) {
13661        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13662        PackageSetting pkgSetting;
13663        final int uid = Binder.getCallingUid();
13664        enforceCrossUserPermission(uid, userId,
13665                true /* requireFullPermission */, true /* checkShell */,
13666                "setApplicationHiddenSetting for user " + userId);
13667
13668        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13669            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13670            return false;
13671        }
13672
13673        long callingId = Binder.clearCallingIdentity();
13674        try {
13675            boolean sendAdded = false;
13676            boolean sendRemoved = false;
13677            // writer
13678            synchronized (mPackages) {
13679                pkgSetting = mSettings.mPackages.get(packageName);
13680                if (pkgSetting == null) {
13681                    return false;
13682                }
13683                // Do not allow "android" is being disabled
13684                if ("android".equals(packageName)) {
13685                    Slog.w(TAG, "Cannot hide package: android");
13686                    return false;
13687                }
13688                // Cannot hide static shared libs as they are considered
13689                // a part of the using app (emulating static linking). Also
13690                // static libs are installed always on internal storage.
13691                PackageParser.Package pkg = mPackages.get(packageName);
13692                if (pkg != null && pkg.staticSharedLibName != null) {
13693                    Slog.w(TAG, "Cannot hide package: " + packageName
13694                            + " providing static shared library: "
13695                            + pkg.staticSharedLibName);
13696                    return false;
13697                }
13698                // Only allow protected packages to hide themselves.
13699                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13700                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13701                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13702                    return false;
13703                }
13704
13705                if (pkgSetting.getHidden(userId) != hidden) {
13706                    pkgSetting.setHidden(hidden, userId);
13707                    mSettings.writePackageRestrictionsLPr(userId);
13708                    if (hidden) {
13709                        sendRemoved = true;
13710                    } else {
13711                        sendAdded = true;
13712                    }
13713                }
13714            }
13715            if (sendAdded) {
13716                sendPackageAddedForUser(packageName, pkgSetting, userId);
13717                return true;
13718            }
13719            if (sendRemoved) {
13720                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13721                        "hiding pkg");
13722                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13723                return true;
13724            }
13725        } finally {
13726            Binder.restoreCallingIdentity(callingId);
13727        }
13728        return false;
13729    }
13730
13731    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13732            int userId) {
13733        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13734        info.removedPackage = packageName;
13735        info.installerPackageName = pkgSetting.installerPackageName;
13736        info.removedUsers = new int[] {userId};
13737        info.broadcastUsers = new int[] {userId};
13738        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13739        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13740    }
13741
13742    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13743        if (pkgList.length > 0) {
13744            Bundle extras = new Bundle(1);
13745            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13746
13747            sendPackageBroadcast(
13748                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13749                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13750                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13751                    new int[] {userId});
13752        }
13753    }
13754
13755    /**
13756     * Returns true if application is not found or there was an error. Otherwise it returns
13757     * the hidden state of the package for the given user.
13758     */
13759    @Override
13760    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13761        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13762        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13763                true /* requireFullPermission */, false /* checkShell */,
13764                "getApplicationHidden for user " + userId);
13765        PackageSetting pkgSetting;
13766        long callingId = Binder.clearCallingIdentity();
13767        try {
13768            // writer
13769            synchronized (mPackages) {
13770                pkgSetting = mSettings.mPackages.get(packageName);
13771                if (pkgSetting == null) {
13772                    return true;
13773                }
13774                return pkgSetting.getHidden(userId);
13775            }
13776        } finally {
13777            Binder.restoreCallingIdentity(callingId);
13778        }
13779    }
13780
13781    /**
13782     * @hide
13783     */
13784    @Override
13785    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13786            int installReason) {
13787        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13788                null);
13789        PackageSetting pkgSetting;
13790        final int uid = Binder.getCallingUid();
13791        enforceCrossUserPermission(uid, userId,
13792                true /* requireFullPermission */, true /* checkShell */,
13793                "installExistingPackage for user " + userId);
13794        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13795            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13796        }
13797
13798        long callingId = Binder.clearCallingIdentity();
13799        try {
13800            boolean installed = false;
13801            final boolean instantApp =
13802                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13803            final boolean fullApp =
13804                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13805
13806            // writer
13807            synchronized (mPackages) {
13808                pkgSetting = mSettings.mPackages.get(packageName);
13809                if (pkgSetting == null) {
13810                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13811                }
13812                if (!pkgSetting.getInstalled(userId)) {
13813                    pkgSetting.setInstalled(true, userId);
13814                    pkgSetting.setHidden(false, userId);
13815                    pkgSetting.setInstallReason(installReason, userId);
13816                    mSettings.writePackageRestrictionsLPr(userId);
13817                    mSettings.writeKernelMappingLPr(pkgSetting);
13818                    installed = true;
13819                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13820                    // upgrade app from instant to full; we don't allow app downgrade
13821                    installed = true;
13822                }
13823                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13824            }
13825
13826            if (installed) {
13827                if (pkgSetting.pkg != null) {
13828                    synchronized (mInstallLock) {
13829                        // We don't need to freeze for a brand new install
13830                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13831                    }
13832                }
13833                sendPackageAddedForUser(packageName, pkgSetting, userId);
13834                synchronized (mPackages) {
13835                    updateSequenceNumberLP(packageName, new int[]{ userId });
13836                }
13837            }
13838        } finally {
13839            Binder.restoreCallingIdentity(callingId);
13840        }
13841
13842        return PackageManager.INSTALL_SUCCEEDED;
13843    }
13844
13845    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13846            boolean instantApp, boolean fullApp) {
13847        // no state specified; do nothing
13848        if (!instantApp && !fullApp) {
13849            return;
13850        }
13851        if (userId != UserHandle.USER_ALL) {
13852            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13853                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13854            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13855                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13856            }
13857        } else {
13858            for (int currentUserId : sUserManager.getUserIds()) {
13859                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13860                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13861                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13862                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13863                }
13864            }
13865        }
13866    }
13867
13868    boolean isUserRestricted(int userId, String restrictionKey) {
13869        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13870        if (restrictions.getBoolean(restrictionKey, false)) {
13871            Log.w(TAG, "User is restricted: " + restrictionKey);
13872            return true;
13873        }
13874        return false;
13875    }
13876
13877    @Override
13878    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13879            int userId) {
13880        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13881        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13882                true /* requireFullPermission */, true /* checkShell */,
13883                "setPackagesSuspended for user " + userId);
13884
13885        if (ArrayUtils.isEmpty(packageNames)) {
13886            return packageNames;
13887        }
13888
13889        // List of package names for whom the suspended state has changed.
13890        List<String> changedPackages = new ArrayList<>(packageNames.length);
13891        // List of package names for whom the suspended state is not set as requested in this
13892        // method.
13893        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13894        long callingId = Binder.clearCallingIdentity();
13895        try {
13896            for (int i = 0; i < packageNames.length; i++) {
13897                String packageName = packageNames[i];
13898                boolean changed = false;
13899                final int appId;
13900                synchronized (mPackages) {
13901                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13902                    if (pkgSetting == null) {
13903                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13904                                + "\". Skipping suspending/un-suspending.");
13905                        unactionedPackages.add(packageName);
13906                        continue;
13907                    }
13908                    appId = pkgSetting.appId;
13909                    if (pkgSetting.getSuspended(userId) != suspended) {
13910                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13911                            unactionedPackages.add(packageName);
13912                            continue;
13913                        }
13914                        pkgSetting.setSuspended(suspended, userId);
13915                        mSettings.writePackageRestrictionsLPr(userId);
13916                        changed = true;
13917                        changedPackages.add(packageName);
13918                    }
13919                }
13920
13921                if (changed && suspended) {
13922                    killApplication(packageName, UserHandle.getUid(userId, appId),
13923                            "suspending package");
13924                }
13925            }
13926        } finally {
13927            Binder.restoreCallingIdentity(callingId);
13928        }
13929
13930        if (!changedPackages.isEmpty()) {
13931            sendPackagesSuspendedForUser(changedPackages.toArray(
13932                    new String[changedPackages.size()]), userId, suspended);
13933        }
13934
13935        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13936    }
13937
13938    @Override
13939    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13940        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13941                true /* requireFullPermission */, false /* checkShell */,
13942                "isPackageSuspendedForUser for user " + userId);
13943        synchronized (mPackages) {
13944            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13945            if (pkgSetting == null) {
13946                throw new IllegalArgumentException("Unknown target package: " + packageName);
13947            }
13948            return pkgSetting.getSuspended(userId);
13949        }
13950    }
13951
13952    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13953        if (isPackageDeviceAdmin(packageName, userId)) {
13954            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13955                    + "\": has an active device admin");
13956            return false;
13957        }
13958
13959        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13960        if (packageName.equals(activeLauncherPackageName)) {
13961            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13962                    + "\": contains the active launcher");
13963            return false;
13964        }
13965
13966        if (packageName.equals(mRequiredInstallerPackage)) {
13967            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13968                    + "\": required for package installation");
13969            return false;
13970        }
13971
13972        if (packageName.equals(mRequiredUninstallerPackage)) {
13973            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13974                    + "\": required for package uninstallation");
13975            return false;
13976        }
13977
13978        if (packageName.equals(mRequiredVerifierPackage)) {
13979            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13980                    + "\": required for package verification");
13981            return false;
13982        }
13983
13984        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13985            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13986                    + "\": is the default dialer");
13987            return false;
13988        }
13989
13990        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13991            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13992                    + "\": protected package");
13993            return false;
13994        }
13995
13996        // Cannot suspend static shared libs as they are considered
13997        // a part of the using app (emulating static linking). Also
13998        // static libs are installed always on internal storage.
13999        PackageParser.Package pkg = mPackages.get(packageName);
14000        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14001            Slog.w(TAG, "Cannot suspend package: " + packageName
14002                    + " providing static shared library: "
14003                    + pkg.staticSharedLibName);
14004            return false;
14005        }
14006
14007        return true;
14008    }
14009
14010    private String getActiveLauncherPackageName(int userId) {
14011        Intent intent = new Intent(Intent.ACTION_MAIN);
14012        intent.addCategory(Intent.CATEGORY_HOME);
14013        ResolveInfo resolveInfo = resolveIntent(
14014                intent,
14015                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14016                PackageManager.MATCH_DEFAULT_ONLY,
14017                userId);
14018
14019        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14020    }
14021
14022    private String getDefaultDialerPackageName(int userId) {
14023        synchronized (mPackages) {
14024            return mSettings.getDefaultDialerPackageNameLPw(userId);
14025        }
14026    }
14027
14028    @Override
14029    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14030        mContext.enforceCallingOrSelfPermission(
14031                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14032                "Only package verification agents can verify applications");
14033
14034        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14035        final PackageVerificationResponse response = new PackageVerificationResponse(
14036                verificationCode, Binder.getCallingUid());
14037        msg.arg1 = id;
14038        msg.obj = response;
14039        mHandler.sendMessage(msg);
14040    }
14041
14042    @Override
14043    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14044            long millisecondsToDelay) {
14045        mContext.enforceCallingOrSelfPermission(
14046                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14047                "Only package verification agents can extend verification timeouts");
14048
14049        final PackageVerificationState state = mPendingVerification.get(id);
14050        final PackageVerificationResponse response = new PackageVerificationResponse(
14051                verificationCodeAtTimeout, Binder.getCallingUid());
14052
14053        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14054            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14055        }
14056        if (millisecondsToDelay < 0) {
14057            millisecondsToDelay = 0;
14058        }
14059        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14060                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14061            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14062        }
14063
14064        if ((state != null) && !state.timeoutExtended()) {
14065            state.extendTimeout();
14066
14067            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14068            msg.arg1 = id;
14069            msg.obj = response;
14070            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14071        }
14072    }
14073
14074    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14075            int verificationCode, UserHandle user) {
14076        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14077        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14078        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14079        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14080        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14081
14082        mContext.sendBroadcastAsUser(intent, user,
14083                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14084    }
14085
14086    private ComponentName matchComponentForVerifier(String packageName,
14087            List<ResolveInfo> receivers) {
14088        ActivityInfo targetReceiver = null;
14089
14090        final int NR = receivers.size();
14091        for (int i = 0; i < NR; i++) {
14092            final ResolveInfo info = receivers.get(i);
14093            if (info.activityInfo == null) {
14094                continue;
14095            }
14096
14097            if (packageName.equals(info.activityInfo.packageName)) {
14098                targetReceiver = info.activityInfo;
14099                break;
14100            }
14101        }
14102
14103        if (targetReceiver == null) {
14104            return null;
14105        }
14106
14107        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14108    }
14109
14110    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14111            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14112        if (pkgInfo.verifiers.length == 0) {
14113            return null;
14114        }
14115
14116        final int N = pkgInfo.verifiers.length;
14117        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14118        for (int i = 0; i < N; i++) {
14119            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14120
14121            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14122                    receivers);
14123            if (comp == null) {
14124                continue;
14125            }
14126
14127            final int verifierUid = getUidForVerifier(verifierInfo);
14128            if (verifierUid == -1) {
14129                continue;
14130            }
14131
14132            if (DEBUG_VERIFY) {
14133                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14134                        + " with the correct signature");
14135            }
14136            sufficientVerifiers.add(comp);
14137            verificationState.addSufficientVerifier(verifierUid);
14138        }
14139
14140        return sufficientVerifiers;
14141    }
14142
14143    private int getUidForVerifier(VerifierInfo verifierInfo) {
14144        synchronized (mPackages) {
14145            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14146            if (pkg == null) {
14147                return -1;
14148            } else if (pkg.mSignatures.length != 1) {
14149                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14150                        + " has more than one signature; ignoring");
14151                return -1;
14152            }
14153
14154            /*
14155             * If the public key of the package's signature does not match
14156             * our expected public key, then this is a different package and
14157             * we should skip.
14158             */
14159
14160            final byte[] expectedPublicKey;
14161            try {
14162                final Signature verifierSig = pkg.mSignatures[0];
14163                final PublicKey publicKey = verifierSig.getPublicKey();
14164                expectedPublicKey = publicKey.getEncoded();
14165            } catch (CertificateException e) {
14166                return -1;
14167            }
14168
14169            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14170
14171            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14172                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14173                        + " does not have the expected public key; ignoring");
14174                return -1;
14175            }
14176
14177            return pkg.applicationInfo.uid;
14178        }
14179    }
14180
14181    @Override
14182    public void finishPackageInstall(int token, boolean didLaunch) {
14183        enforceSystemOrRoot("Only the system is allowed to finish installs");
14184
14185        if (DEBUG_INSTALL) {
14186            Slog.v(TAG, "BM finishing package install for " + token);
14187        }
14188        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14189
14190        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14191        mHandler.sendMessage(msg);
14192    }
14193
14194    /**
14195     * Get the verification agent timeout.  Used for both the APK verifier and the
14196     * intent filter verifier.
14197     *
14198     * @return verification timeout in milliseconds
14199     */
14200    private long getVerificationTimeout() {
14201        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14202                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14203                DEFAULT_VERIFICATION_TIMEOUT);
14204    }
14205
14206    /**
14207     * Get the default verification agent response code.
14208     *
14209     * @return default verification response code
14210     */
14211    private int getDefaultVerificationResponse(UserHandle user) {
14212        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14213            return PackageManager.VERIFICATION_REJECT;
14214        }
14215        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14216                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14217                DEFAULT_VERIFICATION_RESPONSE);
14218    }
14219
14220    /**
14221     * Check whether or not package verification has been enabled.
14222     *
14223     * @return true if verification should be performed
14224     */
14225    private boolean isVerificationEnabled(int userId, int installFlags) {
14226        if (!DEFAULT_VERIFY_ENABLE) {
14227            return false;
14228        }
14229
14230        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14231
14232        // Check if installing from ADB
14233        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14234            // Do not run verification in a test harness environment
14235            if (ActivityManager.isRunningInTestHarness()) {
14236                return false;
14237            }
14238            if (ensureVerifyAppsEnabled) {
14239                return true;
14240            }
14241            // Check if the developer does not want package verification for ADB installs
14242            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14243                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14244                return false;
14245            }
14246        }
14247
14248        if (ensureVerifyAppsEnabled) {
14249            return true;
14250        }
14251
14252        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14253                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14254    }
14255
14256    @Override
14257    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14258            throws RemoteException {
14259        mContext.enforceCallingOrSelfPermission(
14260                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14261                "Only intentfilter verification agents can verify applications");
14262
14263        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14264        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14265                Binder.getCallingUid(), verificationCode, failedDomains);
14266        msg.arg1 = id;
14267        msg.obj = response;
14268        mHandler.sendMessage(msg);
14269    }
14270
14271    @Override
14272    public int getIntentVerificationStatus(String packageName, int userId) {
14273        synchronized (mPackages) {
14274            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14275        }
14276    }
14277
14278    @Override
14279    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14280        mContext.enforceCallingOrSelfPermission(
14281                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14282
14283        boolean result = false;
14284        synchronized (mPackages) {
14285            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14286        }
14287        if (result) {
14288            scheduleWritePackageRestrictionsLocked(userId);
14289        }
14290        return result;
14291    }
14292
14293    @Override
14294    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14295            String packageName) {
14296        synchronized (mPackages) {
14297            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14298        }
14299    }
14300
14301    @Override
14302    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14303        if (TextUtils.isEmpty(packageName)) {
14304            return ParceledListSlice.emptyList();
14305        }
14306        synchronized (mPackages) {
14307            PackageParser.Package pkg = mPackages.get(packageName);
14308            if (pkg == null || pkg.activities == null) {
14309                return ParceledListSlice.emptyList();
14310            }
14311            final int count = pkg.activities.size();
14312            ArrayList<IntentFilter> result = new ArrayList<>();
14313            for (int n=0; n<count; n++) {
14314                PackageParser.Activity activity = pkg.activities.get(n);
14315                if (activity.intents != null && activity.intents.size() > 0) {
14316                    result.addAll(activity.intents);
14317                }
14318            }
14319            return new ParceledListSlice<>(result);
14320        }
14321    }
14322
14323    @Override
14324    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14325        mContext.enforceCallingOrSelfPermission(
14326                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14327
14328        synchronized (mPackages) {
14329            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14330            if (packageName != null) {
14331                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
14332                        packageName, userId);
14333            }
14334            return result;
14335        }
14336    }
14337
14338    @Override
14339    public String getDefaultBrowserPackageName(int userId) {
14340        synchronized (mPackages) {
14341            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14342        }
14343    }
14344
14345    /**
14346     * Get the "allow unknown sources" setting.
14347     *
14348     * @return the current "allow unknown sources" setting
14349     */
14350    private int getUnknownSourcesSettings() {
14351        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14352                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14353                -1);
14354    }
14355
14356    @Override
14357    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14358        final int uid = Binder.getCallingUid();
14359        // writer
14360        synchronized (mPackages) {
14361            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14362            if (targetPackageSetting == null) {
14363                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14364            }
14365
14366            PackageSetting installerPackageSetting;
14367            if (installerPackageName != null) {
14368                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14369                if (installerPackageSetting == null) {
14370                    throw new IllegalArgumentException("Unknown installer package: "
14371                            + installerPackageName);
14372                }
14373            } else {
14374                installerPackageSetting = null;
14375            }
14376
14377            Signature[] callerSignature;
14378            Object obj = mSettings.getUserIdLPr(uid);
14379            if (obj != null) {
14380                if (obj instanceof SharedUserSetting) {
14381                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14382                } else if (obj instanceof PackageSetting) {
14383                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14384                } else {
14385                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
14386                }
14387            } else {
14388                throw new SecurityException("Unknown calling UID: " + uid);
14389            }
14390
14391            // Verify: can't set installerPackageName to a package that is
14392            // not signed with the same cert as the caller.
14393            if (installerPackageSetting != null) {
14394                if (compareSignatures(callerSignature,
14395                        installerPackageSetting.signatures.mSignatures)
14396                        != PackageManager.SIGNATURE_MATCH) {
14397                    throw new SecurityException(
14398                            "Caller does not have same cert as new installer package "
14399                            + installerPackageName);
14400                }
14401            }
14402
14403            // Verify: if target already has an installer package, it must
14404            // be signed with the same cert as the caller.
14405            if (targetPackageSetting.installerPackageName != null) {
14406                PackageSetting setting = mSettings.mPackages.get(
14407                        targetPackageSetting.installerPackageName);
14408                // If the currently set package isn't valid, then it's always
14409                // okay to change it.
14410                if (setting != null) {
14411                    if (compareSignatures(callerSignature,
14412                            setting.signatures.mSignatures)
14413                            != PackageManager.SIGNATURE_MATCH) {
14414                        throw new SecurityException(
14415                                "Caller does not have same cert as old installer package "
14416                                + targetPackageSetting.installerPackageName);
14417                    }
14418                }
14419            }
14420
14421            // Okay!
14422            targetPackageSetting.installerPackageName = installerPackageName;
14423            if (installerPackageName != null) {
14424                mSettings.mInstallerPackages.add(installerPackageName);
14425            }
14426            scheduleWriteSettingsLocked();
14427        }
14428    }
14429
14430    @Override
14431    public void setApplicationCategoryHint(String packageName, int categoryHint,
14432            String callerPackageName) {
14433        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14434                callerPackageName);
14435        synchronized (mPackages) {
14436            PackageSetting ps = mSettings.mPackages.get(packageName);
14437            if (ps == null) {
14438                throw new IllegalArgumentException("Unknown target package " + packageName);
14439            }
14440
14441            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14442                throw new IllegalArgumentException("Calling package " + callerPackageName
14443                        + " is not installer for " + packageName);
14444            }
14445
14446            if (ps.categoryHint != categoryHint) {
14447                ps.categoryHint = categoryHint;
14448                scheduleWriteSettingsLocked();
14449            }
14450        }
14451    }
14452
14453    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14454        // Queue up an async operation since the package installation may take a little while.
14455        mHandler.post(new Runnable() {
14456            public void run() {
14457                mHandler.removeCallbacks(this);
14458                 // Result object to be returned
14459                PackageInstalledInfo res = new PackageInstalledInfo();
14460                res.setReturnCode(currentStatus);
14461                res.uid = -1;
14462                res.pkg = null;
14463                res.removedInfo = null;
14464                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14465                    args.doPreInstall(res.returnCode);
14466                    synchronized (mInstallLock) {
14467                        installPackageTracedLI(args, res);
14468                    }
14469                    args.doPostInstall(res.returnCode, res.uid);
14470                }
14471
14472                // A restore should be performed at this point if (a) the install
14473                // succeeded, (b) the operation is not an update, and (c) the new
14474                // package has not opted out of backup participation.
14475                final boolean update = res.removedInfo != null
14476                        && res.removedInfo.removedPackage != null;
14477                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14478                boolean doRestore = !update
14479                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14480
14481                // Set up the post-install work request bookkeeping.  This will be used
14482                // and cleaned up by the post-install event handling regardless of whether
14483                // there's a restore pass performed.  Token values are >= 1.
14484                int token;
14485                if (mNextInstallToken < 0) mNextInstallToken = 1;
14486                token = mNextInstallToken++;
14487
14488                PostInstallData data = new PostInstallData(args, res);
14489                mRunningInstalls.put(token, data);
14490                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14491
14492                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14493                    // Pass responsibility to the Backup Manager.  It will perform a
14494                    // restore if appropriate, then pass responsibility back to the
14495                    // Package Manager to run the post-install observer callbacks
14496                    // and broadcasts.
14497                    IBackupManager bm = IBackupManager.Stub.asInterface(
14498                            ServiceManager.getService(Context.BACKUP_SERVICE));
14499                    if (bm != null) {
14500                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14501                                + " to BM for possible restore");
14502                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14503                        try {
14504                            // TODO: http://b/22388012
14505                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14506                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14507                            } else {
14508                                doRestore = false;
14509                            }
14510                        } catch (RemoteException e) {
14511                            // can't happen; the backup manager is local
14512                        } catch (Exception e) {
14513                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14514                            doRestore = false;
14515                        }
14516                    } else {
14517                        Slog.e(TAG, "Backup Manager not found!");
14518                        doRestore = false;
14519                    }
14520                }
14521
14522                if (!doRestore) {
14523                    // No restore possible, or the Backup Manager was mysteriously not
14524                    // available -- just fire the post-install work request directly.
14525                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14526
14527                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14528
14529                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14530                    mHandler.sendMessage(msg);
14531                }
14532            }
14533        });
14534    }
14535
14536    /**
14537     * Callback from PackageSettings whenever an app is first transitioned out of the
14538     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14539     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14540     * here whether the app is the target of an ongoing install, and only send the
14541     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14542     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14543     * handling.
14544     */
14545    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14546        // Serialize this with the rest of the install-process message chain.  In the
14547        // restore-at-install case, this Runnable will necessarily run before the
14548        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14549        // are coherent.  In the non-restore case, the app has already completed install
14550        // and been launched through some other means, so it is not in a problematic
14551        // state for observers to see the FIRST_LAUNCH signal.
14552        mHandler.post(new Runnable() {
14553            @Override
14554            public void run() {
14555                for (int i = 0; i < mRunningInstalls.size(); i++) {
14556                    final PostInstallData data = mRunningInstalls.valueAt(i);
14557                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14558                        continue;
14559                    }
14560                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14561                        // right package; but is it for the right user?
14562                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14563                            if (userId == data.res.newUsers[uIndex]) {
14564                                if (DEBUG_BACKUP) {
14565                                    Slog.i(TAG, "Package " + pkgName
14566                                            + " being restored so deferring FIRST_LAUNCH");
14567                                }
14568                                return;
14569                            }
14570                        }
14571                    }
14572                }
14573                // didn't find it, so not being restored
14574                if (DEBUG_BACKUP) {
14575                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14576                }
14577                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14578            }
14579        });
14580    }
14581
14582    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14583        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14584                installerPkg, null, userIds);
14585    }
14586
14587    private abstract class HandlerParams {
14588        private static final int MAX_RETRIES = 4;
14589
14590        /**
14591         * Number of times startCopy() has been attempted and had a non-fatal
14592         * error.
14593         */
14594        private int mRetries = 0;
14595
14596        /** User handle for the user requesting the information or installation. */
14597        private final UserHandle mUser;
14598        String traceMethod;
14599        int traceCookie;
14600
14601        HandlerParams(UserHandle user) {
14602            mUser = user;
14603        }
14604
14605        UserHandle getUser() {
14606            return mUser;
14607        }
14608
14609        HandlerParams setTraceMethod(String traceMethod) {
14610            this.traceMethod = traceMethod;
14611            return this;
14612        }
14613
14614        HandlerParams setTraceCookie(int traceCookie) {
14615            this.traceCookie = traceCookie;
14616            return this;
14617        }
14618
14619        final boolean startCopy() {
14620            boolean res;
14621            try {
14622                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14623
14624                if (++mRetries > MAX_RETRIES) {
14625                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14626                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14627                    handleServiceError();
14628                    return false;
14629                } else {
14630                    handleStartCopy();
14631                    res = true;
14632                }
14633            } catch (RemoteException e) {
14634                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14635                mHandler.sendEmptyMessage(MCS_RECONNECT);
14636                res = false;
14637            }
14638            handleReturnCode();
14639            return res;
14640        }
14641
14642        final void serviceError() {
14643            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14644            handleServiceError();
14645            handleReturnCode();
14646        }
14647
14648        abstract void handleStartCopy() throws RemoteException;
14649        abstract void handleServiceError();
14650        abstract void handleReturnCode();
14651    }
14652
14653    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14654        for (File path : paths) {
14655            try {
14656                mcs.clearDirectory(path.getAbsolutePath());
14657            } catch (RemoteException e) {
14658            }
14659        }
14660    }
14661
14662    static class OriginInfo {
14663        /**
14664         * Location where install is coming from, before it has been
14665         * copied/renamed into place. This could be a single monolithic APK
14666         * file, or a cluster directory. This location may be untrusted.
14667         */
14668        final File file;
14669        final String cid;
14670
14671        /**
14672         * Flag indicating that {@link #file} or {@link #cid} has already been
14673         * staged, meaning downstream users don't need to defensively copy the
14674         * contents.
14675         */
14676        final boolean staged;
14677
14678        /**
14679         * Flag indicating that {@link #file} or {@link #cid} is an already
14680         * installed app that is being moved.
14681         */
14682        final boolean existing;
14683
14684        final String resolvedPath;
14685        final File resolvedFile;
14686
14687        static OriginInfo fromNothing() {
14688            return new OriginInfo(null, null, false, false);
14689        }
14690
14691        static OriginInfo fromUntrustedFile(File file) {
14692            return new OriginInfo(file, null, false, false);
14693        }
14694
14695        static OriginInfo fromExistingFile(File file) {
14696            return new OriginInfo(file, null, false, true);
14697        }
14698
14699        static OriginInfo fromStagedFile(File file) {
14700            return new OriginInfo(file, null, true, false);
14701        }
14702
14703        static OriginInfo fromStagedContainer(String cid) {
14704            return new OriginInfo(null, cid, true, false);
14705        }
14706
14707        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14708            this.file = file;
14709            this.cid = cid;
14710            this.staged = staged;
14711            this.existing = existing;
14712
14713            if (cid != null) {
14714                resolvedPath = PackageHelper.getSdDir(cid);
14715                resolvedFile = new File(resolvedPath);
14716            } else if (file != null) {
14717                resolvedPath = file.getAbsolutePath();
14718                resolvedFile = file;
14719            } else {
14720                resolvedPath = null;
14721                resolvedFile = null;
14722            }
14723        }
14724    }
14725
14726    static class MoveInfo {
14727        final int moveId;
14728        final String fromUuid;
14729        final String toUuid;
14730        final String packageName;
14731        final String dataAppName;
14732        final int appId;
14733        final String seinfo;
14734        final int targetSdkVersion;
14735
14736        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14737                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14738            this.moveId = moveId;
14739            this.fromUuid = fromUuid;
14740            this.toUuid = toUuid;
14741            this.packageName = packageName;
14742            this.dataAppName = dataAppName;
14743            this.appId = appId;
14744            this.seinfo = seinfo;
14745            this.targetSdkVersion = targetSdkVersion;
14746        }
14747    }
14748
14749    static class VerificationInfo {
14750        /** A constant used to indicate that a uid value is not present. */
14751        public static final int NO_UID = -1;
14752
14753        /** URI referencing where the package was downloaded from. */
14754        final Uri originatingUri;
14755
14756        /** HTTP referrer URI associated with the originatingURI. */
14757        final Uri referrer;
14758
14759        /** UID of the application that the install request originated from. */
14760        final int originatingUid;
14761
14762        /** UID of application requesting the install */
14763        final int installerUid;
14764
14765        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14766            this.originatingUri = originatingUri;
14767            this.referrer = referrer;
14768            this.originatingUid = originatingUid;
14769            this.installerUid = installerUid;
14770        }
14771    }
14772
14773    class InstallParams extends HandlerParams {
14774        final OriginInfo origin;
14775        final MoveInfo move;
14776        final IPackageInstallObserver2 observer;
14777        int installFlags;
14778        final String installerPackageName;
14779        final String volumeUuid;
14780        private InstallArgs mArgs;
14781        private int mRet;
14782        final String packageAbiOverride;
14783        final String[] grantedRuntimePermissions;
14784        final VerificationInfo verificationInfo;
14785        final Certificate[][] certificates;
14786        final int installReason;
14787
14788        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14789                int installFlags, String installerPackageName, String volumeUuid,
14790                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14791                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14792            super(user);
14793            this.origin = origin;
14794            this.move = move;
14795            this.observer = observer;
14796            this.installFlags = installFlags;
14797            this.installerPackageName = installerPackageName;
14798            this.volumeUuid = volumeUuid;
14799            this.verificationInfo = verificationInfo;
14800            this.packageAbiOverride = packageAbiOverride;
14801            this.grantedRuntimePermissions = grantedPermissions;
14802            this.certificates = certificates;
14803            this.installReason = installReason;
14804        }
14805
14806        @Override
14807        public String toString() {
14808            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14809                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14810        }
14811
14812        private int installLocationPolicy(PackageInfoLite pkgLite) {
14813            String packageName = pkgLite.packageName;
14814            int installLocation = pkgLite.installLocation;
14815            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14816            // reader
14817            synchronized (mPackages) {
14818                // Currently installed package which the new package is attempting to replace or
14819                // null if no such package is installed.
14820                PackageParser.Package installedPkg = mPackages.get(packageName);
14821                // Package which currently owns the data which the new package will own if installed.
14822                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14823                // will be null whereas dataOwnerPkg will contain information about the package
14824                // which was uninstalled while keeping its data.
14825                PackageParser.Package dataOwnerPkg = installedPkg;
14826                if (dataOwnerPkg  == null) {
14827                    PackageSetting ps = mSettings.mPackages.get(packageName);
14828                    if (ps != null) {
14829                        dataOwnerPkg = ps.pkg;
14830                    }
14831                }
14832
14833                if (dataOwnerPkg != null) {
14834                    // If installed, the package will get access to data left on the device by its
14835                    // predecessor. As a security measure, this is permited only if this is not a
14836                    // version downgrade or if the predecessor package is marked as debuggable and
14837                    // a downgrade is explicitly requested.
14838                    //
14839                    // On debuggable platform builds, downgrades are permitted even for
14840                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14841                    // not offer security guarantees and thus it's OK to disable some security
14842                    // mechanisms to make debugging/testing easier on those builds. However, even on
14843                    // debuggable builds downgrades of packages are permitted only if requested via
14844                    // installFlags. This is because we aim to keep the behavior of debuggable
14845                    // platform builds as close as possible to the behavior of non-debuggable
14846                    // platform builds.
14847                    final boolean downgradeRequested =
14848                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14849                    final boolean packageDebuggable =
14850                                (dataOwnerPkg.applicationInfo.flags
14851                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14852                    final boolean downgradePermitted =
14853                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14854                    if (!downgradePermitted) {
14855                        try {
14856                            checkDowngrade(dataOwnerPkg, pkgLite);
14857                        } catch (PackageManagerException e) {
14858                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14859                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14860                        }
14861                    }
14862                }
14863
14864                if (installedPkg != null) {
14865                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14866                        // Check for updated system application.
14867                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14868                            if (onSd) {
14869                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14870                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14871                            }
14872                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14873                        } else {
14874                            if (onSd) {
14875                                // Install flag overrides everything.
14876                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14877                            }
14878                            // If current upgrade specifies particular preference
14879                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14880                                // Application explicitly specified internal.
14881                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14882                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14883                                // App explictly prefers external. Let policy decide
14884                            } else {
14885                                // Prefer previous location
14886                                if (isExternal(installedPkg)) {
14887                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14888                                }
14889                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14890                            }
14891                        }
14892                    } else {
14893                        // Invalid install. Return error code
14894                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14895                    }
14896                }
14897            }
14898            // All the special cases have been taken care of.
14899            // Return result based on recommended install location.
14900            if (onSd) {
14901                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14902            }
14903            return pkgLite.recommendedInstallLocation;
14904        }
14905
14906        /*
14907         * Invoke remote method to get package information and install
14908         * location values. Override install location based on default
14909         * policy if needed and then create install arguments based
14910         * on the install location.
14911         */
14912        public void handleStartCopy() throws RemoteException {
14913            int ret = PackageManager.INSTALL_SUCCEEDED;
14914
14915            // If we're already staged, we've firmly committed to an install location
14916            if (origin.staged) {
14917                if (origin.file != null) {
14918                    installFlags |= PackageManager.INSTALL_INTERNAL;
14919                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14920                } else if (origin.cid != null) {
14921                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14922                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14923                } else {
14924                    throw new IllegalStateException("Invalid stage location");
14925                }
14926            }
14927
14928            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14929            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14930            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14931            PackageInfoLite pkgLite = null;
14932
14933            if (onInt && onSd) {
14934                // Check if both bits are set.
14935                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14936                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14937            } else if (onSd && ephemeral) {
14938                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14939                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14940            } else {
14941                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14942                        packageAbiOverride);
14943
14944                if (DEBUG_EPHEMERAL && ephemeral) {
14945                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14946                }
14947
14948                /*
14949                 * If we have too little free space, try to free cache
14950                 * before giving up.
14951                 */
14952                if (!origin.staged && pkgLite.recommendedInstallLocation
14953                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14954                    // TODO: focus freeing disk space on the target device
14955                    final StorageManager storage = StorageManager.from(mContext);
14956                    final long lowThreshold = storage.getStorageLowBytes(
14957                            Environment.getDataDirectory());
14958
14959                    final long sizeBytes = mContainerService.calculateInstalledSize(
14960                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14961
14962                    try {
14963                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14964                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14965                                installFlags, packageAbiOverride);
14966                    } catch (InstallerException e) {
14967                        Slog.w(TAG, "Failed to free cache", e);
14968                    }
14969
14970                    /*
14971                     * The cache free must have deleted the file we
14972                     * downloaded to install.
14973                     *
14974                     * TODO: fix the "freeCache" call to not delete
14975                     *       the file we care about.
14976                     */
14977                    if (pkgLite.recommendedInstallLocation
14978                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14979                        pkgLite.recommendedInstallLocation
14980                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14981                    }
14982                }
14983            }
14984
14985            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14986                int loc = pkgLite.recommendedInstallLocation;
14987                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14988                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14989                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14990                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14991                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14992                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14993                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14994                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14995                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14996                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14997                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14998                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14999                } else {
15000                    // Override with defaults if needed.
15001                    loc = installLocationPolicy(pkgLite);
15002                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15003                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15004                    } else if (!onSd && !onInt) {
15005                        // Override install location with flags
15006                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15007                            // Set the flag to install on external media.
15008                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15009                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15010                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15011                            if (DEBUG_EPHEMERAL) {
15012                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15013                            }
15014                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15015                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15016                                    |PackageManager.INSTALL_INTERNAL);
15017                        } else {
15018                            // Make sure the flag for installing on external
15019                            // media is unset
15020                            installFlags |= PackageManager.INSTALL_INTERNAL;
15021                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15022                        }
15023                    }
15024                }
15025            }
15026
15027            final InstallArgs args = createInstallArgs(this);
15028            mArgs = args;
15029
15030            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15031                // TODO: http://b/22976637
15032                // Apps installed for "all" users use the device owner to verify the app
15033                UserHandle verifierUser = getUser();
15034                if (verifierUser == UserHandle.ALL) {
15035                    verifierUser = UserHandle.SYSTEM;
15036                }
15037
15038                /*
15039                 * Determine if we have any installed package verifiers. If we
15040                 * do, then we'll defer to them to verify the packages.
15041                 */
15042                final int requiredUid = mRequiredVerifierPackage == null ? -1
15043                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15044                                verifierUser.getIdentifier());
15045                if (!origin.existing && requiredUid != -1
15046                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
15047                    final Intent verification = new Intent(
15048                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15049                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15050                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15051                            PACKAGE_MIME_TYPE);
15052                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15053
15054                    // Query all live verifiers based on current user state
15055                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15056                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15057
15058                    if (DEBUG_VERIFY) {
15059                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15060                                + verification.toString() + " with " + pkgLite.verifiers.length
15061                                + " optional verifiers");
15062                    }
15063
15064                    final int verificationId = mPendingVerificationToken++;
15065
15066                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15067
15068                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15069                            installerPackageName);
15070
15071                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15072                            installFlags);
15073
15074                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15075                            pkgLite.packageName);
15076
15077                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15078                            pkgLite.versionCode);
15079
15080                    if (verificationInfo != null) {
15081                        if (verificationInfo.originatingUri != null) {
15082                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15083                                    verificationInfo.originatingUri);
15084                        }
15085                        if (verificationInfo.referrer != null) {
15086                            verification.putExtra(Intent.EXTRA_REFERRER,
15087                                    verificationInfo.referrer);
15088                        }
15089                        if (verificationInfo.originatingUid >= 0) {
15090                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15091                                    verificationInfo.originatingUid);
15092                        }
15093                        if (verificationInfo.installerUid >= 0) {
15094                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15095                                    verificationInfo.installerUid);
15096                        }
15097                    }
15098
15099                    final PackageVerificationState verificationState = new PackageVerificationState(
15100                            requiredUid, args);
15101
15102                    mPendingVerification.append(verificationId, verificationState);
15103
15104                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15105                            receivers, verificationState);
15106
15107                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15108                    final long idleDuration = getVerificationTimeout();
15109
15110                    /*
15111                     * If any sufficient verifiers were listed in the package
15112                     * manifest, attempt to ask them.
15113                     */
15114                    if (sufficientVerifiers != null) {
15115                        final int N = sufficientVerifiers.size();
15116                        if (N == 0) {
15117                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15118                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15119                        } else {
15120                            for (int i = 0; i < N; i++) {
15121                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15122                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15123                                        verifierComponent.getPackageName(), idleDuration,
15124                                        verifierUser.getIdentifier(), false, "package verifier");
15125
15126                                final Intent sufficientIntent = new Intent(verification);
15127                                sufficientIntent.setComponent(verifierComponent);
15128                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15129                            }
15130                        }
15131                    }
15132
15133                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15134                            mRequiredVerifierPackage, receivers);
15135                    if (ret == PackageManager.INSTALL_SUCCEEDED
15136                            && mRequiredVerifierPackage != null) {
15137                        Trace.asyncTraceBegin(
15138                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15139                        /*
15140                         * Send the intent to the required verification agent,
15141                         * but only start the verification timeout after the
15142                         * target BroadcastReceivers have run.
15143                         */
15144                        verification.setComponent(requiredVerifierComponent);
15145                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15146                                mRequiredVerifierPackage, idleDuration,
15147                                verifierUser.getIdentifier(), false, "package verifier");
15148                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15149                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15150                                new BroadcastReceiver() {
15151                                    @Override
15152                                    public void onReceive(Context context, Intent intent) {
15153                                        final Message msg = mHandler
15154                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15155                                        msg.arg1 = verificationId;
15156                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15157                                    }
15158                                }, null, 0, null, null);
15159
15160                        /*
15161                         * We don't want the copy to proceed until verification
15162                         * succeeds, so null out this field.
15163                         */
15164                        mArgs = null;
15165                    }
15166                } else {
15167                    /*
15168                     * No package verification is enabled, so immediately start
15169                     * the remote call to initiate copy using temporary file.
15170                     */
15171                    ret = args.copyApk(mContainerService, true);
15172                }
15173            }
15174
15175            mRet = ret;
15176        }
15177
15178        @Override
15179        void handleReturnCode() {
15180            // If mArgs is null, then MCS couldn't be reached. When it
15181            // reconnects, it will try again to install. At that point, this
15182            // will succeed.
15183            if (mArgs != null) {
15184                processPendingInstall(mArgs, mRet);
15185            }
15186        }
15187
15188        @Override
15189        void handleServiceError() {
15190            mArgs = createInstallArgs(this);
15191            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15192        }
15193
15194        public boolean isForwardLocked() {
15195            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15196        }
15197    }
15198
15199    /**
15200     * Used during creation of InstallArgs
15201     *
15202     * @param installFlags package installation flags
15203     * @return true if should be installed on external storage
15204     */
15205    private static boolean installOnExternalAsec(int installFlags) {
15206        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15207            return false;
15208        }
15209        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
15210            return true;
15211        }
15212        return false;
15213    }
15214
15215    /**
15216     * Used during creation of InstallArgs
15217     *
15218     * @param installFlags package installation flags
15219     * @return true if should be installed as forward locked
15220     */
15221    private static boolean installForwardLocked(int installFlags) {
15222        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15223    }
15224
15225    private InstallArgs createInstallArgs(InstallParams params) {
15226        if (params.move != null) {
15227            return new MoveInstallArgs(params);
15228        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15229            return new AsecInstallArgs(params);
15230        } else {
15231            return new FileInstallArgs(params);
15232        }
15233    }
15234
15235    /**
15236     * Create args that describe an existing installed package. Typically used
15237     * when cleaning up old installs, or used as a move source.
15238     */
15239    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15240            String resourcePath, String[] instructionSets) {
15241        final boolean isInAsec;
15242        if (installOnExternalAsec(installFlags)) {
15243            /* Apps on SD card are always in ASEC containers. */
15244            isInAsec = true;
15245        } else if (installForwardLocked(installFlags)
15246                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15247            /*
15248             * Forward-locked apps are only in ASEC containers if they're the
15249             * new style
15250             */
15251            isInAsec = true;
15252        } else {
15253            isInAsec = false;
15254        }
15255
15256        if (isInAsec) {
15257            return new AsecInstallArgs(codePath, instructionSets,
15258                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
15259        } else {
15260            return new FileInstallArgs(codePath, resourcePath, instructionSets);
15261        }
15262    }
15263
15264    static abstract class InstallArgs {
15265        /** @see InstallParams#origin */
15266        final OriginInfo origin;
15267        /** @see InstallParams#move */
15268        final MoveInfo move;
15269
15270        final IPackageInstallObserver2 observer;
15271        // Always refers to PackageManager flags only
15272        final int installFlags;
15273        final String installerPackageName;
15274        final String volumeUuid;
15275        final UserHandle user;
15276        final String abiOverride;
15277        final String[] installGrantPermissions;
15278        /** If non-null, drop an async trace when the install completes */
15279        final String traceMethod;
15280        final int traceCookie;
15281        final Certificate[][] certificates;
15282        final int installReason;
15283
15284        // The list of instruction sets supported by this app. This is currently
15285        // only used during the rmdex() phase to clean up resources. We can get rid of this
15286        // if we move dex files under the common app path.
15287        /* nullable */ String[] instructionSets;
15288
15289        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15290                int installFlags, String installerPackageName, String volumeUuid,
15291                UserHandle user, String[] instructionSets,
15292                String abiOverride, String[] installGrantPermissions,
15293                String traceMethod, int traceCookie, Certificate[][] certificates,
15294                int installReason) {
15295            this.origin = origin;
15296            this.move = move;
15297            this.installFlags = installFlags;
15298            this.observer = observer;
15299            this.installerPackageName = installerPackageName;
15300            this.volumeUuid = volumeUuid;
15301            this.user = user;
15302            this.instructionSets = instructionSets;
15303            this.abiOverride = abiOverride;
15304            this.installGrantPermissions = installGrantPermissions;
15305            this.traceMethod = traceMethod;
15306            this.traceCookie = traceCookie;
15307            this.certificates = certificates;
15308            this.installReason = installReason;
15309        }
15310
15311        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15312        abstract int doPreInstall(int status);
15313
15314        /**
15315         * Rename package into final resting place. All paths on the given
15316         * scanned package should be updated to reflect the rename.
15317         */
15318        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15319        abstract int doPostInstall(int status, int uid);
15320
15321        /** @see PackageSettingBase#codePathString */
15322        abstract String getCodePath();
15323        /** @see PackageSettingBase#resourcePathString */
15324        abstract String getResourcePath();
15325
15326        // Need installer lock especially for dex file removal.
15327        abstract void cleanUpResourcesLI();
15328        abstract boolean doPostDeleteLI(boolean delete);
15329
15330        /**
15331         * Called before the source arguments are copied. This is used mostly
15332         * for MoveParams when it needs to read the source file to put it in the
15333         * destination.
15334         */
15335        int doPreCopy() {
15336            return PackageManager.INSTALL_SUCCEEDED;
15337        }
15338
15339        /**
15340         * Called after the source arguments are copied. This is used mostly for
15341         * MoveParams when it needs to read the source file to put it in the
15342         * destination.
15343         */
15344        int doPostCopy(int uid) {
15345            return PackageManager.INSTALL_SUCCEEDED;
15346        }
15347
15348        protected boolean isFwdLocked() {
15349            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15350        }
15351
15352        protected boolean isExternalAsec() {
15353            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15354        }
15355
15356        protected boolean isEphemeral() {
15357            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15358        }
15359
15360        UserHandle getUser() {
15361            return user;
15362        }
15363    }
15364
15365    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15366        if (!allCodePaths.isEmpty()) {
15367            if (instructionSets == null) {
15368                throw new IllegalStateException("instructionSet == null");
15369            }
15370            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15371            for (String codePath : allCodePaths) {
15372                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15373                    try {
15374                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15375                    } catch (InstallerException ignored) {
15376                    }
15377                }
15378            }
15379        }
15380    }
15381
15382    /**
15383     * Logic to handle installation of non-ASEC applications, including copying
15384     * and renaming logic.
15385     */
15386    class FileInstallArgs extends InstallArgs {
15387        private File codeFile;
15388        private File resourceFile;
15389
15390        // Example topology:
15391        // /data/app/com.example/base.apk
15392        // /data/app/com.example/split_foo.apk
15393        // /data/app/com.example/lib/arm/libfoo.so
15394        // /data/app/com.example/lib/arm64/libfoo.so
15395        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15396
15397        /** New install */
15398        FileInstallArgs(InstallParams params) {
15399            super(params.origin, params.move, params.observer, params.installFlags,
15400                    params.installerPackageName, params.volumeUuid,
15401                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15402                    params.grantedRuntimePermissions,
15403                    params.traceMethod, params.traceCookie, params.certificates,
15404                    params.installReason);
15405            if (isFwdLocked()) {
15406                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15407            }
15408        }
15409
15410        /** Existing install */
15411        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15412            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15413                    null, null, null, 0, null /*certificates*/,
15414                    PackageManager.INSTALL_REASON_UNKNOWN);
15415            this.codeFile = (codePath != null) ? new File(codePath) : null;
15416            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15417        }
15418
15419        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15420            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15421            try {
15422                return doCopyApk(imcs, temp);
15423            } finally {
15424                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15425            }
15426        }
15427
15428        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15429            if (origin.staged) {
15430                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15431                codeFile = origin.file;
15432                resourceFile = origin.file;
15433                return PackageManager.INSTALL_SUCCEEDED;
15434            }
15435
15436            try {
15437                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15438                final File tempDir =
15439                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15440                codeFile = tempDir;
15441                resourceFile = tempDir;
15442            } catch (IOException e) {
15443                Slog.w(TAG, "Failed to create copy file: " + e);
15444                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15445            }
15446
15447            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15448                @Override
15449                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15450                    if (!FileUtils.isValidExtFilename(name)) {
15451                        throw new IllegalArgumentException("Invalid filename: " + name);
15452                    }
15453                    try {
15454                        final File file = new File(codeFile, name);
15455                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15456                                O_RDWR | O_CREAT, 0644);
15457                        Os.chmod(file.getAbsolutePath(), 0644);
15458                        return new ParcelFileDescriptor(fd);
15459                    } catch (ErrnoException e) {
15460                        throw new RemoteException("Failed to open: " + e.getMessage());
15461                    }
15462                }
15463            };
15464
15465            int ret = PackageManager.INSTALL_SUCCEEDED;
15466            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15467            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15468                Slog.e(TAG, "Failed to copy package");
15469                return ret;
15470            }
15471
15472            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15473            NativeLibraryHelper.Handle handle = null;
15474            try {
15475                handle = NativeLibraryHelper.Handle.create(codeFile);
15476                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15477                        abiOverride);
15478            } catch (IOException e) {
15479                Slog.e(TAG, "Copying native libraries failed", e);
15480                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15481            } finally {
15482                IoUtils.closeQuietly(handle);
15483            }
15484
15485            return ret;
15486        }
15487
15488        int doPreInstall(int status) {
15489            if (status != PackageManager.INSTALL_SUCCEEDED) {
15490                cleanUp();
15491            }
15492            return status;
15493        }
15494
15495        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15496            if (status != PackageManager.INSTALL_SUCCEEDED) {
15497                cleanUp();
15498                return false;
15499            }
15500
15501            final File targetDir = codeFile.getParentFile();
15502            final File beforeCodeFile = codeFile;
15503            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15504
15505            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15506            try {
15507                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15508            } catch (ErrnoException e) {
15509                Slog.w(TAG, "Failed to rename", e);
15510                return false;
15511            }
15512
15513            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15514                Slog.w(TAG, "Failed to restorecon");
15515                return false;
15516            }
15517
15518            // Reflect the rename internally
15519            codeFile = afterCodeFile;
15520            resourceFile = afterCodeFile;
15521
15522            // Reflect the rename in scanned details
15523            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15524            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15525                    afterCodeFile, pkg.baseCodePath));
15526            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15527                    afterCodeFile, pkg.splitCodePaths));
15528
15529            // Reflect the rename in app info
15530            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15531            pkg.setApplicationInfoCodePath(pkg.codePath);
15532            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15533            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15534            pkg.setApplicationInfoResourcePath(pkg.codePath);
15535            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15536            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15537
15538            return true;
15539        }
15540
15541        int doPostInstall(int status, int uid) {
15542            if (status != PackageManager.INSTALL_SUCCEEDED) {
15543                cleanUp();
15544            }
15545            return status;
15546        }
15547
15548        @Override
15549        String getCodePath() {
15550            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15551        }
15552
15553        @Override
15554        String getResourcePath() {
15555            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15556        }
15557
15558        private boolean cleanUp() {
15559            if (codeFile == null || !codeFile.exists()) {
15560                return false;
15561            }
15562
15563            removeCodePathLI(codeFile);
15564
15565            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15566                resourceFile.delete();
15567            }
15568
15569            return true;
15570        }
15571
15572        void cleanUpResourcesLI() {
15573            // Try enumerating all code paths before deleting
15574            List<String> allCodePaths = Collections.EMPTY_LIST;
15575            if (codeFile != null && codeFile.exists()) {
15576                try {
15577                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15578                    allCodePaths = pkg.getAllCodePaths();
15579                } catch (PackageParserException e) {
15580                    // Ignored; we tried our best
15581                }
15582            }
15583
15584            cleanUp();
15585            removeDexFiles(allCodePaths, instructionSets);
15586        }
15587
15588        boolean doPostDeleteLI(boolean delete) {
15589            // XXX err, shouldn't we respect the delete flag?
15590            cleanUpResourcesLI();
15591            return true;
15592        }
15593    }
15594
15595    private boolean isAsecExternal(String cid) {
15596        final String asecPath = PackageHelper.getSdFilesystem(cid);
15597        return !asecPath.startsWith(mAsecInternalPath);
15598    }
15599
15600    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15601            PackageManagerException {
15602        if (copyRet < 0) {
15603            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15604                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15605                throw new PackageManagerException(copyRet, message);
15606            }
15607        }
15608    }
15609
15610    /**
15611     * Extract the StorageManagerService "container ID" from the full code path of an
15612     * .apk.
15613     */
15614    static String cidFromCodePath(String fullCodePath) {
15615        int eidx = fullCodePath.lastIndexOf("/");
15616        String subStr1 = fullCodePath.substring(0, eidx);
15617        int sidx = subStr1.lastIndexOf("/");
15618        return subStr1.substring(sidx+1, eidx);
15619    }
15620
15621    /**
15622     * Logic to handle installation of ASEC applications, including copying and
15623     * renaming logic.
15624     */
15625    class AsecInstallArgs extends InstallArgs {
15626        static final String RES_FILE_NAME = "pkg.apk";
15627        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15628
15629        String cid;
15630        String packagePath;
15631        String resourcePath;
15632
15633        /** New install */
15634        AsecInstallArgs(InstallParams params) {
15635            super(params.origin, params.move, params.observer, params.installFlags,
15636                    params.installerPackageName, params.volumeUuid,
15637                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15638                    params.grantedRuntimePermissions,
15639                    params.traceMethod, params.traceCookie, params.certificates,
15640                    params.installReason);
15641        }
15642
15643        /** Existing install */
15644        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15645                        boolean isExternal, boolean isForwardLocked) {
15646            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15647                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15648                    instructionSets, null, null, null, 0, null /*certificates*/,
15649                    PackageManager.INSTALL_REASON_UNKNOWN);
15650            // Hackily pretend we're still looking at a full code path
15651            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15652                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15653            }
15654
15655            // Extract cid from fullCodePath
15656            int eidx = fullCodePath.lastIndexOf("/");
15657            String subStr1 = fullCodePath.substring(0, eidx);
15658            int sidx = subStr1.lastIndexOf("/");
15659            cid = subStr1.substring(sidx+1, eidx);
15660            setMountPath(subStr1);
15661        }
15662
15663        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15664            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15665                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15666                    instructionSets, null, null, null, 0, null /*certificates*/,
15667                    PackageManager.INSTALL_REASON_UNKNOWN);
15668            this.cid = cid;
15669            setMountPath(PackageHelper.getSdDir(cid));
15670        }
15671
15672        void createCopyFile() {
15673            cid = mInstallerService.allocateExternalStageCidLegacy();
15674        }
15675
15676        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15677            if (origin.staged && origin.cid != null) {
15678                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15679                cid = origin.cid;
15680                setMountPath(PackageHelper.getSdDir(cid));
15681                return PackageManager.INSTALL_SUCCEEDED;
15682            }
15683
15684            if (temp) {
15685                createCopyFile();
15686            } else {
15687                /*
15688                 * Pre-emptively destroy the container since it's destroyed if
15689                 * copying fails due to it existing anyway.
15690                 */
15691                PackageHelper.destroySdDir(cid);
15692            }
15693
15694            final String newMountPath = imcs.copyPackageToContainer(
15695                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15696                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15697
15698            if (newMountPath != null) {
15699                setMountPath(newMountPath);
15700                return PackageManager.INSTALL_SUCCEEDED;
15701            } else {
15702                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15703            }
15704        }
15705
15706        @Override
15707        String getCodePath() {
15708            return packagePath;
15709        }
15710
15711        @Override
15712        String getResourcePath() {
15713            return resourcePath;
15714        }
15715
15716        int doPreInstall(int status) {
15717            if (status != PackageManager.INSTALL_SUCCEEDED) {
15718                // Destroy container
15719                PackageHelper.destroySdDir(cid);
15720            } else {
15721                boolean mounted = PackageHelper.isContainerMounted(cid);
15722                if (!mounted) {
15723                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15724                            Process.SYSTEM_UID);
15725                    if (newMountPath != null) {
15726                        setMountPath(newMountPath);
15727                    } else {
15728                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15729                    }
15730                }
15731            }
15732            return status;
15733        }
15734
15735        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15736            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15737            String newMountPath = null;
15738            if (PackageHelper.isContainerMounted(cid)) {
15739                // Unmount the container
15740                if (!PackageHelper.unMountSdDir(cid)) {
15741                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15742                    return false;
15743                }
15744            }
15745            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15746                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15747                        " which might be stale. Will try to clean up.");
15748                // Clean up the stale container and proceed to recreate.
15749                if (!PackageHelper.destroySdDir(newCacheId)) {
15750                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15751                    return false;
15752                }
15753                // Successfully cleaned up stale container. Try to rename again.
15754                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15755                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15756                            + " inspite of cleaning it up.");
15757                    return false;
15758                }
15759            }
15760            if (!PackageHelper.isContainerMounted(newCacheId)) {
15761                Slog.w(TAG, "Mounting container " + newCacheId);
15762                newMountPath = PackageHelper.mountSdDir(newCacheId,
15763                        getEncryptKey(), Process.SYSTEM_UID);
15764            } else {
15765                newMountPath = PackageHelper.getSdDir(newCacheId);
15766            }
15767            if (newMountPath == null) {
15768                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15769                return false;
15770            }
15771            Log.i(TAG, "Succesfully renamed " + cid +
15772                    " to " + newCacheId +
15773                    " at new path: " + newMountPath);
15774            cid = newCacheId;
15775
15776            final File beforeCodeFile = new File(packagePath);
15777            setMountPath(newMountPath);
15778            final File afterCodeFile = new File(packagePath);
15779
15780            // Reflect the rename in scanned details
15781            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15782            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15783                    afterCodeFile, pkg.baseCodePath));
15784            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15785                    afterCodeFile, pkg.splitCodePaths));
15786
15787            // Reflect the rename in app info
15788            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15789            pkg.setApplicationInfoCodePath(pkg.codePath);
15790            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15791            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15792            pkg.setApplicationInfoResourcePath(pkg.codePath);
15793            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15794            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15795
15796            return true;
15797        }
15798
15799        private void setMountPath(String mountPath) {
15800            final File mountFile = new File(mountPath);
15801
15802            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15803            if (monolithicFile.exists()) {
15804                packagePath = monolithicFile.getAbsolutePath();
15805                if (isFwdLocked()) {
15806                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15807                } else {
15808                    resourcePath = packagePath;
15809                }
15810            } else {
15811                packagePath = mountFile.getAbsolutePath();
15812                resourcePath = packagePath;
15813            }
15814        }
15815
15816        int doPostInstall(int status, int uid) {
15817            if (status != PackageManager.INSTALL_SUCCEEDED) {
15818                cleanUp();
15819            } else {
15820                final int groupOwner;
15821                final String protectedFile;
15822                if (isFwdLocked()) {
15823                    groupOwner = UserHandle.getSharedAppGid(uid);
15824                    protectedFile = RES_FILE_NAME;
15825                } else {
15826                    groupOwner = -1;
15827                    protectedFile = null;
15828                }
15829
15830                if (uid < Process.FIRST_APPLICATION_UID
15831                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15832                    Slog.e(TAG, "Failed to finalize " + cid);
15833                    PackageHelper.destroySdDir(cid);
15834                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15835                }
15836
15837                boolean mounted = PackageHelper.isContainerMounted(cid);
15838                if (!mounted) {
15839                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15840                }
15841            }
15842            return status;
15843        }
15844
15845        private void cleanUp() {
15846            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15847
15848            // Destroy secure container
15849            PackageHelper.destroySdDir(cid);
15850        }
15851
15852        private List<String> getAllCodePaths() {
15853            final File codeFile = new File(getCodePath());
15854            if (codeFile != null && codeFile.exists()) {
15855                try {
15856                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15857                    return pkg.getAllCodePaths();
15858                } catch (PackageParserException e) {
15859                    // Ignored; we tried our best
15860                }
15861            }
15862            return Collections.EMPTY_LIST;
15863        }
15864
15865        void cleanUpResourcesLI() {
15866            // Enumerate all code paths before deleting
15867            cleanUpResourcesLI(getAllCodePaths());
15868        }
15869
15870        private void cleanUpResourcesLI(List<String> allCodePaths) {
15871            cleanUp();
15872            removeDexFiles(allCodePaths, instructionSets);
15873        }
15874
15875        String getPackageName() {
15876            return getAsecPackageName(cid);
15877        }
15878
15879        boolean doPostDeleteLI(boolean delete) {
15880            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15881            final List<String> allCodePaths = getAllCodePaths();
15882            boolean mounted = PackageHelper.isContainerMounted(cid);
15883            if (mounted) {
15884                // Unmount first
15885                if (PackageHelper.unMountSdDir(cid)) {
15886                    mounted = false;
15887                }
15888            }
15889            if (!mounted && delete) {
15890                cleanUpResourcesLI(allCodePaths);
15891            }
15892            return !mounted;
15893        }
15894
15895        @Override
15896        int doPreCopy() {
15897            if (isFwdLocked()) {
15898                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15899                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15900                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15901                }
15902            }
15903
15904            return PackageManager.INSTALL_SUCCEEDED;
15905        }
15906
15907        @Override
15908        int doPostCopy(int uid) {
15909            if (isFwdLocked()) {
15910                if (uid < Process.FIRST_APPLICATION_UID
15911                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15912                                RES_FILE_NAME)) {
15913                    Slog.e(TAG, "Failed to finalize " + cid);
15914                    PackageHelper.destroySdDir(cid);
15915                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15916                }
15917            }
15918
15919            return PackageManager.INSTALL_SUCCEEDED;
15920        }
15921    }
15922
15923    /**
15924     * Logic to handle movement of existing installed applications.
15925     */
15926    class MoveInstallArgs extends InstallArgs {
15927        private File codeFile;
15928        private File resourceFile;
15929
15930        /** New install */
15931        MoveInstallArgs(InstallParams params) {
15932            super(params.origin, params.move, params.observer, params.installFlags,
15933                    params.installerPackageName, params.volumeUuid,
15934                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15935                    params.grantedRuntimePermissions,
15936                    params.traceMethod, params.traceCookie, params.certificates,
15937                    params.installReason);
15938        }
15939
15940        int copyApk(IMediaContainerService imcs, boolean temp) {
15941            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15942                    + move.fromUuid + " to " + move.toUuid);
15943            synchronized (mInstaller) {
15944                try {
15945                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15946                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15947                } catch (InstallerException e) {
15948                    Slog.w(TAG, "Failed to move app", e);
15949                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15950                }
15951            }
15952
15953            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15954            resourceFile = codeFile;
15955            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15956
15957            return PackageManager.INSTALL_SUCCEEDED;
15958        }
15959
15960        int doPreInstall(int status) {
15961            if (status != PackageManager.INSTALL_SUCCEEDED) {
15962                cleanUp(move.toUuid);
15963            }
15964            return status;
15965        }
15966
15967        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15968            if (status != PackageManager.INSTALL_SUCCEEDED) {
15969                cleanUp(move.toUuid);
15970                return false;
15971            }
15972
15973            // Reflect the move in app info
15974            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15975            pkg.setApplicationInfoCodePath(pkg.codePath);
15976            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15977            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15978            pkg.setApplicationInfoResourcePath(pkg.codePath);
15979            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15980            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15981
15982            return true;
15983        }
15984
15985        int doPostInstall(int status, int uid) {
15986            if (status == PackageManager.INSTALL_SUCCEEDED) {
15987                cleanUp(move.fromUuid);
15988            } else {
15989                cleanUp(move.toUuid);
15990            }
15991            return status;
15992        }
15993
15994        @Override
15995        String getCodePath() {
15996            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15997        }
15998
15999        @Override
16000        String getResourcePath() {
16001            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16002        }
16003
16004        private boolean cleanUp(String volumeUuid) {
16005            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16006                    move.dataAppName);
16007            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16008            final int[] userIds = sUserManager.getUserIds();
16009            synchronized (mInstallLock) {
16010                // Clean up both app data and code
16011                // All package moves are frozen until finished
16012                for (int userId : userIds) {
16013                    try {
16014                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16015                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16016                    } catch (InstallerException e) {
16017                        Slog.w(TAG, String.valueOf(e));
16018                    }
16019                }
16020                removeCodePathLI(codeFile);
16021            }
16022            return true;
16023        }
16024
16025        void cleanUpResourcesLI() {
16026            throw new UnsupportedOperationException();
16027        }
16028
16029        boolean doPostDeleteLI(boolean delete) {
16030            throw new UnsupportedOperationException();
16031        }
16032    }
16033
16034    static String getAsecPackageName(String packageCid) {
16035        int idx = packageCid.lastIndexOf("-");
16036        if (idx == -1) {
16037            return packageCid;
16038        }
16039        return packageCid.substring(0, idx);
16040    }
16041
16042    // Utility method used to create code paths based on package name and available index.
16043    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16044        String idxStr = "";
16045        int idx = 1;
16046        // Fall back to default value of idx=1 if prefix is not
16047        // part of oldCodePath
16048        if (oldCodePath != null) {
16049            String subStr = oldCodePath;
16050            // Drop the suffix right away
16051            if (suffix != null && subStr.endsWith(suffix)) {
16052                subStr = subStr.substring(0, subStr.length() - suffix.length());
16053            }
16054            // If oldCodePath already contains prefix find out the
16055            // ending index to either increment or decrement.
16056            int sidx = subStr.lastIndexOf(prefix);
16057            if (sidx != -1) {
16058                subStr = subStr.substring(sidx + prefix.length());
16059                if (subStr != null) {
16060                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16061                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16062                    }
16063                    try {
16064                        idx = Integer.parseInt(subStr);
16065                        if (idx <= 1) {
16066                            idx++;
16067                        } else {
16068                            idx--;
16069                        }
16070                    } catch(NumberFormatException e) {
16071                    }
16072                }
16073            }
16074        }
16075        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16076        return prefix + idxStr;
16077    }
16078
16079    private File getNextCodePath(File targetDir, String packageName) {
16080        File result;
16081        SecureRandom random = new SecureRandom();
16082        byte[] bytes = new byte[16];
16083        do {
16084            random.nextBytes(bytes);
16085            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16086            result = new File(targetDir, packageName + "-" + suffix);
16087        } while (result.exists());
16088        return result;
16089    }
16090
16091    // Utility method that returns the relative package path with respect
16092    // to the installation directory. Like say for /data/data/com.test-1.apk
16093    // string com.test-1 is returned.
16094    static String deriveCodePathName(String codePath) {
16095        if (codePath == null) {
16096            return null;
16097        }
16098        final File codeFile = new File(codePath);
16099        final String name = codeFile.getName();
16100        if (codeFile.isDirectory()) {
16101            return name;
16102        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16103            final int lastDot = name.lastIndexOf('.');
16104            return name.substring(0, lastDot);
16105        } else {
16106            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16107            return null;
16108        }
16109    }
16110
16111    static class PackageInstalledInfo {
16112        String name;
16113        int uid;
16114        // The set of users that originally had this package installed.
16115        int[] origUsers;
16116        // The set of users that now have this package installed.
16117        int[] newUsers;
16118        PackageParser.Package pkg;
16119        int returnCode;
16120        String returnMsg;
16121        PackageRemovedInfo removedInfo;
16122        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16123
16124        public void setError(int code, String msg) {
16125            setReturnCode(code);
16126            setReturnMessage(msg);
16127            Slog.w(TAG, msg);
16128        }
16129
16130        public void setError(String msg, PackageParserException e) {
16131            setReturnCode(e.error);
16132            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16133            Slog.w(TAG, msg, e);
16134        }
16135
16136        public void setError(String msg, PackageManagerException e) {
16137            returnCode = e.error;
16138            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16139            Slog.w(TAG, msg, e);
16140        }
16141
16142        public void setReturnCode(int returnCode) {
16143            this.returnCode = returnCode;
16144            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16145            for (int i = 0; i < childCount; i++) {
16146                addedChildPackages.valueAt(i).returnCode = returnCode;
16147            }
16148        }
16149
16150        private void setReturnMessage(String returnMsg) {
16151            this.returnMsg = returnMsg;
16152            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16153            for (int i = 0; i < childCount; i++) {
16154                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16155            }
16156        }
16157
16158        // In some error cases we want to convey more info back to the observer
16159        String origPackage;
16160        String origPermission;
16161    }
16162
16163    /*
16164     * Install a non-existing package.
16165     */
16166    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16167            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16168            PackageInstalledInfo res, int installReason) {
16169        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16170
16171        // Remember this for later, in case we need to rollback this install
16172        String pkgName = pkg.packageName;
16173
16174        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16175
16176        synchronized(mPackages) {
16177            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16178            if (renamedPackage != null) {
16179                // A package with the same name is already installed, though
16180                // it has been renamed to an older name.  The package we
16181                // are trying to install should be installed as an update to
16182                // the existing one, but that has not been requested, so bail.
16183                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16184                        + " without first uninstalling package running as "
16185                        + renamedPackage);
16186                return;
16187            }
16188            if (mPackages.containsKey(pkgName)) {
16189                // Don't allow installation over an existing package with the same name.
16190                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16191                        + " without first uninstalling.");
16192                return;
16193            }
16194        }
16195
16196        try {
16197            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16198                    System.currentTimeMillis(), user);
16199
16200            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16201
16202            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16203                prepareAppDataAfterInstallLIF(newPackage);
16204
16205            } else {
16206                // Remove package from internal structures, but keep around any
16207                // data that might have already existed
16208                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16209                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16210            }
16211        } catch (PackageManagerException e) {
16212            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16213        }
16214
16215        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16216    }
16217
16218    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16219        // Can't rotate keys during boot or if sharedUser.
16220        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16221                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16222            return false;
16223        }
16224        // app is using upgradeKeySets; make sure all are valid
16225        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16226        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16227        for (int i = 0; i < upgradeKeySets.length; i++) {
16228            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16229                Slog.wtf(TAG, "Package "
16230                         + (oldPs.name != null ? oldPs.name : "<null>")
16231                         + " contains upgrade-key-set reference to unknown key-set: "
16232                         + upgradeKeySets[i]
16233                         + " reverting to signatures check.");
16234                return false;
16235            }
16236        }
16237        return true;
16238    }
16239
16240    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16241        // Upgrade keysets are being used.  Determine if new package has a superset of the
16242        // required keys.
16243        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16244        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16245        for (int i = 0; i < upgradeKeySets.length; i++) {
16246            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16247            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16248                return true;
16249            }
16250        }
16251        return false;
16252    }
16253
16254    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16255        try (DigestInputStream digestStream =
16256                new DigestInputStream(new FileInputStream(file), digest)) {
16257            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16258        }
16259    }
16260
16261    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16262            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16263            int installReason) {
16264        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16265
16266        final PackageParser.Package oldPackage;
16267        final PackageSetting ps;
16268        final String pkgName = pkg.packageName;
16269        final int[] allUsers;
16270        final int[] installedUsers;
16271
16272        synchronized(mPackages) {
16273            oldPackage = mPackages.get(pkgName);
16274            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16275
16276            // don't allow upgrade to target a release SDK from a pre-release SDK
16277            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16278                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16279            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16280                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16281            if (oldTargetsPreRelease
16282                    && !newTargetsPreRelease
16283                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16284                Slog.w(TAG, "Can't install package targeting released sdk");
16285                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16286                return;
16287            }
16288
16289            ps = mSettings.mPackages.get(pkgName);
16290
16291            // verify signatures are valid
16292            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16293                if (!checkUpgradeKeySetLP(ps, pkg)) {
16294                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16295                            "New package not signed by keys specified by upgrade-keysets: "
16296                                    + pkgName);
16297                    return;
16298                }
16299            } else {
16300                // default to original signature matching
16301                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16302                        != PackageManager.SIGNATURE_MATCH) {
16303                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16304                            "New package has a different signature: " + pkgName);
16305                    return;
16306                }
16307            }
16308
16309            // don't allow a system upgrade unless the upgrade hash matches
16310            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16311                byte[] digestBytes = null;
16312                try {
16313                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16314                    updateDigest(digest, new File(pkg.baseCodePath));
16315                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16316                        for (String path : pkg.splitCodePaths) {
16317                            updateDigest(digest, new File(path));
16318                        }
16319                    }
16320                    digestBytes = digest.digest();
16321                } catch (NoSuchAlgorithmException | IOException e) {
16322                    res.setError(INSTALL_FAILED_INVALID_APK,
16323                            "Could not compute hash: " + pkgName);
16324                    return;
16325                }
16326                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16327                    res.setError(INSTALL_FAILED_INVALID_APK,
16328                            "New package fails restrict-update check: " + pkgName);
16329                    return;
16330                }
16331                // retain upgrade restriction
16332                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16333            }
16334
16335            // Check for shared user id changes
16336            String invalidPackageName =
16337                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16338            if (invalidPackageName != null) {
16339                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16340                        "Package " + invalidPackageName + " tried to change user "
16341                                + oldPackage.mSharedUserId);
16342                return;
16343            }
16344
16345            // In case of rollback, remember per-user/profile install state
16346            allUsers = sUserManager.getUserIds();
16347            installedUsers = ps.queryInstalledUsers(allUsers, true);
16348
16349            // don't allow an upgrade from full to ephemeral
16350            if (isInstantApp) {
16351                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16352                    for (int currentUser : allUsers) {
16353                        if (!ps.getInstantApp(currentUser)) {
16354                            // can't downgrade from full to instant
16355                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16356                                    + " for user: " + currentUser);
16357                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16358                            return;
16359                        }
16360                    }
16361                } else if (!ps.getInstantApp(user.getIdentifier())) {
16362                    // can't downgrade from full to instant
16363                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16364                            + " for user: " + user.getIdentifier());
16365                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16366                    return;
16367                }
16368            }
16369        }
16370
16371        // Update what is removed
16372        res.removedInfo = new PackageRemovedInfo(this);
16373        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16374        res.removedInfo.removedPackage = oldPackage.packageName;
16375        res.removedInfo.installerPackageName = ps.installerPackageName;
16376        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16377        res.removedInfo.isUpdate = true;
16378        res.removedInfo.origUsers = installedUsers;
16379        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16380        for (int i = 0; i < installedUsers.length; i++) {
16381            final int userId = installedUsers[i];
16382            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16383        }
16384
16385        final int childCount = (oldPackage.childPackages != null)
16386                ? oldPackage.childPackages.size() : 0;
16387        for (int i = 0; i < childCount; i++) {
16388            boolean childPackageUpdated = false;
16389            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16390            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16391            if (res.addedChildPackages != null) {
16392                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16393                if (childRes != null) {
16394                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16395                    childRes.removedInfo.removedPackage = childPkg.packageName;
16396                    if (childPs != null) {
16397                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16398                    }
16399                    childRes.removedInfo.isUpdate = true;
16400                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16401                    childPackageUpdated = true;
16402                }
16403            }
16404            if (!childPackageUpdated) {
16405                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16406                childRemovedRes.removedPackage = childPkg.packageName;
16407                if (childPs != null) {
16408                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16409                }
16410                childRemovedRes.isUpdate = false;
16411                childRemovedRes.dataRemoved = true;
16412                synchronized (mPackages) {
16413                    if (childPs != null) {
16414                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16415                    }
16416                }
16417                if (res.removedInfo.removedChildPackages == null) {
16418                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16419                }
16420                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16421            }
16422        }
16423
16424        boolean sysPkg = (isSystemApp(oldPackage));
16425        if (sysPkg) {
16426            // Set the system/privileged flags as needed
16427            final boolean privileged =
16428                    (oldPackage.applicationInfo.privateFlags
16429                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16430            final int systemPolicyFlags = policyFlags
16431                    | PackageParser.PARSE_IS_SYSTEM
16432                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16433
16434            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16435                    user, allUsers, installerPackageName, res, installReason);
16436        } else {
16437            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16438                    user, allUsers, installerPackageName, res, installReason);
16439        }
16440    }
16441
16442    public List<String> getPreviousCodePaths(String packageName) {
16443        final PackageSetting ps = mSettings.mPackages.get(packageName);
16444        final List<String> result = new ArrayList<String>();
16445        if (ps != null && ps.oldCodePaths != null) {
16446            result.addAll(ps.oldCodePaths);
16447        }
16448        return result;
16449    }
16450
16451    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16452            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16453            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16454            int installReason) {
16455        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16456                + deletedPackage);
16457
16458        String pkgName = deletedPackage.packageName;
16459        boolean deletedPkg = true;
16460        boolean addedPkg = false;
16461        boolean updatedSettings = false;
16462        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16463        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16464                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16465
16466        final long origUpdateTime = (pkg.mExtras != null)
16467                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16468
16469        // First delete the existing package while retaining the data directory
16470        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16471                res.removedInfo, true, pkg)) {
16472            // If the existing package wasn't successfully deleted
16473            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16474            deletedPkg = false;
16475        } else {
16476            // Successfully deleted the old package; proceed with replace.
16477
16478            // If deleted package lived in a container, give users a chance to
16479            // relinquish resources before killing.
16480            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16481                if (DEBUG_INSTALL) {
16482                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16483                }
16484                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16485                final ArrayList<String> pkgList = new ArrayList<String>(1);
16486                pkgList.add(deletedPackage.applicationInfo.packageName);
16487                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16488            }
16489
16490            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16491                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16492            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16493
16494            try {
16495                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16496                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16497                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16498                        installReason);
16499
16500                // Update the in-memory copy of the previous code paths.
16501                PackageSetting ps = mSettings.mPackages.get(pkgName);
16502                if (!killApp) {
16503                    if (ps.oldCodePaths == null) {
16504                        ps.oldCodePaths = new ArraySet<>();
16505                    }
16506                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16507                    if (deletedPackage.splitCodePaths != null) {
16508                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16509                    }
16510                } else {
16511                    ps.oldCodePaths = null;
16512                }
16513                if (ps.childPackageNames != null) {
16514                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16515                        final String childPkgName = ps.childPackageNames.get(i);
16516                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16517                        childPs.oldCodePaths = ps.oldCodePaths;
16518                    }
16519                }
16520                // set instant app status, but, only if it's explicitly specified
16521                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16522                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16523                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16524                prepareAppDataAfterInstallLIF(newPackage);
16525                addedPkg = true;
16526                mDexManager.notifyPackageUpdated(newPackage.packageName,
16527                        newPackage.baseCodePath, newPackage.splitCodePaths);
16528            } catch (PackageManagerException e) {
16529                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16530            }
16531        }
16532
16533        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16534            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16535
16536            // Revert all internal state mutations and added folders for the failed install
16537            if (addedPkg) {
16538                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16539                        res.removedInfo, true, null);
16540            }
16541
16542            // Restore the old package
16543            if (deletedPkg) {
16544                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16545                File restoreFile = new File(deletedPackage.codePath);
16546                // Parse old package
16547                boolean oldExternal = isExternal(deletedPackage);
16548                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16549                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16550                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16551                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16552                try {
16553                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16554                            null);
16555                } catch (PackageManagerException e) {
16556                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16557                            + e.getMessage());
16558                    return;
16559                }
16560
16561                synchronized (mPackages) {
16562                    // Ensure the installer package name up to date
16563                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16564
16565                    // Update permissions for restored package
16566                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16567
16568                    mSettings.writeLPr();
16569                }
16570
16571                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16572            }
16573        } else {
16574            synchronized (mPackages) {
16575                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16576                if (ps != null) {
16577                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16578                    if (res.removedInfo.removedChildPackages != null) {
16579                        final int childCount = res.removedInfo.removedChildPackages.size();
16580                        // Iterate in reverse as we may modify the collection
16581                        for (int i = childCount - 1; i >= 0; i--) {
16582                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16583                            if (res.addedChildPackages.containsKey(childPackageName)) {
16584                                res.removedInfo.removedChildPackages.removeAt(i);
16585                            } else {
16586                                PackageRemovedInfo childInfo = res.removedInfo
16587                                        .removedChildPackages.valueAt(i);
16588                                childInfo.removedForAllUsers = mPackages.get(
16589                                        childInfo.removedPackage) == null;
16590                            }
16591                        }
16592                    }
16593                }
16594            }
16595        }
16596    }
16597
16598    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16599            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16600            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16601            int installReason) {
16602        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16603                + ", old=" + deletedPackage);
16604
16605        final boolean disabledSystem;
16606
16607        // Remove existing system package
16608        removePackageLI(deletedPackage, true);
16609
16610        synchronized (mPackages) {
16611            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16612        }
16613        if (!disabledSystem) {
16614            // We didn't need to disable the .apk as a current system package,
16615            // which means we are replacing another update that is already
16616            // installed.  We need to make sure to delete the older one's .apk.
16617            res.removedInfo.args = createInstallArgsForExisting(0,
16618                    deletedPackage.applicationInfo.getCodePath(),
16619                    deletedPackage.applicationInfo.getResourcePath(),
16620                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16621        } else {
16622            res.removedInfo.args = null;
16623        }
16624
16625        // Successfully disabled the old package. Now proceed with re-installation
16626        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16627                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16628        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16629
16630        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16631        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16632                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16633
16634        PackageParser.Package newPackage = null;
16635        try {
16636            // Add the package to the internal data structures
16637            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16638
16639            // Set the update and install times
16640            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16641            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16642                    System.currentTimeMillis());
16643
16644            // Update the package dynamic state if succeeded
16645            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16646                // Now that the install succeeded make sure we remove data
16647                // directories for any child package the update removed.
16648                final int deletedChildCount = (deletedPackage.childPackages != null)
16649                        ? deletedPackage.childPackages.size() : 0;
16650                final int newChildCount = (newPackage.childPackages != null)
16651                        ? newPackage.childPackages.size() : 0;
16652                for (int i = 0; i < deletedChildCount; i++) {
16653                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16654                    boolean childPackageDeleted = true;
16655                    for (int j = 0; j < newChildCount; j++) {
16656                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16657                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16658                            childPackageDeleted = false;
16659                            break;
16660                        }
16661                    }
16662                    if (childPackageDeleted) {
16663                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16664                                deletedChildPkg.packageName);
16665                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16666                            PackageRemovedInfo removedChildRes = res.removedInfo
16667                                    .removedChildPackages.get(deletedChildPkg.packageName);
16668                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16669                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16670                        }
16671                    }
16672                }
16673
16674                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16675                        installReason);
16676                prepareAppDataAfterInstallLIF(newPackage);
16677
16678                mDexManager.notifyPackageUpdated(newPackage.packageName,
16679                            newPackage.baseCodePath, newPackage.splitCodePaths);
16680            }
16681        } catch (PackageManagerException e) {
16682            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16683            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16684        }
16685
16686        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16687            // Re installation failed. Restore old information
16688            // Remove new pkg information
16689            if (newPackage != null) {
16690                removeInstalledPackageLI(newPackage, true);
16691            }
16692            // Add back the old system package
16693            try {
16694                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16695            } catch (PackageManagerException e) {
16696                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16697            }
16698
16699            synchronized (mPackages) {
16700                if (disabledSystem) {
16701                    enableSystemPackageLPw(deletedPackage);
16702                }
16703
16704                // Ensure the installer package name up to date
16705                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16706
16707                // Update permissions for restored package
16708                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16709
16710                mSettings.writeLPr();
16711            }
16712
16713            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16714                    + " after failed upgrade");
16715        }
16716    }
16717
16718    /**
16719     * Checks whether the parent or any of the child packages have a change shared
16720     * user. For a package to be a valid update the shred users of the parent and
16721     * the children should match. We may later support changing child shared users.
16722     * @param oldPkg The updated package.
16723     * @param newPkg The update package.
16724     * @return The shared user that change between the versions.
16725     */
16726    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16727            PackageParser.Package newPkg) {
16728        // Check parent shared user
16729        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16730            return newPkg.packageName;
16731        }
16732        // Check child shared users
16733        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16734        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16735        for (int i = 0; i < newChildCount; i++) {
16736            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16737            // If this child was present, did it have the same shared user?
16738            for (int j = 0; j < oldChildCount; j++) {
16739                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16740                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16741                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16742                    return newChildPkg.packageName;
16743                }
16744            }
16745        }
16746        return null;
16747    }
16748
16749    private void removeNativeBinariesLI(PackageSetting ps) {
16750        // Remove the lib path for the parent package
16751        if (ps != null) {
16752            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16753            // Remove the lib path for the child packages
16754            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16755            for (int i = 0; i < childCount; i++) {
16756                PackageSetting childPs = null;
16757                synchronized (mPackages) {
16758                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16759                }
16760                if (childPs != null) {
16761                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16762                            .legacyNativeLibraryPathString);
16763                }
16764            }
16765        }
16766    }
16767
16768    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16769        // Enable the parent package
16770        mSettings.enableSystemPackageLPw(pkg.packageName);
16771        // Enable the child packages
16772        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16773        for (int i = 0; i < childCount; i++) {
16774            PackageParser.Package childPkg = pkg.childPackages.get(i);
16775            mSettings.enableSystemPackageLPw(childPkg.packageName);
16776        }
16777    }
16778
16779    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16780            PackageParser.Package newPkg) {
16781        // Disable the parent package (parent always replaced)
16782        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16783        // Disable the child packages
16784        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16785        for (int i = 0; i < childCount; i++) {
16786            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16787            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16788            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16789        }
16790        return disabled;
16791    }
16792
16793    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16794            String installerPackageName) {
16795        // Enable the parent package
16796        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16797        // Enable the child packages
16798        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16799        for (int i = 0; i < childCount; i++) {
16800            PackageParser.Package childPkg = pkg.childPackages.get(i);
16801            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16802        }
16803    }
16804
16805    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16806        // Collect all used permissions in the UID
16807        ArraySet<String> usedPermissions = new ArraySet<>();
16808        final int packageCount = su.packages.size();
16809        for (int i = 0; i < packageCount; i++) {
16810            PackageSetting ps = su.packages.valueAt(i);
16811            if (ps.pkg == null) {
16812                continue;
16813            }
16814            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16815            for (int j = 0; j < requestedPermCount; j++) {
16816                String permission = ps.pkg.requestedPermissions.get(j);
16817                BasePermission bp = mSettings.mPermissions.get(permission);
16818                if (bp != null) {
16819                    usedPermissions.add(permission);
16820                }
16821            }
16822        }
16823
16824        PermissionsState permissionsState = su.getPermissionsState();
16825        // Prune install permissions
16826        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16827        final int installPermCount = installPermStates.size();
16828        for (int i = installPermCount - 1; i >= 0;  i--) {
16829            PermissionState permissionState = installPermStates.get(i);
16830            if (!usedPermissions.contains(permissionState.getName())) {
16831                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16832                if (bp != null) {
16833                    permissionsState.revokeInstallPermission(bp);
16834                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16835                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16836                }
16837            }
16838        }
16839
16840        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16841
16842        // Prune runtime permissions
16843        for (int userId : allUserIds) {
16844            List<PermissionState> runtimePermStates = permissionsState
16845                    .getRuntimePermissionStates(userId);
16846            final int runtimePermCount = runtimePermStates.size();
16847            for (int i = runtimePermCount - 1; i >= 0; i--) {
16848                PermissionState permissionState = runtimePermStates.get(i);
16849                if (!usedPermissions.contains(permissionState.getName())) {
16850                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16851                    if (bp != null) {
16852                        permissionsState.revokeRuntimePermission(bp, userId);
16853                        permissionsState.updatePermissionFlags(bp, userId,
16854                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16855                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16856                                runtimePermissionChangedUserIds, userId);
16857                    }
16858                }
16859            }
16860        }
16861
16862        return runtimePermissionChangedUserIds;
16863    }
16864
16865    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16866            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16867        // Update the parent package setting
16868        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16869                res, user, installReason);
16870        // Update the child packages setting
16871        final int childCount = (newPackage.childPackages != null)
16872                ? newPackage.childPackages.size() : 0;
16873        for (int i = 0; i < childCount; i++) {
16874            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16875            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16876            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16877                    childRes.origUsers, childRes, user, installReason);
16878        }
16879    }
16880
16881    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16882            String installerPackageName, int[] allUsers, int[] installedForUsers,
16883            PackageInstalledInfo res, UserHandle user, int installReason) {
16884        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16885
16886        String pkgName = newPackage.packageName;
16887        synchronized (mPackages) {
16888            //write settings. the installStatus will be incomplete at this stage.
16889            //note that the new package setting would have already been
16890            //added to mPackages. It hasn't been persisted yet.
16891            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16892            // TODO: Remove this write? It's also written at the end of this method
16893            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16894            mSettings.writeLPr();
16895            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16896        }
16897
16898        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16899        synchronized (mPackages) {
16900            updatePermissionsLPw(newPackage.packageName, newPackage,
16901                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16902                            ? UPDATE_PERMISSIONS_ALL : 0));
16903            // For system-bundled packages, we assume that installing an upgraded version
16904            // of the package implies that the user actually wants to run that new code,
16905            // so we enable the package.
16906            PackageSetting ps = mSettings.mPackages.get(pkgName);
16907            final int userId = user.getIdentifier();
16908            if (ps != null) {
16909                if (isSystemApp(newPackage)) {
16910                    if (DEBUG_INSTALL) {
16911                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16912                    }
16913                    // Enable system package for requested users
16914                    if (res.origUsers != null) {
16915                        for (int origUserId : res.origUsers) {
16916                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16917                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16918                                        origUserId, installerPackageName);
16919                            }
16920                        }
16921                    }
16922                    // Also convey the prior install/uninstall state
16923                    if (allUsers != null && installedForUsers != null) {
16924                        for (int currentUserId : allUsers) {
16925                            final boolean installed = ArrayUtils.contains(
16926                                    installedForUsers, currentUserId);
16927                            if (DEBUG_INSTALL) {
16928                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16929                            }
16930                            ps.setInstalled(installed, currentUserId);
16931                        }
16932                        // these install state changes will be persisted in the
16933                        // upcoming call to mSettings.writeLPr().
16934                    }
16935                }
16936                // It's implied that when a user requests installation, they want the app to be
16937                // installed and enabled.
16938                if (userId != UserHandle.USER_ALL) {
16939                    ps.setInstalled(true, userId);
16940                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16941                }
16942
16943                // When replacing an existing package, preserve the original install reason for all
16944                // users that had the package installed before.
16945                final Set<Integer> previousUserIds = new ArraySet<>();
16946                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16947                    final int installReasonCount = res.removedInfo.installReasons.size();
16948                    for (int i = 0; i < installReasonCount; i++) {
16949                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16950                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16951                        ps.setInstallReason(previousInstallReason, previousUserId);
16952                        previousUserIds.add(previousUserId);
16953                    }
16954                }
16955
16956                // Set install reason for users that are having the package newly installed.
16957                if (userId == UserHandle.USER_ALL) {
16958                    for (int currentUserId : sUserManager.getUserIds()) {
16959                        if (!previousUserIds.contains(currentUserId)) {
16960                            ps.setInstallReason(installReason, currentUserId);
16961                        }
16962                    }
16963                } else if (!previousUserIds.contains(userId)) {
16964                    ps.setInstallReason(installReason, userId);
16965                }
16966                mSettings.writeKernelMappingLPr(ps);
16967            }
16968            res.name = pkgName;
16969            res.uid = newPackage.applicationInfo.uid;
16970            res.pkg = newPackage;
16971            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16972            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16973            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16974            //to update install status
16975            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16976            mSettings.writeLPr();
16977            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16978        }
16979
16980        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16981    }
16982
16983    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16984        try {
16985            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16986            installPackageLI(args, res);
16987        } finally {
16988            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16989        }
16990    }
16991
16992    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16993        final int installFlags = args.installFlags;
16994        final String installerPackageName = args.installerPackageName;
16995        final String volumeUuid = args.volumeUuid;
16996        final File tmpPackageFile = new File(args.getCodePath());
16997        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16998        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16999                || (args.volumeUuid != null));
17000        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17001        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17002        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17003        boolean replace = false;
17004        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17005        if (args.move != null) {
17006            // moving a complete application; perform an initial scan on the new install location
17007            scanFlags |= SCAN_INITIAL;
17008        }
17009        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17010            scanFlags |= SCAN_DONT_KILL_APP;
17011        }
17012        if (instantApp) {
17013            scanFlags |= SCAN_AS_INSTANT_APP;
17014        }
17015        if (fullApp) {
17016            scanFlags |= SCAN_AS_FULL_APP;
17017        }
17018
17019        // Result object to be returned
17020        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17021
17022        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17023
17024        // Sanity check
17025        if (instantApp && (forwardLocked || onExternal)) {
17026            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17027                    + " external=" + onExternal);
17028            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17029            return;
17030        }
17031
17032        // Retrieve PackageSettings and parse package
17033        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17034                | PackageParser.PARSE_ENFORCE_CODE
17035                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17036                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17037                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17038                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17039        PackageParser pp = new PackageParser();
17040        pp.setSeparateProcesses(mSeparateProcesses);
17041        pp.setDisplayMetrics(mMetrics);
17042        pp.setCallback(mPackageParserCallback);
17043
17044        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17045        final PackageParser.Package pkg;
17046        try {
17047            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17048        } catch (PackageParserException e) {
17049            res.setError("Failed parse during installPackageLI", e);
17050            return;
17051        } finally {
17052            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17053        }
17054
17055        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17056        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17057            Slog.w(TAG, "Instant app package " + pkg.packageName
17058                    + " does not target O, this will be a fatal error.");
17059            // STOPSHIP: Make this a fatal error
17060            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
17061        }
17062        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17063            Slog.w(TAG, "Instant app package " + pkg.packageName
17064                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
17065            // STOPSHIP: Make this a fatal error
17066            pkg.applicationInfo.targetSandboxVersion = 2;
17067        }
17068
17069        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17070            // Static shared libraries have synthetic package names
17071            renameStaticSharedLibraryPackage(pkg);
17072
17073            // No static shared libs on external storage
17074            if (onExternal) {
17075                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17076                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17077                        "Packages declaring static-shared libs cannot be updated");
17078                return;
17079            }
17080        }
17081
17082        // If we are installing a clustered package add results for the children
17083        if (pkg.childPackages != null) {
17084            synchronized (mPackages) {
17085                final int childCount = pkg.childPackages.size();
17086                for (int i = 0; i < childCount; i++) {
17087                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17088                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17089                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17090                    childRes.pkg = childPkg;
17091                    childRes.name = childPkg.packageName;
17092                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17093                    if (childPs != null) {
17094                        childRes.origUsers = childPs.queryInstalledUsers(
17095                                sUserManager.getUserIds(), true);
17096                    }
17097                    if ((mPackages.containsKey(childPkg.packageName))) {
17098                        childRes.removedInfo = new PackageRemovedInfo(this);
17099                        childRes.removedInfo.removedPackage = childPkg.packageName;
17100                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17101                    }
17102                    if (res.addedChildPackages == null) {
17103                        res.addedChildPackages = new ArrayMap<>();
17104                    }
17105                    res.addedChildPackages.put(childPkg.packageName, childRes);
17106                }
17107            }
17108        }
17109
17110        // If package doesn't declare API override, mark that we have an install
17111        // time CPU ABI override.
17112        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17113            pkg.cpuAbiOverride = args.abiOverride;
17114        }
17115
17116        String pkgName = res.name = pkg.packageName;
17117        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17118            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17119                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17120                return;
17121            }
17122        }
17123
17124        try {
17125            // either use what we've been given or parse directly from the APK
17126            if (args.certificates != null) {
17127                try {
17128                    PackageParser.populateCertificates(pkg, args.certificates);
17129                } catch (PackageParserException e) {
17130                    // there was something wrong with the certificates we were given;
17131                    // try to pull them from the APK
17132                    PackageParser.collectCertificates(pkg, parseFlags);
17133                }
17134            } else {
17135                PackageParser.collectCertificates(pkg, parseFlags);
17136            }
17137        } catch (PackageParserException e) {
17138            res.setError("Failed collect during installPackageLI", e);
17139            return;
17140        }
17141
17142        // Get rid of all references to package scan path via parser.
17143        pp = null;
17144        String oldCodePath = null;
17145        boolean systemApp = false;
17146        synchronized (mPackages) {
17147            // Check if installing already existing package
17148            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17149                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17150                if (pkg.mOriginalPackages != null
17151                        && pkg.mOriginalPackages.contains(oldName)
17152                        && mPackages.containsKey(oldName)) {
17153                    // This package is derived from an original package,
17154                    // and this device has been updating from that original
17155                    // name.  We must continue using the original name, so
17156                    // rename the new package here.
17157                    pkg.setPackageName(oldName);
17158                    pkgName = pkg.packageName;
17159                    replace = true;
17160                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17161                            + oldName + " pkgName=" + pkgName);
17162                } else if (mPackages.containsKey(pkgName)) {
17163                    // This package, under its official name, already exists
17164                    // on the device; we should replace it.
17165                    replace = true;
17166                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17167                }
17168
17169                // Child packages are installed through the parent package
17170                if (pkg.parentPackage != null) {
17171                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17172                            "Package " + pkg.packageName + " is child of package "
17173                                    + pkg.parentPackage.parentPackage + ". Child packages "
17174                                    + "can be updated only through the parent package.");
17175                    return;
17176                }
17177
17178                if (replace) {
17179                    // Prevent apps opting out from runtime permissions
17180                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17181                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17182                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17183                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17184                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17185                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17186                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17187                                        + " doesn't support runtime permissions but the old"
17188                                        + " target SDK " + oldTargetSdk + " does.");
17189                        return;
17190                    }
17191                    // Prevent apps from downgrading their targetSandbox.
17192                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17193                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17194                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17195                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17196                                "Package " + pkg.packageName + " new target sandbox "
17197                                + newTargetSandbox + " is incompatible with the previous value of"
17198                                + oldTargetSandbox + ".");
17199                        return;
17200                    }
17201
17202                    // Prevent installing of child packages
17203                    if (oldPackage.parentPackage != null) {
17204                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17205                                "Package " + pkg.packageName + " is child of package "
17206                                        + oldPackage.parentPackage + ". Child packages "
17207                                        + "can be updated only through the parent package.");
17208                        return;
17209                    }
17210                }
17211            }
17212
17213            PackageSetting ps = mSettings.mPackages.get(pkgName);
17214            if (ps != null) {
17215                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17216
17217                // Static shared libs have same package with different versions where
17218                // we internally use a synthetic package name to allow multiple versions
17219                // of the same package, therefore we need to compare signatures against
17220                // the package setting for the latest library version.
17221                PackageSetting signatureCheckPs = ps;
17222                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17223                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17224                    if (libraryEntry != null) {
17225                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17226                    }
17227                }
17228
17229                // Quick sanity check that we're signed correctly if updating;
17230                // we'll check this again later when scanning, but we want to
17231                // bail early here before tripping over redefined permissions.
17232                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17233                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17234                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17235                                + pkg.packageName + " upgrade keys do not match the "
17236                                + "previously installed version");
17237                        return;
17238                    }
17239                } else {
17240                    try {
17241                        verifySignaturesLP(signatureCheckPs, pkg);
17242                    } catch (PackageManagerException e) {
17243                        res.setError(e.error, e.getMessage());
17244                        return;
17245                    }
17246                }
17247
17248                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17249                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17250                    systemApp = (ps.pkg.applicationInfo.flags &
17251                            ApplicationInfo.FLAG_SYSTEM) != 0;
17252                }
17253                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17254            }
17255
17256            int N = pkg.permissions.size();
17257            for (int i = N-1; i >= 0; i--) {
17258                PackageParser.Permission perm = pkg.permissions.get(i);
17259                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
17260
17261                // Don't allow anyone but the system to define ephemeral permissions.
17262                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
17263                        && !systemApp) {
17264                    Slog.w(TAG, "Non-System package " + pkg.packageName
17265                            + " attempting to delcare ephemeral permission "
17266                            + perm.info.name + "; Removing ephemeral.");
17267                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
17268                }
17269                // Check whether the newly-scanned package wants to define an already-defined perm
17270                if (bp != null) {
17271                    // If the defining package is signed with our cert, it's okay.  This
17272                    // also includes the "updating the same package" case, of course.
17273                    // "updating same package" could also involve key-rotation.
17274                    final boolean sigsOk;
17275                    if (bp.sourcePackage.equals(pkg.packageName)
17276                            && (bp.packageSetting instanceof PackageSetting)
17277                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
17278                                    scanFlags))) {
17279                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
17280                    } else {
17281                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
17282                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17283                    }
17284                    if (!sigsOk) {
17285                        // If the owning package is the system itself, we log but allow
17286                        // install to proceed; we fail the install on all other permission
17287                        // redefinitions.
17288                        if (!bp.sourcePackage.equals("android")) {
17289                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17290                                    + pkg.packageName + " attempting to redeclare permission "
17291                                    + perm.info.name + " already owned by " + bp.sourcePackage);
17292                            res.origPermission = perm.info.name;
17293                            res.origPackage = bp.sourcePackage;
17294                            return;
17295                        } else {
17296                            Slog.w(TAG, "Package " + pkg.packageName
17297                                    + " attempting to redeclare system permission "
17298                                    + perm.info.name + "; ignoring new declaration");
17299                            pkg.permissions.remove(i);
17300                        }
17301                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17302                        // Prevent apps to change protection level to dangerous from any other
17303                        // type as this would allow a privilege escalation where an app adds a
17304                        // normal/signature permission in other app's group and later redefines
17305                        // it as dangerous leading to the group auto-grant.
17306                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17307                                == PermissionInfo.PROTECTION_DANGEROUS) {
17308                            if (bp != null && !bp.isRuntime()) {
17309                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17310                                        + "non-runtime permission " + perm.info.name
17311                                        + " to runtime; keeping old protection level");
17312                                perm.info.protectionLevel = bp.protectionLevel;
17313                            }
17314                        }
17315                    }
17316                }
17317            }
17318        }
17319
17320        if (systemApp) {
17321            if (onExternal) {
17322                // Abort update; system app can't be replaced with app on sdcard
17323                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17324                        "Cannot install updates to system apps on sdcard");
17325                return;
17326            } else if (instantApp) {
17327                // Abort update; system app can't be replaced with an instant app
17328                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17329                        "Cannot update a system app with an instant app");
17330                return;
17331            }
17332        }
17333
17334        if (args.move != null) {
17335            // We did an in-place move, so dex is ready to roll
17336            scanFlags |= SCAN_NO_DEX;
17337            scanFlags |= SCAN_MOVE;
17338
17339            synchronized (mPackages) {
17340                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17341                if (ps == null) {
17342                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17343                            "Missing settings for moved package " + pkgName);
17344                }
17345
17346                // We moved the entire application as-is, so bring over the
17347                // previously derived ABI information.
17348                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17349                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17350            }
17351
17352        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17353            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17354            scanFlags |= SCAN_NO_DEX;
17355
17356            try {
17357                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17358                    args.abiOverride : pkg.cpuAbiOverride);
17359                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17360                        true /*extractLibs*/, mAppLib32InstallDir);
17361            } catch (PackageManagerException pme) {
17362                Slog.e(TAG, "Error deriving application ABI", pme);
17363                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17364                return;
17365            }
17366
17367            // Shared libraries for the package need to be updated.
17368            synchronized (mPackages) {
17369                try {
17370                    updateSharedLibrariesLPr(pkg, null);
17371                } catch (PackageManagerException e) {
17372                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17373                }
17374            }
17375
17376            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17377            // Do not run PackageDexOptimizer through the local performDexOpt
17378            // method because `pkg` may not be in `mPackages` yet.
17379            //
17380            // Also, don't fail application installs if the dexopt step fails.
17381            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17382                    null /* instructionSets */, false /* checkProfiles */,
17383                    getCompilerFilterForReason(REASON_INSTALL),
17384                    getOrCreateCompilerPackageStats(pkg),
17385                    mDexManager.isUsedByOtherApps(pkg.packageName));
17386            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17387
17388            // Notify BackgroundDexOptService that the package has been changed.
17389            // If this is an update of a package which used to fail to compile,
17390            // BDOS will remove it from its blacklist.
17391            // TODO: Layering violation
17392            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17393        }
17394
17395        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17396            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17397            return;
17398        }
17399
17400        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17401
17402        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17403                "installPackageLI")) {
17404            if (replace) {
17405                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17406                    // Static libs have a synthetic package name containing the version
17407                    // and cannot be updated as an update would get a new package name,
17408                    // unless this is the exact same version code which is useful for
17409                    // development.
17410                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17411                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17412                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17413                                + "static-shared libs cannot be updated");
17414                        return;
17415                    }
17416                }
17417                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17418                        installerPackageName, res, args.installReason);
17419            } else {
17420                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17421                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17422            }
17423        }
17424
17425        synchronized (mPackages) {
17426            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17427            if (ps != null) {
17428                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17429                ps.setUpdateAvailable(false /*updateAvailable*/);
17430            }
17431
17432            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17433            for (int i = 0; i < childCount; i++) {
17434                PackageParser.Package childPkg = pkg.childPackages.get(i);
17435                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17436                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17437                if (childPs != null) {
17438                    childRes.newUsers = childPs.queryInstalledUsers(
17439                            sUserManager.getUserIds(), true);
17440                }
17441            }
17442
17443            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17444                updateSequenceNumberLP(pkgName, res.newUsers);
17445                updateInstantAppInstallerLocked(pkgName);
17446            }
17447        }
17448    }
17449
17450    private void startIntentFilterVerifications(int userId, boolean replacing,
17451            PackageParser.Package pkg) {
17452        if (mIntentFilterVerifierComponent == null) {
17453            Slog.w(TAG, "No IntentFilter verification will not be done as "
17454                    + "there is no IntentFilterVerifier available!");
17455            return;
17456        }
17457
17458        final int verifierUid = getPackageUid(
17459                mIntentFilterVerifierComponent.getPackageName(),
17460                MATCH_DEBUG_TRIAGED_MISSING,
17461                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17462
17463        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17464        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17465        mHandler.sendMessage(msg);
17466
17467        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17468        for (int i = 0; i < childCount; i++) {
17469            PackageParser.Package childPkg = pkg.childPackages.get(i);
17470            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17471            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17472            mHandler.sendMessage(msg);
17473        }
17474    }
17475
17476    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17477            PackageParser.Package pkg) {
17478        int size = pkg.activities.size();
17479        if (size == 0) {
17480            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17481                    "No activity, so no need to verify any IntentFilter!");
17482            return;
17483        }
17484
17485        final boolean hasDomainURLs = hasDomainURLs(pkg);
17486        if (!hasDomainURLs) {
17487            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17488                    "No domain URLs, so no need to verify any IntentFilter!");
17489            return;
17490        }
17491
17492        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17493                + " if any IntentFilter from the " + size
17494                + " Activities needs verification ...");
17495
17496        int count = 0;
17497        final String packageName = pkg.packageName;
17498
17499        synchronized (mPackages) {
17500            // If this is a new install and we see that we've already run verification for this
17501            // package, we have nothing to do: it means the state was restored from backup.
17502            if (!replacing) {
17503                IntentFilterVerificationInfo ivi =
17504                        mSettings.getIntentFilterVerificationLPr(packageName);
17505                if (ivi != null) {
17506                    if (DEBUG_DOMAIN_VERIFICATION) {
17507                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17508                                + ivi.getStatusString());
17509                    }
17510                    return;
17511                }
17512            }
17513
17514            // If any filters need to be verified, then all need to be.
17515            boolean needToVerify = false;
17516            for (PackageParser.Activity a : pkg.activities) {
17517                for (ActivityIntentInfo filter : a.intents) {
17518                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17519                        if (DEBUG_DOMAIN_VERIFICATION) {
17520                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17521                        }
17522                        needToVerify = true;
17523                        break;
17524                    }
17525                }
17526            }
17527
17528            if (needToVerify) {
17529                final int verificationId = mIntentFilterVerificationToken++;
17530                for (PackageParser.Activity a : pkg.activities) {
17531                    for (ActivityIntentInfo filter : a.intents) {
17532                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17533                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17534                                    "Verification needed for IntentFilter:" + filter.toString());
17535                            mIntentFilterVerifier.addOneIntentFilterVerification(
17536                                    verifierUid, userId, verificationId, filter, packageName);
17537                            count++;
17538                        }
17539                    }
17540                }
17541            }
17542        }
17543
17544        if (count > 0) {
17545            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17546                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17547                    +  " for userId:" + userId);
17548            mIntentFilterVerifier.startVerifications(userId);
17549        } else {
17550            if (DEBUG_DOMAIN_VERIFICATION) {
17551                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17552            }
17553        }
17554    }
17555
17556    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17557        final ComponentName cn  = filter.activity.getComponentName();
17558        final String packageName = cn.getPackageName();
17559
17560        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17561                packageName);
17562        if (ivi == null) {
17563            return true;
17564        }
17565        int status = ivi.getStatus();
17566        switch (status) {
17567            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17568            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17569                return true;
17570
17571            default:
17572                // Nothing to do
17573                return false;
17574        }
17575    }
17576
17577    private static boolean isMultiArch(ApplicationInfo info) {
17578        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17579    }
17580
17581    private static boolean isExternal(PackageParser.Package pkg) {
17582        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17583    }
17584
17585    private static boolean isExternal(PackageSetting ps) {
17586        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17587    }
17588
17589    private static boolean isSystemApp(PackageParser.Package pkg) {
17590        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17591    }
17592
17593    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17594        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17595    }
17596
17597    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17598        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17599    }
17600
17601    private static boolean isSystemApp(PackageSetting ps) {
17602        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17603    }
17604
17605    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17606        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17607    }
17608
17609    private int packageFlagsToInstallFlags(PackageSetting ps) {
17610        int installFlags = 0;
17611        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17612            // This existing package was an external ASEC install when we have
17613            // the external flag without a UUID
17614            installFlags |= PackageManager.INSTALL_EXTERNAL;
17615        }
17616        if (ps.isForwardLocked()) {
17617            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17618        }
17619        return installFlags;
17620    }
17621
17622    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17623        if (isExternal(pkg)) {
17624            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17625                return StorageManager.UUID_PRIMARY_PHYSICAL;
17626            } else {
17627                return pkg.volumeUuid;
17628            }
17629        } else {
17630            return StorageManager.UUID_PRIVATE_INTERNAL;
17631        }
17632    }
17633
17634    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17635        if (isExternal(pkg)) {
17636            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17637                return mSettings.getExternalVersion();
17638            } else {
17639                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17640            }
17641        } else {
17642            return mSettings.getInternalVersion();
17643        }
17644    }
17645
17646    private void deleteTempPackageFiles() {
17647        final FilenameFilter filter = new FilenameFilter() {
17648            public boolean accept(File dir, String name) {
17649                return name.startsWith("vmdl") && name.endsWith(".tmp");
17650            }
17651        };
17652        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17653            file.delete();
17654        }
17655    }
17656
17657    @Override
17658    public void deletePackageAsUser(String packageName, int versionCode,
17659            IPackageDeleteObserver observer, int userId, int flags) {
17660        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17661                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17662    }
17663
17664    @Override
17665    public void deletePackageVersioned(VersionedPackage versionedPackage,
17666            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17667        mContext.enforceCallingOrSelfPermission(
17668                android.Manifest.permission.DELETE_PACKAGES, null);
17669        Preconditions.checkNotNull(versionedPackage);
17670        Preconditions.checkNotNull(observer);
17671        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17672                PackageManager.VERSION_CODE_HIGHEST,
17673                Integer.MAX_VALUE, "versionCode must be >= -1");
17674
17675        final String packageName = versionedPackage.getPackageName();
17676        // TODO: We will change version code to long, so in the new API it is long
17677        final int versionCode = (int) versionedPackage.getVersionCode();
17678        final String internalPackageName;
17679        synchronized (mPackages) {
17680            // Normalize package name to handle renamed packages and static libs
17681            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17682                    // TODO: We will change version code to long, so in the new API it is long
17683                    (int) versionedPackage.getVersionCode());
17684        }
17685
17686        final int uid = Binder.getCallingUid();
17687        if (!isOrphaned(internalPackageName)
17688                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17689            try {
17690                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17691                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17692                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17693                observer.onUserActionRequired(intent);
17694            } catch (RemoteException re) {
17695            }
17696            return;
17697        }
17698        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17699        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17700        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17701            mContext.enforceCallingOrSelfPermission(
17702                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17703                    "deletePackage for user " + userId);
17704        }
17705
17706        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17707            try {
17708                observer.onPackageDeleted(packageName,
17709                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17710            } catch (RemoteException re) {
17711            }
17712            return;
17713        }
17714
17715        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17716            try {
17717                observer.onPackageDeleted(packageName,
17718                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17719            } catch (RemoteException re) {
17720            }
17721            return;
17722        }
17723
17724        if (DEBUG_REMOVE) {
17725            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17726                    + " deleteAllUsers: " + deleteAllUsers + " version="
17727                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17728                    ? "VERSION_CODE_HIGHEST" : versionCode));
17729        }
17730        // Queue up an async operation since the package deletion may take a little while.
17731        mHandler.post(new Runnable() {
17732            public void run() {
17733                mHandler.removeCallbacks(this);
17734                int returnCode;
17735                if (!deleteAllUsers) {
17736                    returnCode = deletePackageX(internalPackageName, versionCode,
17737                            userId, deleteFlags);
17738                } else {
17739                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17740                            internalPackageName, users);
17741                    // If nobody is blocking uninstall, proceed with delete for all users
17742                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17743                        returnCode = deletePackageX(internalPackageName, versionCode,
17744                                userId, deleteFlags);
17745                    } else {
17746                        // Otherwise uninstall individually for users with blockUninstalls=false
17747                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17748                        for (int userId : users) {
17749                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17750                                returnCode = deletePackageX(internalPackageName, versionCode,
17751                                        userId, userFlags);
17752                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17753                                    Slog.w(TAG, "Package delete failed for user " + userId
17754                                            + ", returnCode " + returnCode);
17755                                }
17756                            }
17757                        }
17758                        // The app has only been marked uninstalled for certain users.
17759                        // We still need to report that delete was blocked
17760                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17761                    }
17762                }
17763                try {
17764                    observer.onPackageDeleted(packageName, returnCode, null);
17765                } catch (RemoteException e) {
17766                    Log.i(TAG, "Observer no longer exists.");
17767                } //end catch
17768            } //end run
17769        });
17770    }
17771
17772    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17773        if (pkg.staticSharedLibName != null) {
17774            return pkg.manifestPackageName;
17775        }
17776        return pkg.packageName;
17777    }
17778
17779    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17780        // Handle renamed packages
17781        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17782        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17783
17784        // Is this a static library?
17785        SparseArray<SharedLibraryEntry> versionedLib =
17786                mStaticLibsByDeclaringPackage.get(packageName);
17787        if (versionedLib == null || versionedLib.size() <= 0) {
17788            return packageName;
17789        }
17790
17791        // Figure out which lib versions the caller can see
17792        SparseIntArray versionsCallerCanSee = null;
17793        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17794        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17795                && callingAppId != Process.ROOT_UID) {
17796            versionsCallerCanSee = new SparseIntArray();
17797            String libName = versionedLib.valueAt(0).info.getName();
17798            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17799            if (uidPackages != null) {
17800                for (String uidPackage : uidPackages) {
17801                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17802                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17803                    if (libIdx >= 0) {
17804                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17805                        versionsCallerCanSee.append(libVersion, libVersion);
17806                    }
17807                }
17808            }
17809        }
17810
17811        // Caller can see nothing - done
17812        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17813            return packageName;
17814        }
17815
17816        // Find the version the caller can see and the app version code
17817        SharedLibraryEntry highestVersion = null;
17818        final int versionCount = versionedLib.size();
17819        for (int i = 0; i < versionCount; i++) {
17820            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17821            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17822                    libEntry.info.getVersion()) < 0) {
17823                continue;
17824            }
17825            // TODO: We will change version code to long, so in the new API it is long
17826            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17827            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17828                if (libVersionCode == versionCode) {
17829                    return libEntry.apk;
17830                }
17831            } else if (highestVersion == null) {
17832                highestVersion = libEntry;
17833            } else if (libVersionCode  > highestVersion.info
17834                    .getDeclaringPackage().getVersionCode()) {
17835                highestVersion = libEntry;
17836            }
17837        }
17838
17839        if (highestVersion != null) {
17840            return highestVersion.apk;
17841        }
17842
17843        return packageName;
17844    }
17845
17846    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17847        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17848              || callingUid == Process.SYSTEM_UID) {
17849            return true;
17850        }
17851        final int callingUserId = UserHandle.getUserId(callingUid);
17852        // If the caller installed the pkgName, then allow it to silently uninstall.
17853        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17854            return true;
17855        }
17856
17857        // Allow package verifier to silently uninstall.
17858        if (mRequiredVerifierPackage != null &&
17859                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17860            return true;
17861        }
17862
17863        // Allow package uninstaller to silently uninstall.
17864        if (mRequiredUninstallerPackage != null &&
17865                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17866            return true;
17867        }
17868
17869        // Allow storage manager to silently uninstall.
17870        if (mStorageManagerPackage != null &&
17871                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17872            return true;
17873        }
17874        return false;
17875    }
17876
17877    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17878        int[] result = EMPTY_INT_ARRAY;
17879        for (int userId : userIds) {
17880            if (getBlockUninstallForUser(packageName, userId)) {
17881                result = ArrayUtils.appendInt(result, userId);
17882            }
17883        }
17884        return result;
17885    }
17886
17887    @Override
17888    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17889        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17890    }
17891
17892    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17893        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17894                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17895        try {
17896            if (dpm != null) {
17897                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17898                        /* callingUserOnly =*/ false);
17899                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17900                        : deviceOwnerComponentName.getPackageName();
17901                // Does the package contains the device owner?
17902                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17903                // this check is probably not needed, since DO should be registered as a device
17904                // admin on some user too. (Original bug for this: b/17657954)
17905                if (packageName.equals(deviceOwnerPackageName)) {
17906                    return true;
17907                }
17908                // Does it contain a device admin for any user?
17909                int[] users;
17910                if (userId == UserHandle.USER_ALL) {
17911                    users = sUserManager.getUserIds();
17912                } else {
17913                    users = new int[]{userId};
17914                }
17915                for (int i = 0; i < users.length; ++i) {
17916                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17917                        return true;
17918                    }
17919                }
17920            }
17921        } catch (RemoteException e) {
17922        }
17923        return false;
17924    }
17925
17926    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17927        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17928    }
17929
17930    /**
17931     *  This method is an internal method that could be get invoked either
17932     *  to delete an installed package or to clean up a failed installation.
17933     *  After deleting an installed package, a broadcast is sent to notify any
17934     *  listeners that the package has been removed. For cleaning up a failed
17935     *  installation, the broadcast is not necessary since the package's
17936     *  installation wouldn't have sent the initial broadcast either
17937     *  The key steps in deleting a package are
17938     *  deleting the package information in internal structures like mPackages,
17939     *  deleting the packages base directories through installd
17940     *  updating mSettings to reflect current status
17941     *  persisting settings for later use
17942     *  sending a broadcast if necessary
17943     */
17944    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17945        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17946        final boolean res;
17947
17948        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17949                ? UserHandle.USER_ALL : userId;
17950
17951        if (isPackageDeviceAdmin(packageName, removeUser)) {
17952            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17953            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17954        }
17955
17956        PackageSetting uninstalledPs = null;
17957        PackageParser.Package pkg = null;
17958
17959        // for the uninstall-updates case and restricted profiles, remember the per-
17960        // user handle installed state
17961        int[] allUsers;
17962        synchronized (mPackages) {
17963            uninstalledPs = mSettings.mPackages.get(packageName);
17964            if (uninstalledPs == null) {
17965                Slog.w(TAG, "Not removing non-existent package " + packageName);
17966                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17967            }
17968
17969            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17970                    && uninstalledPs.versionCode != versionCode) {
17971                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17972                        + uninstalledPs.versionCode + " != " + versionCode);
17973                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17974            }
17975
17976            // Static shared libs can be declared by any package, so let us not
17977            // allow removing a package if it provides a lib others depend on.
17978            pkg = mPackages.get(packageName);
17979            if (pkg != null && pkg.staticSharedLibName != null) {
17980                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17981                        pkg.staticSharedLibVersion);
17982                if (libEntry != null) {
17983                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17984                            libEntry.info, 0, userId);
17985                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17986                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17987                                + " hosting lib " + libEntry.info.getName() + " version "
17988                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17989                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17990                    }
17991                }
17992            }
17993
17994            allUsers = sUserManager.getUserIds();
17995            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17996        }
17997
17998        final int freezeUser;
17999        if (isUpdatedSystemApp(uninstalledPs)
18000                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18001            // We're downgrading a system app, which will apply to all users, so
18002            // freeze them all during the downgrade
18003            freezeUser = UserHandle.USER_ALL;
18004        } else {
18005            freezeUser = removeUser;
18006        }
18007
18008        synchronized (mInstallLock) {
18009            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18010            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18011                    deleteFlags, "deletePackageX")) {
18012                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18013                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18014            }
18015            synchronized (mPackages) {
18016                if (res) {
18017                    if (pkg != null) {
18018                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18019                    }
18020                    updateSequenceNumberLP(packageName, info.removedUsers);
18021                    updateInstantAppInstallerLocked(packageName);
18022                }
18023            }
18024        }
18025
18026        if (res) {
18027            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18028            info.sendPackageRemovedBroadcasts(killApp);
18029            info.sendSystemPackageUpdatedBroadcasts();
18030            info.sendSystemPackageAppearedBroadcasts();
18031        }
18032        // Force a gc here.
18033        Runtime.getRuntime().gc();
18034        // Delete the resources here after sending the broadcast to let
18035        // other processes clean up before deleting resources.
18036        if (info.args != null) {
18037            synchronized (mInstallLock) {
18038                info.args.doPostDeleteLI(true);
18039            }
18040        }
18041
18042        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18043    }
18044
18045    static class PackageRemovedInfo {
18046        final PackageSender packageSender;
18047        String removedPackage;
18048        String installerPackageName;
18049        int uid = -1;
18050        int removedAppId = -1;
18051        int[] origUsers;
18052        int[] removedUsers = null;
18053        int[] broadcastUsers = null;
18054        SparseArray<Integer> installReasons;
18055        boolean isRemovedPackageSystemUpdate = false;
18056        boolean isUpdate;
18057        boolean dataRemoved;
18058        boolean removedForAllUsers;
18059        boolean isStaticSharedLib;
18060        // Clean up resources deleted packages.
18061        InstallArgs args = null;
18062        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18063        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18064
18065        PackageRemovedInfo(PackageSender packageSender) {
18066            this.packageSender = packageSender;
18067        }
18068
18069        void sendPackageRemovedBroadcasts(boolean killApp) {
18070            sendPackageRemovedBroadcastInternal(killApp);
18071            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18072            for (int i = 0; i < childCount; i++) {
18073                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18074                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18075            }
18076        }
18077
18078        void sendSystemPackageUpdatedBroadcasts() {
18079            if (isRemovedPackageSystemUpdate) {
18080                sendSystemPackageUpdatedBroadcastsInternal();
18081                final int childCount = (removedChildPackages != null)
18082                        ? removedChildPackages.size() : 0;
18083                for (int i = 0; i < childCount; i++) {
18084                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18085                    if (childInfo.isRemovedPackageSystemUpdate) {
18086                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18087                    }
18088                }
18089            }
18090        }
18091
18092        void sendSystemPackageAppearedBroadcasts() {
18093            final int packageCount = (appearedChildPackages != null)
18094                    ? appearedChildPackages.size() : 0;
18095            for (int i = 0; i < packageCount; i++) {
18096                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18097                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18098                    true, UserHandle.getAppId(installedInfo.uid),
18099                    installedInfo.newUsers);
18100            }
18101        }
18102
18103        private void sendSystemPackageUpdatedBroadcastsInternal() {
18104            Bundle extras = new Bundle(2);
18105            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18106            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18107            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18108                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18109            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18110                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18111            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18112                null, null, 0, removedPackage, null, null);
18113            if (installerPackageName != null) {
18114                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18115                        removedPackage, extras, 0 /*flags*/,
18116                        installerPackageName, null, null);
18117                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18118                        removedPackage, extras, 0 /*flags*/,
18119                        installerPackageName, null, null);
18120            }
18121        }
18122
18123        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18124            // Don't send static shared library removal broadcasts as these
18125            // libs are visible only the the apps that depend on them an one
18126            // cannot remove the library if it has a dependency.
18127            if (isStaticSharedLib) {
18128                return;
18129            }
18130            Bundle extras = new Bundle(2);
18131            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18132            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18133            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18134            if (isUpdate || isRemovedPackageSystemUpdate) {
18135                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18136            }
18137            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18138            if (removedPackage != null) {
18139                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18140                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18141                if (installerPackageName != null) {
18142                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18143                            removedPackage, extras, 0 /*flags*/,
18144                            installerPackageName, null, broadcastUsers);
18145                }
18146                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18147                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18148                        removedPackage, extras,
18149                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18150                        null, null, broadcastUsers);
18151                }
18152            }
18153            if (removedAppId >= 0) {
18154                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
18155                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
18156            }
18157        }
18158
18159        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18160            removedUsers = userIds;
18161            if (removedUsers == null) {
18162                broadcastUsers = null;
18163                return;
18164            }
18165
18166            broadcastUsers = EMPTY_INT_ARRAY;
18167            for (int i = userIds.length - 1; i >= 0; --i) {
18168                final int userId = userIds[i];
18169                if (deletedPackageSetting.getInstantApp(userId)) {
18170                    continue;
18171                }
18172                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18173            }
18174        }
18175    }
18176
18177    /*
18178     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18179     * flag is not set, the data directory is removed as well.
18180     * make sure this flag is set for partially installed apps. If not its meaningless to
18181     * delete a partially installed application.
18182     */
18183    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18184            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18185        String packageName = ps.name;
18186        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18187        // Retrieve object to delete permissions for shared user later on
18188        final PackageParser.Package deletedPkg;
18189        final PackageSetting deletedPs;
18190        // reader
18191        synchronized (mPackages) {
18192            deletedPkg = mPackages.get(packageName);
18193            deletedPs = mSettings.mPackages.get(packageName);
18194            if (outInfo != null) {
18195                outInfo.removedPackage = packageName;
18196                outInfo.installerPackageName = ps.installerPackageName;
18197                outInfo.isStaticSharedLib = deletedPkg != null
18198                        && deletedPkg.staticSharedLibName != null;
18199                outInfo.populateUsers(deletedPs == null ? null
18200                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18201            }
18202        }
18203
18204        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18205
18206        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18207            final PackageParser.Package resolvedPkg;
18208            if (deletedPkg != null) {
18209                resolvedPkg = deletedPkg;
18210            } else {
18211                // We don't have a parsed package when it lives on an ejected
18212                // adopted storage device, so fake something together
18213                resolvedPkg = new PackageParser.Package(ps.name);
18214                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18215            }
18216            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18217                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18218            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18219            if (outInfo != null) {
18220                outInfo.dataRemoved = true;
18221            }
18222            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18223        }
18224
18225        int removedAppId = -1;
18226
18227        // writer
18228        synchronized (mPackages) {
18229            boolean installedStateChanged = false;
18230            if (deletedPs != null) {
18231                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18232                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18233                    clearDefaultBrowserIfNeeded(packageName);
18234                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18235                    removedAppId = mSettings.removePackageLPw(packageName);
18236                    if (outInfo != null) {
18237                        outInfo.removedAppId = removedAppId;
18238                    }
18239                    updatePermissionsLPw(deletedPs.name, null, 0);
18240                    if (deletedPs.sharedUser != null) {
18241                        // Remove permissions associated with package. Since runtime
18242                        // permissions are per user we have to kill the removed package
18243                        // or packages running under the shared user of the removed
18244                        // package if revoking the permissions requested only by the removed
18245                        // package is successful and this causes a change in gids.
18246                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18247                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18248                                    userId);
18249                            if (userIdToKill == UserHandle.USER_ALL
18250                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18251                                // If gids changed for this user, kill all affected packages.
18252                                mHandler.post(new Runnable() {
18253                                    @Override
18254                                    public void run() {
18255                                        // This has to happen with no lock held.
18256                                        killApplication(deletedPs.name, deletedPs.appId,
18257                                                KILL_APP_REASON_GIDS_CHANGED);
18258                                    }
18259                                });
18260                                break;
18261                            }
18262                        }
18263                    }
18264                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18265                }
18266                // make sure to preserve per-user disabled state if this removal was just
18267                // a downgrade of a system app to the factory package
18268                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18269                    if (DEBUG_REMOVE) {
18270                        Slog.d(TAG, "Propagating install state across downgrade");
18271                    }
18272                    for (int userId : allUserHandles) {
18273                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18274                        if (DEBUG_REMOVE) {
18275                            Slog.d(TAG, "    user " + userId + " => " + installed);
18276                        }
18277                        if (installed != ps.getInstalled(userId)) {
18278                            installedStateChanged = true;
18279                        }
18280                        ps.setInstalled(installed, userId);
18281                    }
18282                }
18283            }
18284            // can downgrade to reader
18285            if (writeSettings) {
18286                // Save settings now
18287                mSettings.writeLPr();
18288            }
18289            if (installedStateChanged) {
18290                mSettings.writeKernelMappingLPr(ps);
18291            }
18292        }
18293        if (removedAppId != -1) {
18294            // A user ID was deleted here. Go through all users and remove it
18295            // from KeyStore.
18296            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18297        }
18298    }
18299
18300    static boolean locationIsPrivileged(File path) {
18301        try {
18302            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18303                    .getCanonicalPath();
18304            return path.getCanonicalPath().startsWith(privilegedAppDir);
18305        } catch (IOException e) {
18306            Slog.e(TAG, "Unable to access code path " + path);
18307        }
18308        return false;
18309    }
18310
18311    /*
18312     * Tries to delete system package.
18313     */
18314    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18315            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18316            boolean writeSettings) {
18317        if (deletedPs.parentPackageName != null) {
18318            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18319            return false;
18320        }
18321
18322        final boolean applyUserRestrictions
18323                = (allUserHandles != null) && (outInfo.origUsers != null);
18324        final PackageSetting disabledPs;
18325        // Confirm if the system package has been updated
18326        // An updated system app can be deleted. This will also have to restore
18327        // the system pkg from system partition
18328        // reader
18329        synchronized (mPackages) {
18330            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18331        }
18332
18333        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18334                + " disabledPs=" + disabledPs);
18335
18336        if (disabledPs == null) {
18337            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18338            return false;
18339        } else if (DEBUG_REMOVE) {
18340            Slog.d(TAG, "Deleting system pkg from data partition");
18341        }
18342
18343        if (DEBUG_REMOVE) {
18344            if (applyUserRestrictions) {
18345                Slog.d(TAG, "Remembering install states:");
18346                for (int userId : allUserHandles) {
18347                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18348                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18349                }
18350            }
18351        }
18352
18353        // Delete the updated package
18354        outInfo.isRemovedPackageSystemUpdate = true;
18355        if (outInfo.removedChildPackages != null) {
18356            final int childCount = (deletedPs.childPackageNames != null)
18357                    ? deletedPs.childPackageNames.size() : 0;
18358            for (int i = 0; i < childCount; i++) {
18359                String childPackageName = deletedPs.childPackageNames.get(i);
18360                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18361                        .contains(childPackageName)) {
18362                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18363                            childPackageName);
18364                    if (childInfo != null) {
18365                        childInfo.isRemovedPackageSystemUpdate = true;
18366                    }
18367                }
18368            }
18369        }
18370
18371        if (disabledPs.versionCode < deletedPs.versionCode) {
18372            // Delete data for downgrades
18373            flags &= ~PackageManager.DELETE_KEEP_DATA;
18374        } else {
18375            // Preserve data by setting flag
18376            flags |= PackageManager.DELETE_KEEP_DATA;
18377        }
18378
18379        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18380                outInfo, writeSettings, disabledPs.pkg);
18381        if (!ret) {
18382            return false;
18383        }
18384
18385        // writer
18386        synchronized (mPackages) {
18387            // Reinstate the old system package
18388            enableSystemPackageLPw(disabledPs.pkg);
18389            // Remove any native libraries from the upgraded package.
18390            removeNativeBinariesLI(deletedPs);
18391        }
18392
18393        // Install the system package
18394        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18395        int parseFlags = mDefParseFlags
18396                | PackageParser.PARSE_MUST_BE_APK
18397                | PackageParser.PARSE_IS_SYSTEM
18398                | PackageParser.PARSE_IS_SYSTEM_DIR;
18399        if (locationIsPrivileged(disabledPs.codePath)) {
18400            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18401        }
18402
18403        final PackageParser.Package newPkg;
18404        try {
18405            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
18406                0 /* currentTime */, null);
18407        } catch (PackageManagerException e) {
18408            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18409                    + e.getMessage());
18410            return false;
18411        }
18412
18413        try {
18414            // update shared libraries for the newly re-installed system package
18415            updateSharedLibrariesLPr(newPkg, null);
18416        } catch (PackageManagerException e) {
18417            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18418        }
18419
18420        prepareAppDataAfterInstallLIF(newPkg);
18421
18422        // writer
18423        synchronized (mPackages) {
18424            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18425
18426            // Propagate the permissions state as we do not want to drop on the floor
18427            // runtime permissions. The update permissions method below will take
18428            // care of removing obsolete permissions and grant install permissions.
18429            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
18430            updatePermissionsLPw(newPkg.packageName, newPkg,
18431                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18432
18433            if (applyUserRestrictions) {
18434                boolean installedStateChanged = false;
18435                if (DEBUG_REMOVE) {
18436                    Slog.d(TAG, "Propagating install state across reinstall");
18437                }
18438                for (int userId : allUserHandles) {
18439                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18440                    if (DEBUG_REMOVE) {
18441                        Slog.d(TAG, "    user " + userId + " => " + installed);
18442                    }
18443                    if (installed != ps.getInstalled(userId)) {
18444                        installedStateChanged = true;
18445                    }
18446                    ps.setInstalled(installed, userId);
18447
18448                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18449                }
18450                // Regardless of writeSettings we need to ensure that this restriction
18451                // state propagation is persisted
18452                mSettings.writeAllUsersPackageRestrictionsLPr();
18453                if (installedStateChanged) {
18454                    mSettings.writeKernelMappingLPr(ps);
18455                }
18456            }
18457            // can downgrade to reader here
18458            if (writeSettings) {
18459                mSettings.writeLPr();
18460            }
18461        }
18462        return true;
18463    }
18464
18465    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18466            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18467            PackageRemovedInfo outInfo, boolean writeSettings,
18468            PackageParser.Package replacingPackage) {
18469        synchronized (mPackages) {
18470            if (outInfo != null) {
18471                outInfo.uid = ps.appId;
18472            }
18473
18474            if (outInfo != null && outInfo.removedChildPackages != null) {
18475                final int childCount = (ps.childPackageNames != null)
18476                        ? ps.childPackageNames.size() : 0;
18477                for (int i = 0; i < childCount; i++) {
18478                    String childPackageName = ps.childPackageNames.get(i);
18479                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18480                    if (childPs == null) {
18481                        return false;
18482                    }
18483                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18484                            childPackageName);
18485                    if (childInfo != null) {
18486                        childInfo.uid = childPs.appId;
18487                    }
18488                }
18489            }
18490        }
18491
18492        // Delete package data from internal structures and also remove data if flag is set
18493        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18494
18495        // Delete the child packages data
18496        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18497        for (int i = 0; i < childCount; i++) {
18498            PackageSetting childPs;
18499            synchronized (mPackages) {
18500                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18501            }
18502            if (childPs != null) {
18503                PackageRemovedInfo childOutInfo = (outInfo != null
18504                        && outInfo.removedChildPackages != null)
18505                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18506                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18507                        && (replacingPackage != null
18508                        && !replacingPackage.hasChildPackage(childPs.name))
18509                        ? flags & ~DELETE_KEEP_DATA : flags;
18510                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18511                        deleteFlags, writeSettings);
18512            }
18513        }
18514
18515        // Delete application code and resources only for parent packages
18516        if (ps.parentPackageName == null) {
18517            if (deleteCodeAndResources && (outInfo != null)) {
18518                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18519                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18520                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18521            }
18522        }
18523
18524        return true;
18525    }
18526
18527    @Override
18528    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18529            int userId) {
18530        mContext.enforceCallingOrSelfPermission(
18531                android.Manifest.permission.DELETE_PACKAGES, null);
18532        synchronized (mPackages) {
18533            // Cannot block uninstall of static shared libs as they are
18534            // considered a part of the using app (emulating static linking).
18535            // Also static libs are installed always on internal storage.
18536            PackageParser.Package pkg = mPackages.get(packageName);
18537            if (pkg != null && pkg.staticSharedLibName != null) {
18538                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18539                        + " providing static shared library: " + pkg.staticSharedLibName);
18540                return false;
18541            }
18542            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18543            mSettings.writePackageRestrictionsLPr(userId);
18544        }
18545        return true;
18546    }
18547
18548    @Override
18549    public boolean getBlockUninstallForUser(String packageName, int userId) {
18550        synchronized (mPackages) {
18551            return mSettings.getBlockUninstallLPr(userId, packageName);
18552        }
18553    }
18554
18555    @Override
18556    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18557        int callingUid = Binder.getCallingUid();
18558        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18559            throw new SecurityException(
18560                    "setRequiredForSystemUser can only be run by the system or root");
18561        }
18562        synchronized (mPackages) {
18563            PackageSetting ps = mSettings.mPackages.get(packageName);
18564            if (ps == null) {
18565                Log.w(TAG, "Package doesn't exist: " + packageName);
18566                return false;
18567            }
18568            if (systemUserApp) {
18569                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18570            } else {
18571                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18572            }
18573            mSettings.writeLPr();
18574        }
18575        return true;
18576    }
18577
18578    /*
18579     * This method handles package deletion in general
18580     */
18581    private boolean deletePackageLIF(String packageName, UserHandle user,
18582            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18583            PackageRemovedInfo outInfo, boolean writeSettings,
18584            PackageParser.Package replacingPackage) {
18585        if (packageName == null) {
18586            Slog.w(TAG, "Attempt to delete null packageName.");
18587            return false;
18588        }
18589
18590        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18591
18592        PackageSetting ps;
18593        synchronized (mPackages) {
18594            ps = mSettings.mPackages.get(packageName);
18595            if (ps == null) {
18596                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18597                return false;
18598            }
18599
18600            if (ps.parentPackageName != null && (!isSystemApp(ps)
18601                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18602                if (DEBUG_REMOVE) {
18603                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18604                            + ((user == null) ? UserHandle.USER_ALL : user));
18605                }
18606                final int removedUserId = (user != null) ? user.getIdentifier()
18607                        : UserHandle.USER_ALL;
18608                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18609                    return false;
18610                }
18611                markPackageUninstalledForUserLPw(ps, user);
18612                scheduleWritePackageRestrictionsLocked(user);
18613                return true;
18614            }
18615        }
18616
18617        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18618                && user.getIdentifier() != UserHandle.USER_ALL)) {
18619            // The caller is asking that the package only be deleted for a single
18620            // user.  To do this, we just mark its uninstalled state and delete
18621            // its data. If this is a system app, we only allow this to happen if
18622            // they have set the special DELETE_SYSTEM_APP which requests different
18623            // semantics than normal for uninstalling system apps.
18624            markPackageUninstalledForUserLPw(ps, user);
18625
18626            if (!isSystemApp(ps)) {
18627                // Do not uninstall the APK if an app should be cached
18628                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18629                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18630                    // Other user still have this package installed, so all
18631                    // we need to do is clear this user's data and save that
18632                    // it is uninstalled.
18633                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18634                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18635                        return false;
18636                    }
18637                    scheduleWritePackageRestrictionsLocked(user);
18638                    return true;
18639                } else {
18640                    // We need to set it back to 'installed' so the uninstall
18641                    // broadcasts will be sent correctly.
18642                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18643                    ps.setInstalled(true, user.getIdentifier());
18644                    mSettings.writeKernelMappingLPr(ps);
18645                }
18646            } else {
18647                // This is a system app, so we assume that the
18648                // other users still have this package installed, so all
18649                // we need to do is clear this user's data and save that
18650                // it is uninstalled.
18651                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18652                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18653                    return false;
18654                }
18655                scheduleWritePackageRestrictionsLocked(user);
18656                return true;
18657            }
18658        }
18659
18660        // If we are deleting a composite package for all users, keep track
18661        // of result for each child.
18662        if (ps.childPackageNames != null && outInfo != null) {
18663            synchronized (mPackages) {
18664                final int childCount = ps.childPackageNames.size();
18665                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18666                for (int i = 0; i < childCount; i++) {
18667                    String childPackageName = ps.childPackageNames.get(i);
18668                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18669                    childInfo.removedPackage = childPackageName;
18670                    childInfo.installerPackageName = ps.installerPackageName;
18671                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18672                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18673                    if (childPs != null) {
18674                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18675                    }
18676                }
18677            }
18678        }
18679
18680        boolean ret = false;
18681        if (isSystemApp(ps)) {
18682            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18683            // When an updated system application is deleted we delete the existing resources
18684            // as well and fall back to existing code in system partition
18685            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18686        } else {
18687            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18688            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18689                    outInfo, writeSettings, replacingPackage);
18690        }
18691
18692        // Take a note whether we deleted the package for all users
18693        if (outInfo != null) {
18694            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18695            if (outInfo.removedChildPackages != null) {
18696                synchronized (mPackages) {
18697                    final int childCount = outInfo.removedChildPackages.size();
18698                    for (int i = 0; i < childCount; i++) {
18699                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18700                        if (childInfo != null) {
18701                            childInfo.removedForAllUsers = mPackages.get(
18702                                    childInfo.removedPackage) == null;
18703                        }
18704                    }
18705                }
18706            }
18707            // If we uninstalled an update to a system app there may be some
18708            // child packages that appeared as they are declared in the system
18709            // app but were not declared in the update.
18710            if (isSystemApp(ps)) {
18711                synchronized (mPackages) {
18712                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18713                    final int childCount = (updatedPs.childPackageNames != null)
18714                            ? updatedPs.childPackageNames.size() : 0;
18715                    for (int i = 0; i < childCount; i++) {
18716                        String childPackageName = updatedPs.childPackageNames.get(i);
18717                        if (outInfo.removedChildPackages == null
18718                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18719                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18720                            if (childPs == null) {
18721                                continue;
18722                            }
18723                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18724                            installRes.name = childPackageName;
18725                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18726                            installRes.pkg = mPackages.get(childPackageName);
18727                            installRes.uid = childPs.pkg.applicationInfo.uid;
18728                            if (outInfo.appearedChildPackages == null) {
18729                                outInfo.appearedChildPackages = new ArrayMap<>();
18730                            }
18731                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18732                        }
18733                    }
18734                }
18735            }
18736        }
18737
18738        return ret;
18739    }
18740
18741    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18742        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18743                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18744        for (int nextUserId : userIds) {
18745            if (DEBUG_REMOVE) {
18746                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18747            }
18748            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18749                    false /*installed*/,
18750                    true /*stopped*/,
18751                    true /*notLaunched*/,
18752                    false /*hidden*/,
18753                    false /*suspended*/,
18754                    false /*instantApp*/,
18755                    null /*lastDisableAppCaller*/,
18756                    null /*enabledComponents*/,
18757                    null /*disabledComponents*/,
18758                    ps.readUserState(nextUserId).domainVerificationStatus,
18759                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18760        }
18761        mSettings.writeKernelMappingLPr(ps);
18762    }
18763
18764    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18765            PackageRemovedInfo outInfo) {
18766        final PackageParser.Package pkg;
18767        synchronized (mPackages) {
18768            pkg = mPackages.get(ps.name);
18769        }
18770
18771        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18772                : new int[] {userId};
18773        for (int nextUserId : userIds) {
18774            if (DEBUG_REMOVE) {
18775                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18776                        + nextUserId);
18777            }
18778
18779            destroyAppDataLIF(pkg, userId,
18780                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18781            destroyAppProfilesLIF(pkg, userId);
18782            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18783            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18784            schedulePackageCleaning(ps.name, nextUserId, false);
18785            synchronized (mPackages) {
18786                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18787                    scheduleWritePackageRestrictionsLocked(nextUserId);
18788                }
18789                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18790            }
18791        }
18792
18793        if (outInfo != null) {
18794            outInfo.removedPackage = ps.name;
18795            outInfo.installerPackageName = ps.installerPackageName;
18796            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18797            outInfo.removedAppId = ps.appId;
18798            outInfo.removedUsers = userIds;
18799            outInfo.broadcastUsers = userIds;
18800        }
18801
18802        return true;
18803    }
18804
18805    private final class ClearStorageConnection implements ServiceConnection {
18806        IMediaContainerService mContainerService;
18807
18808        @Override
18809        public void onServiceConnected(ComponentName name, IBinder service) {
18810            synchronized (this) {
18811                mContainerService = IMediaContainerService.Stub
18812                        .asInterface(Binder.allowBlocking(service));
18813                notifyAll();
18814            }
18815        }
18816
18817        @Override
18818        public void onServiceDisconnected(ComponentName name) {
18819        }
18820    }
18821
18822    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18823        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18824
18825        final boolean mounted;
18826        if (Environment.isExternalStorageEmulated()) {
18827            mounted = true;
18828        } else {
18829            final String status = Environment.getExternalStorageState();
18830
18831            mounted = status.equals(Environment.MEDIA_MOUNTED)
18832                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18833        }
18834
18835        if (!mounted) {
18836            return;
18837        }
18838
18839        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18840        int[] users;
18841        if (userId == UserHandle.USER_ALL) {
18842            users = sUserManager.getUserIds();
18843        } else {
18844            users = new int[] { userId };
18845        }
18846        final ClearStorageConnection conn = new ClearStorageConnection();
18847        if (mContext.bindServiceAsUser(
18848                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18849            try {
18850                for (int curUser : users) {
18851                    long timeout = SystemClock.uptimeMillis() + 5000;
18852                    synchronized (conn) {
18853                        long now;
18854                        while (conn.mContainerService == null &&
18855                                (now = SystemClock.uptimeMillis()) < timeout) {
18856                            try {
18857                                conn.wait(timeout - now);
18858                            } catch (InterruptedException e) {
18859                            }
18860                        }
18861                    }
18862                    if (conn.mContainerService == null) {
18863                        return;
18864                    }
18865
18866                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18867                    clearDirectory(conn.mContainerService,
18868                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18869                    if (allData) {
18870                        clearDirectory(conn.mContainerService,
18871                                userEnv.buildExternalStorageAppDataDirs(packageName));
18872                        clearDirectory(conn.mContainerService,
18873                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18874                    }
18875                }
18876            } finally {
18877                mContext.unbindService(conn);
18878            }
18879        }
18880    }
18881
18882    @Override
18883    public void clearApplicationProfileData(String packageName) {
18884        enforceSystemOrRoot("Only the system can clear all profile data");
18885
18886        final PackageParser.Package pkg;
18887        synchronized (mPackages) {
18888            pkg = mPackages.get(packageName);
18889        }
18890
18891        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18892            synchronized (mInstallLock) {
18893                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18894            }
18895        }
18896    }
18897
18898    @Override
18899    public void clearApplicationUserData(final String packageName,
18900            final IPackageDataObserver observer, final int userId) {
18901        mContext.enforceCallingOrSelfPermission(
18902                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18903
18904        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18905                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18906
18907        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18908            throw new SecurityException("Cannot clear data for a protected package: "
18909                    + packageName);
18910        }
18911        // Queue up an async operation since the package deletion may take a little while.
18912        mHandler.post(new Runnable() {
18913            public void run() {
18914                mHandler.removeCallbacks(this);
18915                final boolean succeeded;
18916                try (PackageFreezer freezer = freezePackage(packageName,
18917                        "clearApplicationUserData")) {
18918                    synchronized (mInstallLock) {
18919                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18920                    }
18921                    clearExternalStorageDataSync(packageName, userId, true);
18922                    synchronized (mPackages) {
18923                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18924                                packageName, userId);
18925                    }
18926                }
18927                if (succeeded) {
18928                    // invoke DeviceStorageMonitor's update method to clear any notifications
18929                    DeviceStorageMonitorInternal dsm = LocalServices
18930                            .getService(DeviceStorageMonitorInternal.class);
18931                    if (dsm != null) {
18932                        dsm.checkMemory();
18933                    }
18934                }
18935                if(observer != null) {
18936                    try {
18937                        observer.onRemoveCompleted(packageName, succeeded);
18938                    } catch (RemoteException e) {
18939                        Log.i(TAG, "Observer no longer exists.");
18940                    }
18941                } //end if observer
18942            } //end run
18943        });
18944    }
18945
18946    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18947        if (packageName == null) {
18948            Slog.w(TAG, "Attempt to delete null packageName.");
18949            return false;
18950        }
18951
18952        // Try finding details about the requested package
18953        PackageParser.Package pkg;
18954        synchronized (mPackages) {
18955            pkg = mPackages.get(packageName);
18956            if (pkg == null) {
18957                final PackageSetting ps = mSettings.mPackages.get(packageName);
18958                if (ps != null) {
18959                    pkg = ps.pkg;
18960                }
18961            }
18962
18963            if (pkg == null) {
18964                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18965                return false;
18966            }
18967
18968            PackageSetting ps = (PackageSetting) pkg.mExtras;
18969            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18970        }
18971
18972        clearAppDataLIF(pkg, userId,
18973                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18974
18975        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18976        removeKeystoreDataIfNeeded(userId, appId);
18977
18978        UserManagerInternal umInternal = getUserManagerInternal();
18979        final int flags;
18980        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18981            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18982        } else if (umInternal.isUserRunning(userId)) {
18983            flags = StorageManager.FLAG_STORAGE_DE;
18984        } else {
18985            flags = 0;
18986        }
18987        prepareAppDataContentsLIF(pkg, userId, flags);
18988
18989        return true;
18990    }
18991
18992    /**
18993     * Reverts user permission state changes (permissions and flags) in
18994     * all packages for a given user.
18995     *
18996     * @param userId The device user for which to do a reset.
18997     */
18998    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18999        final int packageCount = mPackages.size();
19000        for (int i = 0; i < packageCount; i++) {
19001            PackageParser.Package pkg = mPackages.valueAt(i);
19002            PackageSetting ps = (PackageSetting) pkg.mExtras;
19003            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19004        }
19005    }
19006
19007    private void resetNetworkPolicies(int userId) {
19008        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19009    }
19010
19011    /**
19012     * Reverts user permission state changes (permissions and flags).
19013     *
19014     * @param ps The package for which to reset.
19015     * @param userId The device user for which to do a reset.
19016     */
19017    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19018            final PackageSetting ps, final int userId) {
19019        if (ps.pkg == null) {
19020            return;
19021        }
19022
19023        // These are flags that can change base on user actions.
19024        final int userSettableMask = FLAG_PERMISSION_USER_SET
19025                | FLAG_PERMISSION_USER_FIXED
19026                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19027                | FLAG_PERMISSION_REVIEW_REQUIRED;
19028
19029        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19030                | FLAG_PERMISSION_POLICY_FIXED;
19031
19032        boolean writeInstallPermissions = false;
19033        boolean writeRuntimePermissions = false;
19034
19035        final int permissionCount = ps.pkg.requestedPermissions.size();
19036        for (int i = 0; i < permissionCount; i++) {
19037            String permission = ps.pkg.requestedPermissions.get(i);
19038
19039            BasePermission bp = mSettings.mPermissions.get(permission);
19040            if (bp == null) {
19041                continue;
19042            }
19043
19044            // If shared user we just reset the state to which only this app contributed.
19045            if (ps.sharedUser != null) {
19046                boolean used = false;
19047                final int packageCount = ps.sharedUser.packages.size();
19048                for (int j = 0; j < packageCount; j++) {
19049                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19050                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19051                            && pkg.pkg.requestedPermissions.contains(permission)) {
19052                        used = true;
19053                        break;
19054                    }
19055                }
19056                if (used) {
19057                    continue;
19058                }
19059            }
19060
19061            PermissionsState permissionsState = ps.getPermissionsState();
19062
19063            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19064
19065            // Always clear the user settable flags.
19066            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19067                    bp.name) != null;
19068            // If permission review is enabled and this is a legacy app, mark the
19069            // permission as requiring a review as this is the initial state.
19070            int flags = 0;
19071            if (mPermissionReviewRequired
19072                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19073                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19074            }
19075            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19076                if (hasInstallState) {
19077                    writeInstallPermissions = true;
19078                } else {
19079                    writeRuntimePermissions = true;
19080                }
19081            }
19082
19083            // Below is only runtime permission handling.
19084            if (!bp.isRuntime()) {
19085                continue;
19086            }
19087
19088            // Never clobber system or policy.
19089            if ((oldFlags & policyOrSystemFlags) != 0) {
19090                continue;
19091            }
19092
19093            // If this permission was granted by default, make sure it is.
19094            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19095                if (permissionsState.grantRuntimePermission(bp, userId)
19096                        != PERMISSION_OPERATION_FAILURE) {
19097                    writeRuntimePermissions = true;
19098                }
19099            // If permission review is enabled the permissions for a legacy apps
19100            // are represented as constantly granted runtime ones, so don't revoke.
19101            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19102                // Otherwise, reset the permission.
19103                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19104                switch (revokeResult) {
19105                    case PERMISSION_OPERATION_SUCCESS:
19106                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19107                        writeRuntimePermissions = true;
19108                        final int appId = ps.appId;
19109                        mHandler.post(new Runnable() {
19110                            @Override
19111                            public void run() {
19112                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19113                            }
19114                        });
19115                    } break;
19116                }
19117            }
19118        }
19119
19120        // Synchronously write as we are taking permissions away.
19121        if (writeRuntimePermissions) {
19122            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19123        }
19124
19125        // Synchronously write as we are taking permissions away.
19126        if (writeInstallPermissions) {
19127            mSettings.writeLPr();
19128        }
19129    }
19130
19131    /**
19132     * Remove entries from the keystore daemon. Will only remove it if the
19133     * {@code appId} is valid.
19134     */
19135    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19136        if (appId < 0) {
19137            return;
19138        }
19139
19140        final KeyStore keyStore = KeyStore.getInstance();
19141        if (keyStore != null) {
19142            if (userId == UserHandle.USER_ALL) {
19143                for (final int individual : sUserManager.getUserIds()) {
19144                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19145                }
19146            } else {
19147                keyStore.clearUid(UserHandle.getUid(userId, appId));
19148            }
19149        } else {
19150            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19151        }
19152    }
19153
19154    @Override
19155    public void deleteApplicationCacheFiles(final String packageName,
19156            final IPackageDataObserver observer) {
19157        final int userId = UserHandle.getCallingUserId();
19158        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19159    }
19160
19161    @Override
19162    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19163            final IPackageDataObserver observer) {
19164        mContext.enforceCallingOrSelfPermission(
19165                android.Manifest.permission.DELETE_CACHE_FILES, null);
19166        enforceCrossUserPermission(Binder.getCallingUid(), userId,
19167                /* requireFullPermission= */ true, /* checkShell= */ false,
19168                "delete application cache files");
19169
19170        final PackageParser.Package pkg;
19171        synchronized (mPackages) {
19172            pkg = mPackages.get(packageName);
19173        }
19174
19175        // Queue up an async operation since the package deletion may take a little while.
19176        mHandler.post(new Runnable() {
19177            public void run() {
19178                synchronized (mInstallLock) {
19179                    final int flags = StorageManager.FLAG_STORAGE_DE
19180                            | StorageManager.FLAG_STORAGE_CE;
19181                    // We're only clearing cache files, so we don't care if the
19182                    // app is unfrozen and still able to run
19183                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19184                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19185                }
19186                clearExternalStorageDataSync(packageName, userId, false);
19187                if (observer != null) {
19188                    try {
19189                        observer.onRemoveCompleted(packageName, true);
19190                    } catch (RemoteException e) {
19191                        Log.i(TAG, "Observer no longer exists.");
19192                    }
19193                }
19194            }
19195        });
19196    }
19197
19198    @Override
19199    public void getPackageSizeInfo(final String packageName, int userHandle,
19200            final IPackageStatsObserver observer) {
19201        throw new UnsupportedOperationException(
19202                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19203    }
19204
19205    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19206        final PackageSetting ps;
19207        synchronized (mPackages) {
19208            ps = mSettings.mPackages.get(packageName);
19209            if (ps == null) {
19210                Slog.w(TAG, "Failed to find settings for " + packageName);
19211                return false;
19212            }
19213        }
19214
19215        final String[] packageNames = { packageName };
19216        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19217        final String[] codePaths = { ps.codePathString };
19218
19219        try {
19220            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19221                    ps.appId, ceDataInodes, codePaths, stats);
19222
19223            // For now, ignore code size of packages on system partition
19224            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19225                stats.codeSize = 0;
19226            }
19227
19228            // External clients expect these to be tracked separately
19229            stats.dataSize -= stats.cacheSize;
19230
19231        } catch (InstallerException e) {
19232            Slog.w(TAG, String.valueOf(e));
19233            return false;
19234        }
19235
19236        return true;
19237    }
19238
19239    private int getUidTargetSdkVersionLockedLPr(int uid) {
19240        Object obj = mSettings.getUserIdLPr(uid);
19241        if (obj instanceof SharedUserSetting) {
19242            final SharedUserSetting sus = (SharedUserSetting) obj;
19243            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19244            final Iterator<PackageSetting> it = sus.packages.iterator();
19245            while (it.hasNext()) {
19246                final PackageSetting ps = it.next();
19247                if (ps.pkg != null) {
19248                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19249                    if (v < vers) vers = v;
19250                }
19251            }
19252            return vers;
19253        } else if (obj instanceof PackageSetting) {
19254            final PackageSetting ps = (PackageSetting) obj;
19255            if (ps.pkg != null) {
19256                return ps.pkg.applicationInfo.targetSdkVersion;
19257            }
19258        }
19259        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19260    }
19261
19262    @Override
19263    public void addPreferredActivity(IntentFilter filter, int match,
19264            ComponentName[] set, ComponentName activity, int userId) {
19265        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19266                "Adding preferred");
19267    }
19268
19269    private void addPreferredActivityInternal(IntentFilter filter, int match,
19270            ComponentName[] set, ComponentName activity, boolean always, int userId,
19271            String opname) {
19272        // writer
19273        int callingUid = Binder.getCallingUid();
19274        enforceCrossUserPermission(callingUid, userId,
19275                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19276        if (filter.countActions() == 0) {
19277            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19278            return;
19279        }
19280        synchronized (mPackages) {
19281            if (mContext.checkCallingOrSelfPermission(
19282                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19283                    != PackageManager.PERMISSION_GRANTED) {
19284                if (getUidTargetSdkVersionLockedLPr(callingUid)
19285                        < Build.VERSION_CODES.FROYO) {
19286                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19287                            + callingUid);
19288                    return;
19289                }
19290                mContext.enforceCallingOrSelfPermission(
19291                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19292            }
19293
19294            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19295            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19296                    + userId + ":");
19297            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19298            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19299            scheduleWritePackageRestrictionsLocked(userId);
19300            postPreferredActivityChangedBroadcast(userId);
19301        }
19302    }
19303
19304    private void postPreferredActivityChangedBroadcast(int userId) {
19305        mHandler.post(() -> {
19306            final IActivityManager am = ActivityManager.getService();
19307            if (am == null) {
19308                return;
19309            }
19310
19311            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19312            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19313            try {
19314                am.broadcastIntent(null, intent, null, null,
19315                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19316                        null, false, false, userId);
19317            } catch (RemoteException e) {
19318            }
19319        });
19320    }
19321
19322    @Override
19323    public void replacePreferredActivity(IntentFilter filter, int match,
19324            ComponentName[] set, ComponentName activity, int userId) {
19325        if (filter.countActions() != 1) {
19326            throw new IllegalArgumentException(
19327                    "replacePreferredActivity expects filter to have only 1 action.");
19328        }
19329        if (filter.countDataAuthorities() != 0
19330                || filter.countDataPaths() != 0
19331                || filter.countDataSchemes() > 1
19332                || filter.countDataTypes() != 0) {
19333            throw new IllegalArgumentException(
19334                    "replacePreferredActivity expects filter to have no data authorities, " +
19335                    "paths, or types; and at most one scheme.");
19336        }
19337
19338        final int callingUid = Binder.getCallingUid();
19339        enforceCrossUserPermission(callingUid, userId,
19340                true /* requireFullPermission */, false /* checkShell */,
19341                "replace preferred activity");
19342        synchronized (mPackages) {
19343            if (mContext.checkCallingOrSelfPermission(
19344                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19345                    != PackageManager.PERMISSION_GRANTED) {
19346                if (getUidTargetSdkVersionLockedLPr(callingUid)
19347                        < Build.VERSION_CODES.FROYO) {
19348                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19349                            + Binder.getCallingUid());
19350                    return;
19351                }
19352                mContext.enforceCallingOrSelfPermission(
19353                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19354            }
19355
19356            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19357            if (pir != null) {
19358                // Get all of the existing entries that exactly match this filter.
19359                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19360                if (existing != null && existing.size() == 1) {
19361                    PreferredActivity cur = existing.get(0);
19362                    if (DEBUG_PREFERRED) {
19363                        Slog.i(TAG, "Checking replace of preferred:");
19364                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19365                        if (!cur.mPref.mAlways) {
19366                            Slog.i(TAG, "  -- CUR; not mAlways!");
19367                        } else {
19368                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19369                            Slog.i(TAG, "  -- CUR: mSet="
19370                                    + Arrays.toString(cur.mPref.mSetComponents));
19371                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19372                            Slog.i(TAG, "  -- NEW: mMatch="
19373                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19374                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19375                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19376                        }
19377                    }
19378                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19379                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19380                            && cur.mPref.sameSet(set)) {
19381                        // Setting the preferred activity to what it happens to be already
19382                        if (DEBUG_PREFERRED) {
19383                            Slog.i(TAG, "Replacing with same preferred activity "
19384                                    + cur.mPref.mShortComponent + " for user "
19385                                    + userId + ":");
19386                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19387                        }
19388                        return;
19389                    }
19390                }
19391
19392                if (existing != null) {
19393                    if (DEBUG_PREFERRED) {
19394                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19395                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19396                    }
19397                    for (int i = 0; i < existing.size(); i++) {
19398                        PreferredActivity pa = existing.get(i);
19399                        if (DEBUG_PREFERRED) {
19400                            Slog.i(TAG, "Removing existing preferred activity "
19401                                    + pa.mPref.mComponent + ":");
19402                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19403                        }
19404                        pir.removeFilter(pa);
19405                    }
19406                }
19407            }
19408            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19409                    "Replacing preferred");
19410        }
19411    }
19412
19413    @Override
19414    public void clearPackagePreferredActivities(String packageName) {
19415        final int uid = Binder.getCallingUid();
19416        // writer
19417        synchronized (mPackages) {
19418            PackageParser.Package pkg = mPackages.get(packageName);
19419            if (pkg == null || pkg.applicationInfo.uid != uid) {
19420                if (mContext.checkCallingOrSelfPermission(
19421                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19422                        != PackageManager.PERMISSION_GRANTED) {
19423                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
19424                            < Build.VERSION_CODES.FROYO) {
19425                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19426                                + Binder.getCallingUid());
19427                        return;
19428                    }
19429                    mContext.enforceCallingOrSelfPermission(
19430                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19431                }
19432            }
19433
19434            int user = UserHandle.getCallingUserId();
19435            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19436                scheduleWritePackageRestrictionsLocked(user);
19437            }
19438        }
19439    }
19440
19441    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19442    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19443        ArrayList<PreferredActivity> removed = null;
19444        boolean changed = false;
19445        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19446            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19447            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19448            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19449                continue;
19450            }
19451            Iterator<PreferredActivity> it = pir.filterIterator();
19452            while (it.hasNext()) {
19453                PreferredActivity pa = it.next();
19454                // Mark entry for removal only if it matches the package name
19455                // and the entry is of type "always".
19456                if (packageName == null ||
19457                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19458                                && pa.mPref.mAlways)) {
19459                    if (removed == null) {
19460                        removed = new ArrayList<PreferredActivity>();
19461                    }
19462                    removed.add(pa);
19463                }
19464            }
19465            if (removed != null) {
19466                for (int j=0; j<removed.size(); j++) {
19467                    PreferredActivity pa = removed.get(j);
19468                    pir.removeFilter(pa);
19469                }
19470                changed = true;
19471            }
19472        }
19473        if (changed) {
19474            postPreferredActivityChangedBroadcast(userId);
19475        }
19476        return changed;
19477    }
19478
19479    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19480    private void clearIntentFilterVerificationsLPw(int userId) {
19481        final int packageCount = mPackages.size();
19482        for (int i = 0; i < packageCount; i++) {
19483            PackageParser.Package pkg = mPackages.valueAt(i);
19484            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19485        }
19486    }
19487
19488    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19489    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19490        if (userId == UserHandle.USER_ALL) {
19491            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19492                    sUserManager.getUserIds())) {
19493                for (int oneUserId : sUserManager.getUserIds()) {
19494                    scheduleWritePackageRestrictionsLocked(oneUserId);
19495                }
19496            }
19497        } else {
19498            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19499                scheduleWritePackageRestrictionsLocked(userId);
19500            }
19501        }
19502    }
19503
19504    /** Clears state for all users, and touches intent filter verification policy */
19505    void clearDefaultBrowserIfNeeded(String packageName) {
19506        for (int oneUserId : sUserManager.getUserIds()) {
19507            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19508        }
19509    }
19510
19511    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19512        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19513        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19514            if (packageName.equals(defaultBrowserPackageName)) {
19515                setDefaultBrowserPackageName(null, userId);
19516            }
19517        }
19518    }
19519
19520    @Override
19521    public void resetApplicationPreferences(int userId) {
19522        mContext.enforceCallingOrSelfPermission(
19523                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19524        final long identity = Binder.clearCallingIdentity();
19525        // writer
19526        try {
19527            synchronized (mPackages) {
19528                clearPackagePreferredActivitiesLPw(null, userId);
19529                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19530                // TODO: We have to reset the default SMS and Phone. This requires
19531                // significant refactoring to keep all default apps in the package
19532                // manager (cleaner but more work) or have the services provide
19533                // callbacks to the package manager to request a default app reset.
19534                applyFactoryDefaultBrowserLPw(userId);
19535                clearIntentFilterVerificationsLPw(userId);
19536                primeDomainVerificationsLPw(userId);
19537                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19538                scheduleWritePackageRestrictionsLocked(userId);
19539            }
19540            resetNetworkPolicies(userId);
19541        } finally {
19542            Binder.restoreCallingIdentity(identity);
19543        }
19544    }
19545
19546    @Override
19547    public int getPreferredActivities(List<IntentFilter> outFilters,
19548            List<ComponentName> outActivities, String packageName) {
19549
19550        int num = 0;
19551        final int userId = UserHandle.getCallingUserId();
19552        // reader
19553        synchronized (mPackages) {
19554            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19555            if (pir != null) {
19556                final Iterator<PreferredActivity> it = pir.filterIterator();
19557                while (it.hasNext()) {
19558                    final PreferredActivity pa = it.next();
19559                    if (packageName == null
19560                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19561                                    && pa.mPref.mAlways)) {
19562                        if (outFilters != null) {
19563                            outFilters.add(new IntentFilter(pa));
19564                        }
19565                        if (outActivities != null) {
19566                            outActivities.add(pa.mPref.mComponent);
19567                        }
19568                    }
19569                }
19570            }
19571        }
19572
19573        return num;
19574    }
19575
19576    @Override
19577    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19578            int userId) {
19579        int callingUid = Binder.getCallingUid();
19580        if (callingUid != Process.SYSTEM_UID) {
19581            throw new SecurityException(
19582                    "addPersistentPreferredActivity can only be run by the system");
19583        }
19584        if (filter.countActions() == 0) {
19585            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19586            return;
19587        }
19588        synchronized (mPackages) {
19589            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19590                    ":");
19591            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19592            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19593                    new PersistentPreferredActivity(filter, activity));
19594            scheduleWritePackageRestrictionsLocked(userId);
19595            postPreferredActivityChangedBroadcast(userId);
19596        }
19597    }
19598
19599    @Override
19600    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19601        int callingUid = Binder.getCallingUid();
19602        if (callingUid != Process.SYSTEM_UID) {
19603            throw new SecurityException(
19604                    "clearPackagePersistentPreferredActivities can only be run by the system");
19605        }
19606        ArrayList<PersistentPreferredActivity> removed = null;
19607        boolean changed = false;
19608        synchronized (mPackages) {
19609            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19610                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19611                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19612                        .valueAt(i);
19613                if (userId != thisUserId) {
19614                    continue;
19615                }
19616                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19617                while (it.hasNext()) {
19618                    PersistentPreferredActivity ppa = it.next();
19619                    // Mark entry for removal only if it matches the package name.
19620                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19621                        if (removed == null) {
19622                            removed = new ArrayList<PersistentPreferredActivity>();
19623                        }
19624                        removed.add(ppa);
19625                    }
19626                }
19627                if (removed != null) {
19628                    for (int j=0; j<removed.size(); j++) {
19629                        PersistentPreferredActivity ppa = removed.get(j);
19630                        ppir.removeFilter(ppa);
19631                    }
19632                    changed = true;
19633                }
19634            }
19635
19636            if (changed) {
19637                scheduleWritePackageRestrictionsLocked(userId);
19638                postPreferredActivityChangedBroadcast(userId);
19639            }
19640        }
19641    }
19642
19643    /**
19644     * Common machinery for picking apart a restored XML blob and passing
19645     * it to a caller-supplied functor to be applied to the running system.
19646     */
19647    private void restoreFromXml(XmlPullParser parser, int userId,
19648            String expectedStartTag, BlobXmlRestorer functor)
19649            throws IOException, XmlPullParserException {
19650        int type;
19651        while ((type = parser.next()) != XmlPullParser.START_TAG
19652                && type != XmlPullParser.END_DOCUMENT) {
19653        }
19654        if (type != XmlPullParser.START_TAG) {
19655            // oops didn't find a start tag?!
19656            if (DEBUG_BACKUP) {
19657                Slog.e(TAG, "Didn't find start tag during restore");
19658            }
19659            return;
19660        }
19661Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19662        // this is supposed to be TAG_PREFERRED_BACKUP
19663        if (!expectedStartTag.equals(parser.getName())) {
19664            if (DEBUG_BACKUP) {
19665                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19666            }
19667            return;
19668        }
19669
19670        // skip interfering stuff, then we're aligned with the backing implementation
19671        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19672Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19673        functor.apply(parser, userId);
19674    }
19675
19676    private interface BlobXmlRestorer {
19677        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19678    }
19679
19680    /**
19681     * Non-Binder method, support for the backup/restore mechanism: write the
19682     * full set of preferred activities in its canonical XML format.  Returns the
19683     * XML output as a byte array, or null if there is none.
19684     */
19685    @Override
19686    public byte[] getPreferredActivityBackup(int userId) {
19687        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19688            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19689        }
19690
19691        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19692        try {
19693            final XmlSerializer serializer = new FastXmlSerializer();
19694            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19695            serializer.startDocument(null, true);
19696            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19697
19698            synchronized (mPackages) {
19699                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19700            }
19701
19702            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19703            serializer.endDocument();
19704            serializer.flush();
19705        } catch (Exception e) {
19706            if (DEBUG_BACKUP) {
19707                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19708            }
19709            return null;
19710        }
19711
19712        return dataStream.toByteArray();
19713    }
19714
19715    @Override
19716    public void restorePreferredActivities(byte[] backup, int userId) {
19717        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19718            throw new SecurityException("Only the system may call restorePreferredActivities()");
19719        }
19720
19721        try {
19722            final XmlPullParser parser = Xml.newPullParser();
19723            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19724            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19725                    new BlobXmlRestorer() {
19726                        @Override
19727                        public void apply(XmlPullParser parser, int userId)
19728                                throws XmlPullParserException, IOException {
19729                            synchronized (mPackages) {
19730                                mSettings.readPreferredActivitiesLPw(parser, userId);
19731                            }
19732                        }
19733                    } );
19734        } catch (Exception e) {
19735            if (DEBUG_BACKUP) {
19736                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19737            }
19738        }
19739    }
19740
19741    /**
19742     * Non-Binder method, support for the backup/restore mechanism: write the
19743     * default browser (etc) settings in its canonical XML format.  Returns the default
19744     * browser XML representation as a byte array, or null if there is none.
19745     */
19746    @Override
19747    public byte[] getDefaultAppsBackup(int userId) {
19748        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19749            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19750        }
19751
19752        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19753        try {
19754            final XmlSerializer serializer = new FastXmlSerializer();
19755            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19756            serializer.startDocument(null, true);
19757            serializer.startTag(null, TAG_DEFAULT_APPS);
19758
19759            synchronized (mPackages) {
19760                mSettings.writeDefaultAppsLPr(serializer, userId);
19761            }
19762
19763            serializer.endTag(null, TAG_DEFAULT_APPS);
19764            serializer.endDocument();
19765            serializer.flush();
19766        } catch (Exception e) {
19767            if (DEBUG_BACKUP) {
19768                Slog.e(TAG, "Unable to write default apps for backup", e);
19769            }
19770            return null;
19771        }
19772
19773        return dataStream.toByteArray();
19774    }
19775
19776    @Override
19777    public void restoreDefaultApps(byte[] backup, int userId) {
19778        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19779            throw new SecurityException("Only the system may call restoreDefaultApps()");
19780        }
19781
19782        try {
19783            final XmlPullParser parser = Xml.newPullParser();
19784            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19785            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19786                    new BlobXmlRestorer() {
19787                        @Override
19788                        public void apply(XmlPullParser parser, int userId)
19789                                throws XmlPullParserException, IOException {
19790                            synchronized (mPackages) {
19791                                mSettings.readDefaultAppsLPw(parser, userId);
19792                            }
19793                        }
19794                    } );
19795        } catch (Exception e) {
19796            if (DEBUG_BACKUP) {
19797                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19798            }
19799        }
19800    }
19801
19802    @Override
19803    public byte[] getIntentFilterVerificationBackup(int userId) {
19804        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19805            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19806        }
19807
19808        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19809        try {
19810            final XmlSerializer serializer = new FastXmlSerializer();
19811            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19812            serializer.startDocument(null, true);
19813            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19814
19815            synchronized (mPackages) {
19816                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19817            }
19818
19819            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19820            serializer.endDocument();
19821            serializer.flush();
19822        } catch (Exception e) {
19823            if (DEBUG_BACKUP) {
19824                Slog.e(TAG, "Unable to write default apps for backup", e);
19825            }
19826            return null;
19827        }
19828
19829        return dataStream.toByteArray();
19830    }
19831
19832    @Override
19833    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19834        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19835            throw new SecurityException("Only the system may call restorePreferredActivities()");
19836        }
19837
19838        try {
19839            final XmlPullParser parser = Xml.newPullParser();
19840            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19841            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19842                    new BlobXmlRestorer() {
19843                        @Override
19844                        public void apply(XmlPullParser parser, int userId)
19845                                throws XmlPullParserException, IOException {
19846                            synchronized (mPackages) {
19847                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19848                                mSettings.writeLPr();
19849                            }
19850                        }
19851                    } );
19852        } catch (Exception e) {
19853            if (DEBUG_BACKUP) {
19854                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19855            }
19856        }
19857    }
19858
19859    @Override
19860    public byte[] getPermissionGrantBackup(int userId) {
19861        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19862            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19863        }
19864
19865        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19866        try {
19867            final XmlSerializer serializer = new FastXmlSerializer();
19868            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19869            serializer.startDocument(null, true);
19870            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19871
19872            synchronized (mPackages) {
19873                serializeRuntimePermissionGrantsLPr(serializer, userId);
19874            }
19875
19876            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19877            serializer.endDocument();
19878            serializer.flush();
19879        } catch (Exception e) {
19880            if (DEBUG_BACKUP) {
19881                Slog.e(TAG, "Unable to write default apps for backup", e);
19882            }
19883            return null;
19884        }
19885
19886        return dataStream.toByteArray();
19887    }
19888
19889    @Override
19890    public void restorePermissionGrants(byte[] backup, int userId) {
19891        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19892            throw new SecurityException("Only the system may call restorePermissionGrants()");
19893        }
19894
19895        try {
19896            final XmlPullParser parser = Xml.newPullParser();
19897            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19898            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19899                    new BlobXmlRestorer() {
19900                        @Override
19901                        public void apply(XmlPullParser parser, int userId)
19902                                throws XmlPullParserException, IOException {
19903                            synchronized (mPackages) {
19904                                processRestoredPermissionGrantsLPr(parser, userId);
19905                            }
19906                        }
19907                    } );
19908        } catch (Exception e) {
19909            if (DEBUG_BACKUP) {
19910                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19911            }
19912        }
19913    }
19914
19915    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19916            throws IOException {
19917        serializer.startTag(null, TAG_ALL_GRANTS);
19918
19919        final int N = mSettings.mPackages.size();
19920        for (int i = 0; i < N; i++) {
19921            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19922            boolean pkgGrantsKnown = false;
19923
19924            PermissionsState packagePerms = ps.getPermissionsState();
19925
19926            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19927                final int grantFlags = state.getFlags();
19928                // only look at grants that are not system/policy fixed
19929                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19930                    final boolean isGranted = state.isGranted();
19931                    // And only back up the user-twiddled state bits
19932                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19933                        final String packageName = mSettings.mPackages.keyAt(i);
19934                        if (!pkgGrantsKnown) {
19935                            serializer.startTag(null, TAG_GRANT);
19936                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19937                            pkgGrantsKnown = true;
19938                        }
19939
19940                        final boolean userSet =
19941                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19942                        final boolean userFixed =
19943                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19944                        final boolean revoke =
19945                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19946
19947                        serializer.startTag(null, TAG_PERMISSION);
19948                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19949                        if (isGranted) {
19950                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19951                        }
19952                        if (userSet) {
19953                            serializer.attribute(null, ATTR_USER_SET, "true");
19954                        }
19955                        if (userFixed) {
19956                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19957                        }
19958                        if (revoke) {
19959                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19960                        }
19961                        serializer.endTag(null, TAG_PERMISSION);
19962                    }
19963                }
19964            }
19965
19966            if (pkgGrantsKnown) {
19967                serializer.endTag(null, TAG_GRANT);
19968            }
19969        }
19970
19971        serializer.endTag(null, TAG_ALL_GRANTS);
19972    }
19973
19974    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19975            throws XmlPullParserException, IOException {
19976        String pkgName = null;
19977        int outerDepth = parser.getDepth();
19978        int type;
19979        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19980                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19981            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19982                continue;
19983            }
19984
19985            final String tagName = parser.getName();
19986            if (tagName.equals(TAG_GRANT)) {
19987                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19988                if (DEBUG_BACKUP) {
19989                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19990                }
19991            } else if (tagName.equals(TAG_PERMISSION)) {
19992
19993                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19994                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19995
19996                int newFlagSet = 0;
19997                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19998                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19999                }
20000                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20001                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20002                }
20003                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20004                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20005                }
20006                if (DEBUG_BACKUP) {
20007                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20008                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20009                }
20010                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20011                if (ps != null) {
20012                    // Already installed so we apply the grant immediately
20013                    if (DEBUG_BACKUP) {
20014                        Slog.v(TAG, "        + already installed; applying");
20015                    }
20016                    PermissionsState perms = ps.getPermissionsState();
20017                    BasePermission bp = mSettings.mPermissions.get(permName);
20018                    if (bp != null) {
20019                        if (isGranted) {
20020                            perms.grantRuntimePermission(bp, userId);
20021                        }
20022                        if (newFlagSet != 0) {
20023                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20024                        }
20025                    }
20026                } else {
20027                    // Need to wait for post-restore install to apply the grant
20028                    if (DEBUG_BACKUP) {
20029                        Slog.v(TAG, "        - not yet installed; saving for later");
20030                    }
20031                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20032                            isGranted, newFlagSet, userId);
20033                }
20034            } else {
20035                PackageManagerService.reportSettingsProblem(Log.WARN,
20036                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20037                XmlUtils.skipCurrentTag(parser);
20038            }
20039        }
20040
20041        scheduleWriteSettingsLocked();
20042        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20043    }
20044
20045    @Override
20046    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20047            int sourceUserId, int targetUserId, int flags) {
20048        mContext.enforceCallingOrSelfPermission(
20049                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20050        int callingUid = Binder.getCallingUid();
20051        enforceOwnerRights(ownerPackage, callingUid);
20052        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20053        if (intentFilter.countActions() == 0) {
20054            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20055            return;
20056        }
20057        synchronized (mPackages) {
20058            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20059                    ownerPackage, targetUserId, flags);
20060            CrossProfileIntentResolver resolver =
20061                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20062            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20063            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20064            if (existing != null) {
20065                int size = existing.size();
20066                for (int i = 0; i < size; i++) {
20067                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20068                        return;
20069                    }
20070                }
20071            }
20072            resolver.addFilter(newFilter);
20073            scheduleWritePackageRestrictionsLocked(sourceUserId);
20074        }
20075    }
20076
20077    @Override
20078    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20079        mContext.enforceCallingOrSelfPermission(
20080                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20081        int callingUid = Binder.getCallingUid();
20082        enforceOwnerRights(ownerPackage, callingUid);
20083        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20084        synchronized (mPackages) {
20085            CrossProfileIntentResolver resolver =
20086                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20087            ArraySet<CrossProfileIntentFilter> set =
20088                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20089            for (CrossProfileIntentFilter filter : set) {
20090                if (filter.getOwnerPackage().equals(ownerPackage)) {
20091                    resolver.removeFilter(filter);
20092                }
20093            }
20094            scheduleWritePackageRestrictionsLocked(sourceUserId);
20095        }
20096    }
20097
20098    // Enforcing that callingUid is owning pkg on userId
20099    private void enforceOwnerRights(String pkg, int callingUid) {
20100        // The system owns everything.
20101        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20102            return;
20103        }
20104        int callingUserId = UserHandle.getUserId(callingUid);
20105        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20106        if (pi == null) {
20107            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20108                    + callingUserId);
20109        }
20110        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20111            throw new SecurityException("Calling uid " + callingUid
20112                    + " does not own package " + pkg);
20113        }
20114    }
20115
20116    @Override
20117    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20118        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20119    }
20120
20121    /**
20122     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20123     * then reports the most likely home activity or null if there are more than one.
20124     */
20125    public ComponentName getDefaultHomeActivity(int userId) {
20126        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20127        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20128        if (cn != null) {
20129            return cn;
20130        }
20131
20132        // Find the launcher with the highest priority and return that component if there are no
20133        // other home activity with the same priority.
20134        int lastPriority = Integer.MIN_VALUE;
20135        ComponentName lastComponent = null;
20136        final int size = allHomeCandidates.size();
20137        for (int i = 0; i < size; i++) {
20138            final ResolveInfo ri = allHomeCandidates.get(i);
20139            if (ri.priority > lastPriority) {
20140                lastComponent = ri.activityInfo.getComponentName();
20141                lastPriority = ri.priority;
20142            } else if (ri.priority == lastPriority) {
20143                // Two components found with same priority.
20144                lastComponent = null;
20145            }
20146        }
20147        return lastComponent;
20148    }
20149
20150    private Intent getHomeIntent() {
20151        Intent intent = new Intent(Intent.ACTION_MAIN);
20152        intent.addCategory(Intent.CATEGORY_HOME);
20153        intent.addCategory(Intent.CATEGORY_DEFAULT);
20154        return intent;
20155    }
20156
20157    private IntentFilter getHomeFilter() {
20158        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20159        filter.addCategory(Intent.CATEGORY_HOME);
20160        filter.addCategory(Intent.CATEGORY_DEFAULT);
20161        return filter;
20162    }
20163
20164    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20165            int userId) {
20166        Intent intent  = getHomeIntent();
20167        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20168                PackageManager.GET_META_DATA, userId);
20169        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20170                true, false, false, userId);
20171
20172        allHomeCandidates.clear();
20173        if (list != null) {
20174            for (ResolveInfo ri : list) {
20175                allHomeCandidates.add(ri);
20176            }
20177        }
20178        return (preferred == null || preferred.activityInfo == null)
20179                ? null
20180                : new ComponentName(preferred.activityInfo.packageName,
20181                        preferred.activityInfo.name);
20182    }
20183
20184    @Override
20185    public void setHomeActivity(ComponentName comp, int userId) {
20186        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20187        getHomeActivitiesAsUser(homeActivities, userId);
20188
20189        boolean found = false;
20190
20191        final int size = homeActivities.size();
20192        final ComponentName[] set = new ComponentName[size];
20193        for (int i = 0; i < size; i++) {
20194            final ResolveInfo candidate = homeActivities.get(i);
20195            final ActivityInfo info = candidate.activityInfo;
20196            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20197            set[i] = activityName;
20198            if (!found && activityName.equals(comp)) {
20199                found = true;
20200            }
20201        }
20202        if (!found) {
20203            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20204                    + userId);
20205        }
20206        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20207                set, comp, userId);
20208    }
20209
20210    private @Nullable String getSetupWizardPackageName() {
20211        final Intent intent = new Intent(Intent.ACTION_MAIN);
20212        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20213
20214        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20215                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20216                        | MATCH_DISABLED_COMPONENTS,
20217                UserHandle.myUserId());
20218        if (matches.size() == 1) {
20219            return matches.get(0).getComponentInfo().packageName;
20220        } else {
20221            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20222                    + ": matches=" + matches);
20223            return null;
20224        }
20225    }
20226
20227    private @Nullable String getStorageManagerPackageName() {
20228        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20229
20230        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20231                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20232                        | MATCH_DISABLED_COMPONENTS,
20233                UserHandle.myUserId());
20234        if (matches.size() == 1) {
20235            return matches.get(0).getComponentInfo().packageName;
20236        } else {
20237            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20238                    + matches.size() + ": matches=" + matches);
20239            return null;
20240        }
20241    }
20242
20243    @Override
20244    public void setApplicationEnabledSetting(String appPackageName,
20245            int newState, int flags, int userId, String callingPackage) {
20246        if (!sUserManager.exists(userId)) return;
20247        if (callingPackage == null) {
20248            callingPackage = Integer.toString(Binder.getCallingUid());
20249        }
20250        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20251    }
20252
20253    @Override
20254    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20255        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20256        synchronized (mPackages) {
20257            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20258            if (pkgSetting != null) {
20259                pkgSetting.setUpdateAvailable(updateAvailable);
20260            }
20261        }
20262    }
20263
20264    @Override
20265    public void setComponentEnabledSetting(ComponentName componentName,
20266            int newState, int flags, int userId) {
20267        if (!sUserManager.exists(userId)) return;
20268        setEnabledSetting(componentName.getPackageName(),
20269                componentName.getClassName(), newState, flags, userId, null);
20270    }
20271
20272    private void setEnabledSetting(final String packageName, String className, int newState,
20273            final int flags, int userId, String callingPackage) {
20274        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20275              || newState == COMPONENT_ENABLED_STATE_ENABLED
20276              || newState == COMPONENT_ENABLED_STATE_DISABLED
20277              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20278              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20279            throw new IllegalArgumentException("Invalid new component state: "
20280                    + newState);
20281        }
20282        PackageSetting pkgSetting;
20283        final int uid = Binder.getCallingUid();
20284        final int permission;
20285        if (uid == Process.SYSTEM_UID) {
20286            permission = PackageManager.PERMISSION_GRANTED;
20287        } else {
20288            permission = mContext.checkCallingOrSelfPermission(
20289                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20290        }
20291        enforceCrossUserPermission(uid, userId,
20292                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20293        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20294        boolean sendNow = false;
20295        boolean isApp = (className == null);
20296        String componentName = isApp ? packageName : className;
20297        int packageUid = -1;
20298        ArrayList<String> components;
20299
20300        // writer
20301        synchronized (mPackages) {
20302            pkgSetting = mSettings.mPackages.get(packageName);
20303            if (pkgSetting == null) {
20304                if (className == null) {
20305                    throw new IllegalArgumentException("Unknown package: " + packageName);
20306                }
20307                throw new IllegalArgumentException(
20308                        "Unknown component: " + packageName + "/" + className);
20309            }
20310        }
20311
20312        // Limit who can change which apps
20313        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
20314            // Don't allow apps that don't have permission to modify other apps
20315            if (!allowedByPermission) {
20316                throw new SecurityException(
20317                        "Permission Denial: attempt to change component state from pid="
20318                        + Binder.getCallingPid()
20319                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
20320            }
20321            // Don't allow changing protected packages.
20322            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20323                throw new SecurityException("Cannot disable a protected package: " + packageName);
20324            }
20325        }
20326
20327        synchronized (mPackages) {
20328            if (uid == Process.SHELL_UID
20329                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20330                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20331                // unless it is a test package.
20332                int oldState = pkgSetting.getEnabled(userId);
20333                if (className == null
20334                    &&
20335                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20336                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20337                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20338                    &&
20339                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20340                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
20341                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20342                    // ok
20343                } else {
20344                    throw new SecurityException(
20345                            "Shell cannot change component state for " + packageName + "/"
20346                            + className + " to " + newState);
20347                }
20348            }
20349            if (className == null) {
20350                // We're dealing with an application/package level state change
20351                if (pkgSetting.getEnabled(userId) == newState) {
20352                    // Nothing to do
20353                    return;
20354                }
20355                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20356                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20357                    // Don't care about who enables an app.
20358                    callingPackage = null;
20359                }
20360                pkgSetting.setEnabled(newState, userId, callingPackage);
20361                // pkgSetting.pkg.mSetEnabled = newState;
20362            } else {
20363                // We're dealing with a component level state change
20364                // First, verify that this is a valid class name.
20365                PackageParser.Package pkg = pkgSetting.pkg;
20366                if (pkg == null || !pkg.hasComponentClassName(className)) {
20367                    if (pkg != null &&
20368                            pkg.applicationInfo.targetSdkVersion >=
20369                                    Build.VERSION_CODES.JELLY_BEAN) {
20370                        throw new IllegalArgumentException("Component class " + className
20371                                + " does not exist in " + packageName);
20372                    } else {
20373                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20374                                + className + " does not exist in " + packageName);
20375                    }
20376                }
20377                switch (newState) {
20378                case COMPONENT_ENABLED_STATE_ENABLED:
20379                    if (!pkgSetting.enableComponentLPw(className, userId)) {
20380                        return;
20381                    }
20382                    break;
20383                case COMPONENT_ENABLED_STATE_DISABLED:
20384                    if (!pkgSetting.disableComponentLPw(className, userId)) {
20385                        return;
20386                    }
20387                    break;
20388                case COMPONENT_ENABLED_STATE_DEFAULT:
20389                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
20390                        return;
20391                    }
20392                    break;
20393                default:
20394                    Slog.e(TAG, "Invalid new component state: " + newState);
20395                    return;
20396                }
20397            }
20398            scheduleWritePackageRestrictionsLocked(userId);
20399            updateSequenceNumberLP(packageName, new int[] { userId });
20400            final long callingId = Binder.clearCallingIdentity();
20401            try {
20402                updateInstantAppInstallerLocked(packageName);
20403            } finally {
20404                Binder.restoreCallingIdentity(callingId);
20405            }
20406            components = mPendingBroadcasts.get(userId, packageName);
20407            final boolean newPackage = components == null;
20408            if (newPackage) {
20409                components = new ArrayList<String>();
20410            }
20411            if (!components.contains(componentName)) {
20412                components.add(componentName);
20413            }
20414            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20415                sendNow = true;
20416                // Purge entry from pending broadcast list if another one exists already
20417                // since we are sending one right away.
20418                mPendingBroadcasts.remove(userId, packageName);
20419            } else {
20420                if (newPackage) {
20421                    mPendingBroadcasts.put(userId, packageName, components);
20422                }
20423                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20424                    // Schedule a message
20425                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20426                }
20427            }
20428        }
20429
20430        long callingId = Binder.clearCallingIdentity();
20431        try {
20432            if (sendNow) {
20433                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20434                sendPackageChangedBroadcast(packageName,
20435                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20436            }
20437        } finally {
20438            Binder.restoreCallingIdentity(callingId);
20439        }
20440    }
20441
20442    @Override
20443    public void flushPackageRestrictionsAsUser(int userId) {
20444        if (!sUserManager.exists(userId)) {
20445            return;
20446        }
20447        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20448                false /* checkShell */, "flushPackageRestrictions");
20449        synchronized (mPackages) {
20450            mSettings.writePackageRestrictionsLPr(userId);
20451            mDirtyUsers.remove(userId);
20452            if (mDirtyUsers.isEmpty()) {
20453                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20454            }
20455        }
20456    }
20457
20458    private void sendPackageChangedBroadcast(String packageName,
20459            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20460        if (DEBUG_INSTALL)
20461            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20462                    + componentNames);
20463        Bundle extras = new Bundle(4);
20464        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20465        String nameList[] = new String[componentNames.size()];
20466        componentNames.toArray(nameList);
20467        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20468        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20469        extras.putInt(Intent.EXTRA_UID, packageUid);
20470        // If this is not reporting a change of the overall package, then only send it
20471        // to registered receivers.  We don't want to launch a swath of apps for every
20472        // little component state change.
20473        final int flags = !componentNames.contains(packageName)
20474                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20475        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20476                new int[] {UserHandle.getUserId(packageUid)});
20477    }
20478
20479    @Override
20480    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20481        if (!sUserManager.exists(userId)) return;
20482        final int uid = Binder.getCallingUid();
20483        final int permission = mContext.checkCallingOrSelfPermission(
20484                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20485        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20486        enforceCrossUserPermission(uid, userId,
20487                true /* requireFullPermission */, true /* checkShell */, "stop package");
20488        // writer
20489        synchronized (mPackages) {
20490            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20491                    allowedByPermission, uid, userId)) {
20492                scheduleWritePackageRestrictionsLocked(userId);
20493            }
20494        }
20495    }
20496
20497    @Override
20498    public String getInstallerPackageName(String packageName) {
20499        // reader
20500        synchronized (mPackages) {
20501            return mSettings.getInstallerPackageNameLPr(packageName);
20502        }
20503    }
20504
20505    public boolean isOrphaned(String packageName) {
20506        // reader
20507        synchronized (mPackages) {
20508            return mSettings.isOrphaned(packageName);
20509        }
20510    }
20511
20512    @Override
20513    public int getApplicationEnabledSetting(String packageName, int userId) {
20514        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20515        int uid = Binder.getCallingUid();
20516        enforceCrossUserPermission(uid, userId,
20517                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20518        // reader
20519        synchronized (mPackages) {
20520            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20521        }
20522    }
20523
20524    @Override
20525    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20526        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20527        int uid = Binder.getCallingUid();
20528        enforceCrossUserPermission(uid, userId,
20529                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20530        // reader
20531        synchronized (mPackages) {
20532            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20533        }
20534    }
20535
20536    @Override
20537    public void enterSafeMode() {
20538        enforceSystemOrRoot("Only the system can request entering safe mode");
20539
20540        if (!mSystemReady) {
20541            mSafeMode = true;
20542        }
20543    }
20544
20545    @Override
20546    public void systemReady() {
20547        mSystemReady = true;
20548        final ContentResolver resolver = mContext.getContentResolver();
20549        ContentObserver co = new ContentObserver(mHandler) {
20550            @Override
20551            public void onChange(boolean selfChange) {
20552                mEphemeralAppsDisabled =
20553                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20554                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20555            }
20556        };
20557        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20558                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20559                false, co, UserHandle.USER_SYSTEM);
20560        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20561                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20562        co.onChange(true);
20563
20564        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20565        // disabled after already being started.
20566        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20567                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20568
20569        // Read the compatibilty setting when the system is ready.
20570        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20571                mContext.getContentResolver(),
20572                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20573        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20574        if (DEBUG_SETTINGS) {
20575            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20576        }
20577
20578        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20579
20580        synchronized (mPackages) {
20581            // Verify that all of the preferred activity components actually
20582            // exist.  It is possible for applications to be updated and at
20583            // that point remove a previously declared activity component that
20584            // had been set as a preferred activity.  We try to clean this up
20585            // the next time we encounter that preferred activity, but it is
20586            // possible for the user flow to never be able to return to that
20587            // situation so here we do a sanity check to make sure we haven't
20588            // left any junk around.
20589            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20590            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20591                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20592                removed.clear();
20593                for (PreferredActivity pa : pir.filterSet()) {
20594                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20595                        removed.add(pa);
20596                    }
20597                }
20598                if (removed.size() > 0) {
20599                    for (int r=0; r<removed.size(); r++) {
20600                        PreferredActivity pa = removed.get(r);
20601                        Slog.w(TAG, "Removing dangling preferred activity: "
20602                                + pa.mPref.mComponent);
20603                        pir.removeFilter(pa);
20604                    }
20605                    mSettings.writePackageRestrictionsLPr(
20606                            mSettings.mPreferredActivities.keyAt(i));
20607                }
20608            }
20609
20610            for (int userId : UserManagerService.getInstance().getUserIds()) {
20611                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20612                    grantPermissionsUserIds = ArrayUtils.appendInt(
20613                            grantPermissionsUserIds, userId);
20614                }
20615            }
20616        }
20617        sUserManager.systemReady();
20618
20619        // If we upgraded grant all default permissions before kicking off.
20620        for (int userId : grantPermissionsUserIds) {
20621            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20622        }
20623
20624        // If we did not grant default permissions, we preload from this the
20625        // default permission exceptions lazily to ensure we don't hit the
20626        // disk on a new user creation.
20627        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20628            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20629        }
20630
20631        // Kick off any messages waiting for system ready
20632        if (mPostSystemReadyMessages != null) {
20633            for (Message msg : mPostSystemReadyMessages) {
20634                msg.sendToTarget();
20635            }
20636            mPostSystemReadyMessages = null;
20637        }
20638
20639        // Watch for external volumes that come and go over time
20640        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20641        storage.registerListener(mStorageListener);
20642
20643        mInstallerService.systemReady();
20644        mPackageDexOptimizer.systemReady();
20645
20646        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20647                StorageManagerInternal.class);
20648        StorageManagerInternal.addExternalStoragePolicy(
20649                new StorageManagerInternal.ExternalStorageMountPolicy() {
20650            @Override
20651            public int getMountMode(int uid, String packageName) {
20652                if (Process.isIsolated(uid)) {
20653                    return Zygote.MOUNT_EXTERNAL_NONE;
20654                }
20655                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20656                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20657                }
20658                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20659                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20660                }
20661                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20662                    return Zygote.MOUNT_EXTERNAL_READ;
20663                }
20664                return Zygote.MOUNT_EXTERNAL_WRITE;
20665            }
20666
20667            @Override
20668            public boolean hasExternalStorage(int uid, String packageName) {
20669                return true;
20670            }
20671        });
20672
20673        // Now that we're mostly running, clean up stale users and apps
20674        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20675        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20676
20677        if (mPrivappPermissionsViolations != null) {
20678            Slog.wtf(TAG,"Signature|privileged permissions not in "
20679                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20680            mPrivappPermissionsViolations = null;
20681        }
20682    }
20683
20684    public void waitForAppDataPrepared() {
20685        if (mPrepareAppDataFuture == null) {
20686            return;
20687        }
20688        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20689        mPrepareAppDataFuture = null;
20690    }
20691
20692    @Override
20693    public boolean isSafeMode() {
20694        return mSafeMode;
20695    }
20696
20697    @Override
20698    public boolean hasSystemUidErrors() {
20699        return mHasSystemUidErrors;
20700    }
20701
20702    static String arrayToString(int[] array) {
20703        StringBuffer buf = new StringBuffer(128);
20704        buf.append('[');
20705        if (array != null) {
20706            for (int i=0; i<array.length; i++) {
20707                if (i > 0) buf.append(", ");
20708                buf.append(array[i]);
20709            }
20710        }
20711        buf.append(']');
20712        return buf.toString();
20713    }
20714
20715    static class DumpState {
20716        public static final int DUMP_LIBS = 1 << 0;
20717        public static final int DUMP_FEATURES = 1 << 1;
20718        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20719        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20720        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20721        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20722        public static final int DUMP_PERMISSIONS = 1 << 6;
20723        public static final int DUMP_PACKAGES = 1 << 7;
20724        public static final int DUMP_SHARED_USERS = 1 << 8;
20725        public static final int DUMP_MESSAGES = 1 << 9;
20726        public static final int DUMP_PROVIDERS = 1 << 10;
20727        public static final int DUMP_VERIFIERS = 1 << 11;
20728        public static final int DUMP_PREFERRED = 1 << 12;
20729        public static final int DUMP_PREFERRED_XML = 1 << 13;
20730        public static final int DUMP_KEYSETS = 1 << 14;
20731        public static final int DUMP_VERSION = 1 << 15;
20732        public static final int DUMP_INSTALLS = 1 << 16;
20733        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20734        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20735        public static final int DUMP_FROZEN = 1 << 19;
20736        public static final int DUMP_DEXOPT = 1 << 20;
20737        public static final int DUMP_COMPILER_STATS = 1 << 21;
20738        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20739        public static final int DUMP_CHANGES = 1 << 23;
20740
20741        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20742
20743        private int mTypes;
20744
20745        private int mOptions;
20746
20747        private boolean mTitlePrinted;
20748
20749        private SharedUserSetting mSharedUser;
20750
20751        public boolean isDumping(int type) {
20752            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20753                return true;
20754            }
20755
20756            return (mTypes & type) != 0;
20757        }
20758
20759        public void setDump(int type) {
20760            mTypes |= type;
20761        }
20762
20763        public boolean isOptionEnabled(int option) {
20764            return (mOptions & option) != 0;
20765        }
20766
20767        public void setOptionEnabled(int option) {
20768            mOptions |= option;
20769        }
20770
20771        public boolean onTitlePrinted() {
20772            final boolean printed = mTitlePrinted;
20773            mTitlePrinted = true;
20774            return printed;
20775        }
20776
20777        public boolean getTitlePrinted() {
20778            return mTitlePrinted;
20779        }
20780
20781        public void setTitlePrinted(boolean enabled) {
20782            mTitlePrinted = enabled;
20783        }
20784
20785        public SharedUserSetting getSharedUser() {
20786            return mSharedUser;
20787        }
20788
20789        public void setSharedUser(SharedUserSetting user) {
20790            mSharedUser = user;
20791        }
20792    }
20793
20794    @Override
20795    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20796            FileDescriptor err, String[] args, ShellCallback callback,
20797            ResultReceiver resultReceiver) {
20798        (new PackageManagerShellCommand(this)).exec(
20799                this, in, out, err, args, callback, resultReceiver);
20800    }
20801
20802    @Override
20803    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20804        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20805
20806        DumpState dumpState = new DumpState();
20807        boolean fullPreferred = false;
20808        boolean checkin = false;
20809
20810        String packageName = null;
20811        ArraySet<String> permissionNames = null;
20812
20813        int opti = 0;
20814        while (opti < args.length) {
20815            String opt = args[opti];
20816            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20817                break;
20818            }
20819            opti++;
20820
20821            if ("-a".equals(opt)) {
20822                // Right now we only know how to print all.
20823            } else if ("-h".equals(opt)) {
20824                pw.println("Package manager dump options:");
20825                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20826                pw.println("    --checkin: dump for a checkin");
20827                pw.println("    -f: print details of intent filters");
20828                pw.println("    -h: print this help");
20829                pw.println("  cmd may be one of:");
20830                pw.println("    l[ibraries]: list known shared libraries");
20831                pw.println("    f[eatures]: list device features");
20832                pw.println("    k[eysets]: print known keysets");
20833                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20834                pw.println("    perm[issions]: dump permissions");
20835                pw.println("    permission [name ...]: dump declaration and use of given permission");
20836                pw.println("    pref[erred]: print preferred package settings");
20837                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20838                pw.println("    prov[iders]: dump content providers");
20839                pw.println("    p[ackages]: dump installed packages");
20840                pw.println("    s[hared-users]: dump shared user IDs");
20841                pw.println("    m[essages]: print collected runtime messages");
20842                pw.println("    v[erifiers]: print package verifier info");
20843                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20844                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20845                pw.println("    version: print database version info");
20846                pw.println("    write: write current settings now");
20847                pw.println("    installs: details about install sessions");
20848                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20849                pw.println("    dexopt: dump dexopt state");
20850                pw.println("    compiler-stats: dump compiler statistics");
20851                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20852                pw.println("    <package.name>: info about given package");
20853                return;
20854            } else if ("--checkin".equals(opt)) {
20855                checkin = true;
20856            } else if ("-f".equals(opt)) {
20857                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20858            } else if ("--proto".equals(opt)) {
20859                dumpProto(fd);
20860                return;
20861            } else {
20862                pw.println("Unknown argument: " + opt + "; use -h for help");
20863            }
20864        }
20865
20866        // Is the caller requesting to dump a particular piece of data?
20867        if (opti < args.length) {
20868            String cmd = args[opti];
20869            opti++;
20870            // Is this a package name?
20871            if ("android".equals(cmd) || cmd.contains(".")) {
20872                packageName = cmd;
20873                // When dumping a single package, we always dump all of its
20874                // filter information since the amount of data will be reasonable.
20875                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20876            } else if ("check-permission".equals(cmd)) {
20877                if (opti >= args.length) {
20878                    pw.println("Error: check-permission missing permission argument");
20879                    return;
20880                }
20881                String perm = args[opti];
20882                opti++;
20883                if (opti >= args.length) {
20884                    pw.println("Error: check-permission missing package argument");
20885                    return;
20886                }
20887
20888                String pkg = args[opti];
20889                opti++;
20890                int user = UserHandle.getUserId(Binder.getCallingUid());
20891                if (opti < args.length) {
20892                    try {
20893                        user = Integer.parseInt(args[opti]);
20894                    } catch (NumberFormatException e) {
20895                        pw.println("Error: check-permission user argument is not a number: "
20896                                + args[opti]);
20897                        return;
20898                    }
20899                }
20900
20901                // Normalize package name to handle renamed packages and static libs
20902                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20903
20904                pw.println(checkPermission(perm, pkg, user));
20905                return;
20906            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20907                dumpState.setDump(DumpState.DUMP_LIBS);
20908            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20909                dumpState.setDump(DumpState.DUMP_FEATURES);
20910            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20911                if (opti >= args.length) {
20912                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20913                            | DumpState.DUMP_SERVICE_RESOLVERS
20914                            | DumpState.DUMP_RECEIVER_RESOLVERS
20915                            | DumpState.DUMP_CONTENT_RESOLVERS);
20916                } else {
20917                    while (opti < args.length) {
20918                        String name = args[opti];
20919                        if ("a".equals(name) || "activity".equals(name)) {
20920                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20921                        } else if ("s".equals(name) || "service".equals(name)) {
20922                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20923                        } else if ("r".equals(name) || "receiver".equals(name)) {
20924                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20925                        } else if ("c".equals(name) || "content".equals(name)) {
20926                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20927                        } else {
20928                            pw.println("Error: unknown resolver table type: " + name);
20929                            return;
20930                        }
20931                        opti++;
20932                    }
20933                }
20934            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20935                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20936            } else if ("permission".equals(cmd)) {
20937                if (opti >= args.length) {
20938                    pw.println("Error: permission requires permission name");
20939                    return;
20940                }
20941                permissionNames = new ArraySet<>();
20942                while (opti < args.length) {
20943                    permissionNames.add(args[opti]);
20944                    opti++;
20945                }
20946                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20947                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20948            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20949                dumpState.setDump(DumpState.DUMP_PREFERRED);
20950            } else if ("preferred-xml".equals(cmd)) {
20951                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20952                if (opti < args.length && "--full".equals(args[opti])) {
20953                    fullPreferred = true;
20954                    opti++;
20955                }
20956            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20957                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20958            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20959                dumpState.setDump(DumpState.DUMP_PACKAGES);
20960            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20961                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20962            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20963                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20964            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20965                dumpState.setDump(DumpState.DUMP_MESSAGES);
20966            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20967                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20968            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20969                    || "intent-filter-verifiers".equals(cmd)) {
20970                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20971            } else if ("version".equals(cmd)) {
20972                dumpState.setDump(DumpState.DUMP_VERSION);
20973            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20974                dumpState.setDump(DumpState.DUMP_KEYSETS);
20975            } else if ("installs".equals(cmd)) {
20976                dumpState.setDump(DumpState.DUMP_INSTALLS);
20977            } else if ("frozen".equals(cmd)) {
20978                dumpState.setDump(DumpState.DUMP_FROZEN);
20979            } else if ("dexopt".equals(cmd)) {
20980                dumpState.setDump(DumpState.DUMP_DEXOPT);
20981            } else if ("compiler-stats".equals(cmd)) {
20982                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20983            } else if ("enabled-overlays".equals(cmd)) {
20984                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20985            } else if ("changes".equals(cmd)) {
20986                dumpState.setDump(DumpState.DUMP_CHANGES);
20987            } else if ("write".equals(cmd)) {
20988                synchronized (mPackages) {
20989                    mSettings.writeLPr();
20990                    pw.println("Settings written.");
20991                    return;
20992                }
20993            }
20994        }
20995
20996        if (checkin) {
20997            pw.println("vers,1");
20998        }
20999
21000        // reader
21001        synchronized (mPackages) {
21002            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21003                if (!checkin) {
21004                    if (dumpState.onTitlePrinted())
21005                        pw.println();
21006                    pw.println("Database versions:");
21007                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21008                }
21009            }
21010
21011            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21012                if (!checkin) {
21013                    if (dumpState.onTitlePrinted())
21014                        pw.println();
21015                    pw.println("Verifiers:");
21016                    pw.print("  Required: ");
21017                    pw.print(mRequiredVerifierPackage);
21018                    pw.print(" (uid=");
21019                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21020                            UserHandle.USER_SYSTEM));
21021                    pw.println(")");
21022                } else if (mRequiredVerifierPackage != null) {
21023                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21024                    pw.print(",");
21025                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21026                            UserHandle.USER_SYSTEM));
21027                }
21028            }
21029
21030            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21031                    packageName == null) {
21032                if (mIntentFilterVerifierComponent != null) {
21033                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21034                    if (!checkin) {
21035                        if (dumpState.onTitlePrinted())
21036                            pw.println();
21037                        pw.println("Intent Filter Verifier:");
21038                        pw.print("  Using: ");
21039                        pw.print(verifierPackageName);
21040                        pw.print(" (uid=");
21041                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21042                                UserHandle.USER_SYSTEM));
21043                        pw.println(")");
21044                    } else if (verifierPackageName != null) {
21045                        pw.print("ifv,"); pw.print(verifierPackageName);
21046                        pw.print(",");
21047                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21048                                UserHandle.USER_SYSTEM));
21049                    }
21050                } else {
21051                    pw.println();
21052                    pw.println("No Intent Filter Verifier available!");
21053                }
21054            }
21055
21056            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21057                boolean printedHeader = false;
21058                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21059                while (it.hasNext()) {
21060                    String libName = it.next();
21061                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21062                    if (versionedLib == null) {
21063                        continue;
21064                    }
21065                    final int versionCount = versionedLib.size();
21066                    for (int i = 0; i < versionCount; i++) {
21067                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21068                        if (!checkin) {
21069                            if (!printedHeader) {
21070                                if (dumpState.onTitlePrinted())
21071                                    pw.println();
21072                                pw.println("Libraries:");
21073                                printedHeader = true;
21074                            }
21075                            pw.print("  ");
21076                        } else {
21077                            pw.print("lib,");
21078                        }
21079                        pw.print(libEntry.info.getName());
21080                        if (libEntry.info.isStatic()) {
21081                            pw.print(" version=" + libEntry.info.getVersion());
21082                        }
21083                        if (!checkin) {
21084                            pw.print(" -> ");
21085                        }
21086                        if (libEntry.path != null) {
21087                            pw.print(" (jar) ");
21088                            pw.print(libEntry.path);
21089                        } else {
21090                            pw.print(" (apk) ");
21091                            pw.print(libEntry.apk);
21092                        }
21093                        pw.println();
21094                    }
21095                }
21096            }
21097
21098            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21099                if (dumpState.onTitlePrinted())
21100                    pw.println();
21101                if (!checkin) {
21102                    pw.println("Features:");
21103                }
21104
21105                synchronized (mAvailableFeatures) {
21106                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21107                        if (checkin) {
21108                            pw.print("feat,");
21109                            pw.print(feat.name);
21110                            pw.print(",");
21111                            pw.println(feat.version);
21112                        } else {
21113                            pw.print("  ");
21114                            pw.print(feat.name);
21115                            if (feat.version > 0) {
21116                                pw.print(" version=");
21117                                pw.print(feat.version);
21118                            }
21119                            pw.println();
21120                        }
21121                    }
21122                }
21123            }
21124
21125            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21126                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21127                        : "Activity Resolver Table:", "  ", packageName,
21128                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21129                    dumpState.setTitlePrinted(true);
21130                }
21131            }
21132            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21133                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21134                        : "Receiver Resolver Table:", "  ", packageName,
21135                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21136                    dumpState.setTitlePrinted(true);
21137                }
21138            }
21139            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21140                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21141                        : "Service Resolver Table:", "  ", packageName,
21142                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21143                    dumpState.setTitlePrinted(true);
21144                }
21145            }
21146            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21147                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21148                        : "Provider Resolver Table:", "  ", packageName,
21149                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21150                    dumpState.setTitlePrinted(true);
21151                }
21152            }
21153
21154            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21155                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21156                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21157                    int user = mSettings.mPreferredActivities.keyAt(i);
21158                    if (pir.dump(pw,
21159                            dumpState.getTitlePrinted()
21160                                ? "\nPreferred Activities User " + user + ":"
21161                                : "Preferred Activities User " + user + ":", "  ",
21162                            packageName, true, false)) {
21163                        dumpState.setTitlePrinted(true);
21164                    }
21165                }
21166            }
21167
21168            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21169                pw.flush();
21170                FileOutputStream fout = new FileOutputStream(fd);
21171                BufferedOutputStream str = new BufferedOutputStream(fout);
21172                XmlSerializer serializer = new FastXmlSerializer();
21173                try {
21174                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21175                    serializer.startDocument(null, true);
21176                    serializer.setFeature(
21177                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21178                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21179                    serializer.endDocument();
21180                    serializer.flush();
21181                } catch (IllegalArgumentException e) {
21182                    pw.println("Failed writing: " + e);
21183                } catch (IllegalStateException e) {
21184                    pw.println("Failed writing: " + e);
21185                } catch (IOException e) {
21186                    pw.println("Failed writing: " + e);
21187                }
21188            }
21189
21190            if (!checkin
21191                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21192                    && packageName == null) {
21193                pw.println();
21194                int count = mSettings.mPackages.size();
21195                if (count == 0) {
21196                    pw.println("No applications!");
21197                    pw.println();
21198                } else {
21199                    final String prefix = "  ";
21200                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21201                    if (allPackageSettings.size() == 0) {
21202                        pw.println("No domain preferred apps!");
21203                        pw.println();
21204                    } else {
21205                        pw.println("App verification status:");
21206                        pw.println();
21207                        count = 0;
21208                        for (PackageSetting ps : allPackageSettings) {
21209                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21210                            if (ivi == null || ivi.getPackageName() == null) continue;
21211                            pw.println(prefix + "Package: " + ivi.getPackageName());
21212                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21213                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21214                            pw.println();
21215                            count++;
21216                        }
21217                        if (count == 0) {
21218                            pw.println(prefix + "No app verification established.");
21219                            pw.println();
21220                        }
21221                        for (int userId : sUserManager.getUserIds()) {
21222                            pw.println("App linkages for user " + userId + ":");
21223                            pw.println();
21224                            count = 0;
21225                            for (PackageSetting ps : allPackageSettings) {
21226                                final long status = ps.getDomainVerificationStatusForUser(userId);
21227                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21228                                        && !DEBUG_DOMAIN_VERIFICATION) {
21229                                    continue;
21230                                }
21231                                pw.println(prefix + "Package: " + ps.name);
21232                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21233                                String statusStr = IntentFilterVerificationInfo.
21234                                        getStatusStringFromValue(status);
21235                                pw.println(prefix + "Status:  " + statusStr);
21236                                pw.println();
21237                                count++;
21238                            }
21239                            if (count == 0) {
21240                                pw.println(prefix + "No configured app linkages.");
21241                                pw.println();
21242                            }
21243                        }
21244                    }
21245                }
21246            }
21247
21248            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21249                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21250                if (packageName == null && permissionNames == null) {
21251                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
21252                        if (iperm == 0) {
21253                            if (dumpState.onTitlePrinted())
21254                                pw.println();
21255                            pw.println("AppOp Permissions:");
21256                        }
21257                        pw.print("  AppOp Permission ");
21258                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
21259                        pw.println(":");
21260                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
21261                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
21262                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
21263                        }
21264                    }
21265                }
21266            }
21267
21268            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21269                boolean printedSomething = false;
21270                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21271                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21272                        continue;
21273                    }
21274                    if (!printedSomething) {
21275                        if (dumpState.onTitlePrinted())
21276                            pw.println();
21277                        pw.println("Registered ContentProviders:");
21278                        printedSomething = true;
21279                    }
21280                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21281                    pw.print("    "); pw.println(p.toString());
21282                }
21283                printedSomething = false;
21284                for (Map.Entry<String, PackageParser.Provider> entry :
21285                        mProvidersByAuthority.entrySet()) {
21286                    PackageParser.Provider p = entry.getValue();
21287                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21288                        continue;
21289                    }
21290                    if (!printedSomething) {
21291                        if (dumpState.onTitlePrinted())
21292                            pw.println();
21293                        pw.println("ContentProvider Authorities:");
21294                        printedSomething = true;
21295                    }
21296                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21297                    pw.print("    "); pw.println(p.toString());
21298                    if (p.info != null && p.info.applicationInfo != null) {
21299                        final String appInfo = p.info.applicationInfo.toString();
21300                        pw.print("      applicationInfo="); pw.println(appInfo);
21301                    }
21302                }
21303            }
21304
21305            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21306                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21307            }
21308
21309            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21310                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21311            }
21312
21313            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21314                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21315            }
21316
21317            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21318                if (dumpState.onTitlePrinted()) pw.println();
21319                pw.println("Package Changes:");
21320                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21321                final int K = mChangedPackages.size();
21322                for (int i = 0; i < K; i++) {
21323                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21324                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21325                    final int N = changes.size();
21326                    if (N == 0) {
21327                        pw.print("    "); pw.println("No packages changed");
21328                    } else {
21329                        for (int j = 0; j < N; j++) {
21330                            final String pkgName = changes.valueAt(j);
21331                            final int sequenceNumber = changes.keyAt(j);
21332                            pw.print("    ");
21333                            pw.print("seq=");
21334                            pw.print(sequenceNumber);
21335                            pw.print(", package=");
21336                            pw.println(pkgName);
21337                        }
21338                    }
21339                }
21340            }
21341
21342            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21343                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21344            }
21345
21346            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21347                // XXX should handle packageName != null by dumping only install data that
21348                // the given package is involved with.
21349                if (dumpState.onTitlePrinted()) pw.println();
21350
21351                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21352                ipw.println();
21353                ipw.println("Frozen packages:");
21354                ipw.increaseIndent();
21355                if (mFrozenPackages.size() == 0) {
21356                    ipw.println("(none)");
21357                } else {
21358                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21359                        ipw.println(mFrozenPackages.valueAt(i));
21360                    }
21361                }
21362                ipw.decreaseIndent();
21363            }
21364
21365            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21366                if (dumpState.onTitlePrinted()) pw.println();
21367                dumpDexoptStateLPr(pw, packageName);
21368            }
21369
21370            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21371                if (dumpState.onTitlePrinted()) pw.println();
21372                dumpCompilerStatsLPr(pw, packageName);
21373            }
21374
21375            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
21376                if (dumpState.onTitlePrinted()) pw.println();
21377                dumpEnabledOverlaysLPr(pw);
21378            }
21379
21380            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21381                if (dumpState.onTitlePrinted()) pw.println();
21382                mSettings.dumpReadMessagesLPr(pw, dumpState);
21383
21384                pw.println();
21385                pw.println("Package warning messages:");
21386                BufferedReader in = null;
21387                String line = null;
21388                try {
21389                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21390                    while ((line = in.readLine()) != null) {
21391                        if (line.contains("ignored: updated version")) continue;
21392                        pw.println(line);
21393                    }
21394                } catch (IOException ignored) {
21395                } finally {
21396                    IoUtils.closeQuietly(in);
21397                }
21398            }
21399
21400            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21401                BufferedReader in = null;
21402                String line = null;
21403                try {
21404                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21405                    while ((line = in.readLine()) != null) {
21406                        if (line.contains("ignored: updated version")) continue;
21407                        pw.print("msg,");
21408                        pw.println(line);
21409                    }
21410                } catch (IOException ignored) {
21411                } finally {
21412                    IoUtils.closeQuietly(in);
21413                }
21414            }
21415        }
21416
21417        // PackageInstaller should be called outside of mPackages lock
21418        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21419            // XXX should handle packageName != null by dumping only install data that
21420            // the given package is involved with.
21421            if (dumpState.onTitlePrinted()) pw.println();
21422            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21423        }
21424    }
21425
21426    private void dumpProto(FileDescriptor fd) {
21427        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21428
21429        synchronized (mPackages) {
21430            final long requiredVerifierPackageToken =
21431                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21432            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21433            proto.write(
21434                    PackageServiceDumpProto.PackageShortProto.UID,
21435                    getPackageUid(
21436                            mRequiredVerifierPackage,
21437                            MATCH_DEBUG_TRIAGED_MISSING,
21438                            UserHandle.USER_SYSTEM));
21439            proto.end(requiredVerifierPackageToken);
21440
21441            if (mIntentFilterVerifierComponent != null) {
21442                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21443                final long verifierPackageToken =
21444                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21445                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21446                proto.write(
21447                        PackageServiceDumpProto.PackageShortProto.UID,
21448                        getPackageUid(
21449                                verifierPackageName,
21450                                MATCH_DEBUG_TRIAGED_MISSING,
21451                                UserHandle.USER_SYSTEM));
21452                proto.end(verifierPackageToken);
21453            }
21454
21455            dumpSharedLibrariesProto(proto);
21456            dumpFeaturesProto(proto);
21457            mSettings.dumpPackagesProto(proto);
21458            mSettings.dumpSharedUsersProto(proto);
21459            dumpMessagesProto(proto);
21460        }
21461        proto.flush();
21462    }
21463
21464    private void dumpMessagesProto(ProtoOutputStream proto) {
21465        BufferedReader in = null;
21466        String line = null;
21467        try {
21468            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21469            while ((line = in.readLine()) != null) {
21470                if (line.contains("ignored: updated version")) continue;
21471                proto.write(PackageServiceDumpProto.MESSAGES, line);
21472            }
21473        } catch (IOException ignored) {
21474        } finally {
21475            IoUtils.closeQuietly(in);
21476        }
21477    }
21478
21479    private void dumpFeaturesProto(ProtoOutputStream proto) {
21480        synchronized (mAvailableFeatures) {
21481            final int count = mAvailableFeatures.size();
21482            for (int i = 0; i < count; i++) {
21483                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
21484                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
21485                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
21486                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
21487                proto.end(featureToken);
21488            }
21489        }
21490    }
21491
21492    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21493        final int count = mSharedLibraries.size();
21494        for (int i = 0; i < count; i++) {
21495            final String libName = mSharedLibraries.keyAt(i);
21496            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21497            if (versionedLib == null) {
21498                continue;
21499            }
21500            final int versionCount = versionedLib.size();
21501            for (int j = 0; j < versionCount; j++) {
21502                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21503                final long sharedLibraryToken =
21504                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21505                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21506                final boolean isJar = (libEntry.path != null);
21507                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21508                if (isJar) {
21509                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21510                } else {
21511                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21512                }
21513                proto.end(sharedLibraryToken);
21514            }
21515        }
21516    }
21517
21518    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21519        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21520        ipw.println();
21521        ipw.println("Dexopt state:");
21522        ipw.increaseIndent();
21523        Collection<PackageParser.Package> packages = null;
21524        if (packageName != null) {
21525            PackageParser.Package targetPackage = mPackages.get(packageName);
21526            if (targetPackage != null) {
21527                packages = Collections.singletonList(targetPackage);
21528            } else {
21529                ipw.println("Unable to find package: " + packageName);
21530                return;
21531            }
21532        } else {
21533            packages = mPackages.values();
21534        }
21535
21536        for (PackageParser.Package pkg : packages) {
21537            ipw.println("[" + pkg.packageName + "]");
21538            ipw.increaseIndent();
21539            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
21540            ipw.decreaseIndent();
21541        }
21542    }
21543
21544    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21545        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21546        ipw.println();
21547        ipw.println("Compiler stats:");
21548        ipw.increaseIndent();
21549        Collection<PackageParser.Package> packages = null;
21550        if (packageName != null) {
21551            PackageParser.Package targetPackage = mPackages.get(packageName);
21552            if (targetPackage != null) {
21553                packages = Collections.singletonList(targetPackage);
21554            } else {
21555                ipw.println("Unable to find package: " + packageName);
21556                return;
21557            }
21558        } else {
21559            packages = mPackages.values();
21560        }
21561
21562        for (PackageParser.Package pkg : packages) {
21563            ipw.println("[" + pkg.packageName + "]");
21564            ipw.increaseIndent();
21565
21566            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21567            if (stats == null) {
21568                ipw.println("(No recorded stats)");
21569            } else {
21570                stats.dump(ipw);
21571            }
21572            ipw.decreaseIndent();
21573        }
21574    }
21575
21576    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
21577        pw.println("Enabled overlay paths:");
21578        final int N = mEnabledOverlayPaths.size();
21579        for (int i = 0; i < N; i++) {
21580            final int userId = mEnabledOverlayPaths.keyAt(i);
21581            pw.println(String.format("    User %d:", userId));
21582            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
21583                mEnabledOverlayPaths.valueAt(i);
21584            final int M = userSpecificOverlays.size();
21585            for (int j = 0; j < M; j++) {
21586                final String targetPackageName = userSpecificOverlays.keyAt(j);
21587                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
21588                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
21589            }
21590        }
21591    }
21592
21593    private String dumpDomainString(String packageName) {
21594        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21595                .getList();
21596        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21597
21598        ArraySet<String> result = new ArraySet<>();
21599        if (iviList.size() > 0) {
21600            for (IntentFilterVerificationInfo ivi : iviList) {
21601                for (String host : ivi.getDomains()) {
21602                    result.add(host);
21603                }
21604            }
21605        }
21606        if (filters != null && filters.size() > 0) {
21607            for (IntentFilter filter : filters) {
21608                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21609                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21610                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21611                    result.addAll(filter.getHostsList());
21612                }
21613            }
21614        }
21615
21616        StringBuilder sb = new StringBuilder(result.size() * 16);
21617        for (String domain : result) {
21618            if (sb.length() > 0) sb.append(" ");
21619            sb.append(domain);
21620        }
21621        return sb.toString();
21622    }
21623
21624    // ------- apps on sdcard specific code -------
21625    static final boolean DEBUG_SD_INSTALL = false;
21626
21627    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21628
21629    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21630
21631    private boolean mMediaMounted = false;
21632
21633    static String getEncryptKey() {
21634        try {
21635            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21636                    SD_ENCRYPTION_KEYSTORE_NAME);
21637            if (sdEncKey == null) {
21638                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21639                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21640                if (sdEncKey == null) {
21641                    Slog.e(TAG, "Failed to create encryption keys");
21642                    return null;
21643                }
21644            }
21645            return sdEncKey;
21646        } catch (NoSuchAlgorithmException nsae) {
21647            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21648            return null;
21649        } catch (IOException ioe) {
21650            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21651            return null;
21652        }
21653    }
21654
21655    /*
21656     * Update media status on PackageManager.
21657     */
21658    @Override
21659    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21660        int callingUid = Binder.getCallingUid();
21661        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21662            throw new SecurityException("Media status can only be updated by the system");
21663        }
21664        // reader; this apparently protects mMediaMounted, but should probably
21665        // be a different lock in that case.
21666        synchronized (mPackages) {
21667            Log.i(TAG, "Updating external media status from "
21668                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21669                    + (mediaStatus ? "mounted" : "unmounted"));
21670            if (DEBUG_SD_INSTALL)
21671                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21672                        + ", mMediaMounted=" + mMediaMounted);
21673            if (mediaStatus == mMediaMounted) {
21674                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21675                        : 0, -1);
21676                mHandler.sendMessage(msg);
21677                return;
21678            }
21679            mMediaMounted = mediaStatus;
21680        }
21681        // Queue up an async operation since the package installation may take a
21682        // little while.
21683        mHandler.post(new Runnable() {
21684            public void run() {
21685                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21686            }
21687        });
21688    }
21689
21690    /**
21691     * Called by StorageManagerService when the initial ASECs to scan are available.
21692     * Should block until all the ASEC containers are finished being scanned.
21693     */
21694    public void scanAvailableAsecs() {
21695        updateExternalMediaStatusInner(true, false, false);
21696    }
21697
21698    /*
21699     * Collect information of applications on external media, map them against
21700     * existing containers and update information based on current mount status.
21701     * Please note that we always have to report status if reportStatus has been
21702     * set to true especially when unloading packages.
21703     */
21704    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21705            boolean externalStorage) {
21706        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21707        int[] uidArr = EmptyArray.INT;
21708
21709        final String[] list = PackageHelper.getSecureContainerList();
21710        if (ArrayUtils.isEmpty(list)) {
21711            Log.i(TAG, "No secure containers found");
21712        } else {
21713            // Process list of secure containers and categorize them
21714            // as active or stale based on their package internal state.
21715
21716            // reader
21717            synchronized (mPackages) {
21718                for (String cid : list) {
21719                    // Leave stages untouched for now; installer service owns them
21720                    if (PackageInstallerService.isStageName(cid)) continue;
21721
21722                    if (DEBUG_SD_INSTALL)
21723                        Log.i(TAG, "Processing container " + cid);
21724                    String pkgName = getAsecPackageName(cid);
21725                    if (pkgName == null) {
21726                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21727                        continue;
21728                    }
21729                    if (DEBUG_SD_INSTALL)
21730                        Log.i(TAG, "Looking for pkg : " + pkgName);
21731
21732                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21733                    if (ps == null) {
21734                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21735                        continue;
21736                    }
21737
21738                    /*
21739                     * Skip packages that are not external if we're unmounting
21740                     * external storage.
21741                     */
21742                    if (externalStorage && !isMounted && !isExternal(ps)) {
21743                        continue;
21744                    }
21745
21746                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21747                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21748                    // The package status is changed only if the code path
21749                    // matches between settings and the container id.
21750                    if (ps.codePathString != null
21751                            && ps.codePathString.startsWith(args.getCodePath())) {
21752                        if (DEBUG_SD_INSTALL) {
21753                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21754                                    + " at code path: " + ps.codePathString);
21755                        }
21756
21757                        // We do have a valid package installed on sdcard
21758                        processCids.put(args, ps.codePathString);
21759                        final int uid = ps.appId;
21760                        if (uid != -1) {
21761                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21762                        }
21763                    } else {
21764                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21765                                + ps.codePathString);
21766                    }
21767                }
21768            }
21769
21770            Arrays.sort(uidArr);
21771        }
21772
21773        // Process packages with valid entries.
21774        if (isMounted) {
21775            if (DEBUG_SD_INSTALL)
21776                Log.i(TAG, "Loading packages");
21777            loadMediaPackages(processCids, uidArr, externalStorage);
21778            startCleaningPackages();
21779            mInstallerService.onSecureContainersAvailable();
21780        } else {
21781            if (DEBUG_SD_INSTALL)
21782                Log.i(TAG, "Unloading packages");
21783            unloadMediaPackages(processCids, uidArr, reportStatus);
21784        }
21785    }
21786
21787    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21788            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21789        final int size = infos.size();
21790        final String[] packageNames = new String[size];
21791        final int[] packageUids = new int[size];
21792        for (int i = 0; i < size; i++) {
21793            final ApplicationInfo info = infos.get(i);
21794            packageNames[i] = info.packageName;
21795            packageUids[i] = info.uid;
21796        }
21797        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21798                finishedReceiver);
21799    }
21800
21801    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21802            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21803        sendResourcesChangedBroadcast(mediaStatus, replacing,
21804                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21805    }
21806
21807    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21808            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21809        int size = pkgList.length;
21810        if (size > 0) {
21811            // Send broadcasts here
21812            Bundle extras = new Bundle();
21813            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21814            if (uidArr != null) {
21815                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21816            }
21817            if (replacing) {
21818                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21819            }
21820            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21821                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21822            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21823        }
21824    }
21825
21826   /*
21827     * Look at potentially valid container ids from processCids If package
21828     * information doesn't match the one on record or package scanning fails,
21829     * the cid is added to list of removeCids. We currently don't delete stale
21830     * containers.
21831     */
21832    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21833            boolean externalStorage) {
21834        ArrayList<String> pkgList = new ArrayList<String>();
21835        Set<AsecInstallArgs> keys = processCids.keySet();
21836
21837        for (AsecInstallArgs args : keys) {
21838            String codePath = processCids.get(args);
21839            if (DEBUG_SD_INSTALL)
21840                Log.i(TAG, "Loading container : " + args.cid);
21841            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21842            try {
21843                // Make sure there are no container errors first.
21844                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21845                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21846                            + " when installing from sdcard");
21847                    continue;
21848                }
21849                // Check code path here.
21850                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21851                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21852                            + " does not match one in settings " + codePath);
21853                    continue;
21854                }
21855                // Parse package
21856                int parseFlags = mDefParseFlags;
21857                if (args.isExternalAsec()) {
21858                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21859                }
21860                if (args.isFwdLocked()) {
21861                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21862                }
21863
21864                synchronized (mInstallLock) {
21865                    PackageParser.Package pkg = null;
21866                    try {
21867                        // Sadly we don't know the package name yet to freeze it
21868                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21869                                SCAN_IGNORE_FROZEN, 0, null);
21870                    } catch (PackageManagerException e) {
21871                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21872                    }
21873                    // Scan the package
21874                    if (pkg != null) {
21875                        /*
21876                         * TODO why is the lock being held? doPostInstall is
21877                         * called in other places without the lock. This needs
21878                         * to be straightened out.
21879                         */
21880                        // writer
21881                        synchronized (mPackages) {
21882                            retCode = PackageManager.INSTALL_SUCCEEDED;
21883                            pkgList.add(pkg.packageName);
21884                            // Post process args
21885                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21886                                    pkg.applicationInfo.uid);
21887                        }
21888                    } else {
21889                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21890                    }
21891                }
21892
21893            } finally {
21894                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21895                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21896                }
21897            }
21898        }
21899        // writer
21900        synchronized (mPackages) {
21901            // If the platform SDK has changed since the last time we booted,
21902            // we need to re-grant app permission to catch any new ones that
21903            // appear. This is really a hack, and means that apps can in some
21904            // cases get permissions that the user didn't initially explicitly
21905            // allow... it would be nice to have some better way to handle
21906            // this situation.
21907            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21908                    : mSettings.getInternalVersion();
21909            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21910                    : StorageManager.UUID_PRIVATE_INTERNAL;
21911
21912            int updateFlags = UPDATE_PERMISSIONS_ALL;
21913            if (ver.sdkVersion != mSdkVersion) {
21914                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21915                        + mSdkVersion + "; regranting permissions for external");
21916                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21917            }
21918            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21919
21920            // Yay, everything is now upgraded
21921            ver.forceCurrent();
21922
21923            // can downgrade to reader
21924            // Persist settings
21925            mSettings.writeLPr();
21926        }
21927        // Send a broadcast to let everyone know we are done processing
21928        if (pkgList.size() > 0) {
21929            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21930        }
21931    }
21932
21933   /*
21934     * Utility method to unload a list of specified containers
21935     */
21936    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21937        // Just unmount all valid containers.
21938        for (AsecInstallArgs arg : cidArgs) {
21939            synchronized (mInstallLock) {
21940                arg.doPostDeleteLI(false);
21941           }
21942       }
21943   }
21944
21945    /*
21946     * Unload packages mounted on external media. This involves deleting package
21947     * data from internal structures, sending broadcasts about disabled packages,
21948     * gc'ing to free up references, unmounting all secure containers
21949     * corresponding to packages on external media, and posting a
21950     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21951     * that we always have to post this message if status has been requested no
21952     * matter what.
21953     */
21954    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21955            final boolean reportStatus) {
21956        if (DEBUG_SD_INSTALL)
21957            Log.i(TAG, "unloading media packages");
21958        ArrayList<String> pkgList = new ArrayList<String>();
21959        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21960        final Set<AsecInstallArgs> keys = processCids.keySet();
21961        for (AsecInstallArgs args : keys) {
21962            String pkgName = args.getPackageName();
21963            if (DEBUG_SD_INSTALL)
21964                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21965            // Delete package internally
21966            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21967            synchronized (mInstallLock) {
21968                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21969                final boolean res;
21970                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21971                        "unloadMediaPackages")) {
21972                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21973                            null);
21974                }
21975                if (res) {
21976                    pkgList.add(pkgName);
21977                } else {
21978                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21979                    failedList.add(args);
21980                }
21981            }
21982        }
21983
21984        // reader
21985        synchronized (mPackages) {
21986            // We didn't update the settings after removing each package;
21987            // write them now for all packages.
21988            mSettings.writeLPr();
21989        }
21990
21991        // We have to absolutely send UPDATED_MEDIA_STATUS only
21992        // after confirming that all the receivers processed the ordered
21993        // broadcast when packages get disabled, force a gc to clean things up.
21994        // and unload all the containers.
21995        if (pkgList.size() > 0) {
21996            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21997                    new IIntentReceiver.Stub() {
21998                public void performReceive(Intent intent, int resultCode, String data,
21999                        Bundle extras, boolean ordered, boolean sticky,
22000                        int sendingUser) throws RemoteException {
22001                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22002                            reportStatus ? 1 : 0, 1, keys);
22003                    mHandler.sendMessage(msg);
22004                }
22005            });
22006        } else {
22007            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22008                    keys);
22009            mHandler.sendMessage(msg);
22010        }
22011    }
22012
22013    private void loadPrivatePackages(final VolumeInfo vol) {
22014        mHandler.post(new Runnable() {
22015            @Override
22016            public void run() {
22017                loadPrivatePackagesInner(vol);
22018            }
22019        });
22020    }
22021
22022    private void loadPrivatePackagesInner(VolumeInfo vol) {
22023        final String volumeUuid = vol.fsUuid;
22024        if (TextUtils.isEmpty(volumeUuid)) {
22025            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22026            return;
22027        }
22028
22029        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22030        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22031        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22032
22033        final VersionInfo ver;
22034        final List<PackageSetting> packages;
22035        synchronized (mPackages) {
22036            ver = mSettings.findOrCreateVersion(volumeUuid);
22037            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22038        }
22039
22040        for (PackageSetting ps : packages) {
22041            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22042            synchronized (mInstallLock) {
22043                final PackageParser.Package pkg;
22044                try {
22045                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22046                    loaded.add(pkg.applicationInfo);
22047
22048                } catch (PackageManagerException e) {
22049                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22050                }
22051
22052                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22053                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22054                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22055                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22056                }
22057            }
22058        }
22059
22060        // Reconcile app data for all started/unlocked users
22061        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22062        final UserManager um = mContext.getSystemService(UserManager.class);
22063        UserManagerInternal umInternal = getUserManagerInternal();
22064        for (UserInfo user : um.getUsers()) {
22065            final int flags;
22066            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22067                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22068            } else if (umInternal.isUserRunning(user.id)) {
22069                flags = StorageManager.FLAG_STORAGE_DE;
22070            } else {
22071                continue;
22072            }
22073
22074            try {
22075                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22076                synchronized (mInstallLock) {
22077                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22078                }
22079            } catch (IllegalStateException e) {
22080                // Device was probably ejected, and we'll process that event momentarily
22081                Slog.w(TAG, "Failed to prepare storage: " + e);
22082            }
22083        }
22084
22085        synchronized (mPackages) {
22086            int updateFlags = UPDATE_PERMISSIONS_ALL;
22087            if (ver.sdkVersion != mSdkVersion) {
22088                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22089                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22090                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22091            }
22092            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22093
22094            // Yay, everything is now upgraded
22095            ver.forceCurrent();
22096
22097            mSettings.writeLPr();
22098        }
22099
22100        for (PackageFreezer freezer : freezers) {
22101            freezer.close();
22102        }
22103
22104        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22105        sendResourcesChangedBroadcast(true, false, loaded, null);
22106    }
22107
22108    private void unloadPrivatePackages(final VolumeInfo vol) {
22109        mHandler.post(new Runnable() {
22110            @Override
22111            public void run() {
22112                unloadPrivatePackagesInner(vol);
22113            }
22114        });
22115    }
22116
22117    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22118        final String volumeUuid = vol.fsUuid;
22119        if (TextUtils.isEmpty(volumeUuid)) {
22120            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22121            return;
22122        }
22123
22124        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22125        synchronized (mInstallLock) {
22126        synchronized (mPackages) {
22127            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22128            for (PackageSetting ps : packages) {
22129                if (ps.pkg == null) continue;
22130
22131                final ApplicationInfo info = ps.pkg.applicationInfo;
22132                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22133                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22134
22135                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22136                        "unloadPrivatePackagesInner")) {
22137                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22138                            false, null)) {
22139                        unloaded.add(info);
22140                    } else {
22141                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22142                    }
22143                }
22144
22145                // Try very hard to release any references to this package
22146                // so we don't risk the system server being killed due to
22147                // open FDs
22148                AttributeCache.instance().removePackage(ps.name);
22149            }
22150
22151            mSettings.writeLPr();
22152        }
22153        }
22154
22155        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22156        sendResourcesChangedBroadcast(false, false, unloaded, null);
22157
22158        // Try very hard to release any references to this path so we don't risk
22159        // the system server being killed due to open FDs
22160        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22161
22162        for (int i = 0; i < 3; i++) {
22163            System.gc();
22164            System.runFinalization();
22165        }
22166    }
22167
22168    private void assertPackageKnown(String volumeUuid, String packageName)
22169            throws PackageManagerException {
22170        synchronized (mPackages) {
22171            // Normalize package name to handle renamed packages
22172            packageName = normalizePackageNameLPr(packageName);
22173
22174            final PackageSetting ps = mSettings.mPackages.get(packageName);
22175            if (ps == null) {
22176                throw new PackageManagerException("Package " + packageName + " is unknown");
22177            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22178                throw new PackageManagerException(
22179                        "Package " + packageName + " found on unknown volume " + volumeUuid
22180                                + "; expected volume " + ps.volumeUuid);
22181            }
22182        }
22183    }
22184
22185    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22186            throws PackageManagerException {
22187        synchronized (mPackages) {
22188            // Normalize package name to handle renamed packages
22189            packageName = normalizePackageNameLPr(packageName);
22190
22191            final PackageSetting ps = mSettings.mPackages.get(packageName);
22192            if (ps == null) {
22193                throw new PackageManagerException("Package " + packageName + " is unknown");
22194            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22195                throw new PackageManagerException(
22196                        "Package " + packageName + " found on unknown volume " + volumeUuid
22197                                + "; expected volume " + ps.volumeUuid);
22198            } else if (!ps.getInstalled(userId)) {
22199                throw new PackageManagerException(
22200                        "Package " + packageName + " not installed for user " + userId);
22201            }
22202        }
22203    }
22204
22205    private List<String> collectAbsoluteCodePaths() {
22206        synchronized (mPackages) {
22207            List<String> codePaths = new ArrayList<>();
22208            final int packageCount = mSettings.mPackages.size();
22209            for (int i = 0; i < packageCount; i++) {
22210                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22211                codePaths.add(ps.codePath.getAbsolutePath());
22212            }
22213            return codePaths;
22214        }
22215    }
22216
22217    /**
22218     * Examine all apps present on given mounted volume, and destroy apps that
22219     * aren't expected, either due to uninstallation or reinstallation on
22220     * another volume.
22221     */
22222    private void reconcileApps(String volumeUuid) {
22223        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22224        List<File> filesToDelete = null;
22225
22226        final File[] files = FileUtils.listFilesOrEmpty(
22227                Environment.getDataAppDirectory(volumeUuid));
22228        for (File file : files) {
22229            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22230                    && !PackageInstallerService.isStageName(file.getName());
22231            if (!isPackage) {
22232                // Ignore entries which are not packages
22233                continue;
22234            }
22235
22236            String absolutePath = file.getAbsolutePath();
22237
22238            boolean pathValid = false;
22239            final int absoluteCodePathCount = absoluteCodePaths.size();
22240            for (int i = 0; i < absoluteCodePathCount; i++) {
22241                String absoluteCodePath = absoluteCodePaths.get(i);
22242                if (absolutePath.startsWith(absoluteCodePath)) {
22243                    pathValid = true;
22244                    break;
22245                }
22246            }
22247
22248            if (!pathValid) {
22249                if (filesToDelete == null) {
22250                    filesToDelete = new ArrayList<>();
22251                }
22252                filesToDelete.add(file);
22253            }
22254        }
22255
22256        if (filesToDelete != null) {
22257            final int fileToDeleteCount = filesToDelete.size();
22258            for (int i = 0; i < fileToDeleteCount; i++) {
22259                File fileToDelete = filesToDelete.get(i);
22260                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22261                synchronized (mInstallLock) {
22262                    removeCodePathLI(fileToDelete);
22263                }
22264            }
22265        }
22266    }
22267
22268    /**
22269     * Reconcile all app data for the given user.
22270     * <p>
22271     * Verifies that directories exist and that ownership and labeling is
22272     * correct for all installed apps on all mounted volumes.
22273     */
22274    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22275        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22276        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22277            final String volumeUuid = vol.getFsUuid();
22278            synchronized (mInstallLock) {
22279                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22280            }
22281        }
22282    }
22283
22284    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22285            boolean migrateAppData) {
22286        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22287    }
22288
22289    /**
22290     * Reconcile all app data on given mounted volume.
22291     * <p>
22292     * Destroys app data that isn't expected, either due to uninstallation or
22293     * reinstallation on another volume.
22294     * <p>
22295     * Verifies that directories exist and that ownership and labeling is
22296     * correct for all installed apps.
22297     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22298     */
22299    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22300            boolean migrateAppData, boolean onlyCoreApps) {
22301        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22302                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22303        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22304
22305        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22306        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22307
22308        // First look for stale data that doesn't belong, and check if things
22309        // have changed since we did our last restorecon
22310        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22311            if (StorageManager.isFileEncryptedNativeOrEmulated()
22312                    && !StorageManager.isUserKeyUnlocked(userId)) {
22313                throw new RuntimeException(
22314                        "Yikes, someone asked us to reconcile CE storage while " + userId
22315                                + " was still locked; this would have caused massive data loss!");
22316            }
22317
22318            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22319            for (File file : files) {
22320                final String packageName = file.getName();
22321                try {
22322                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22323                } catch (PackageManagerException e) {
22324                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22325                    try {
22326                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22327                                StorageManager.FLAG_STORAGE_CE, 0);
22328                    } catch (InstallerException e2) {
22329                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22330                    }
22331                }
22332            }
22333        }
22334        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22335            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22336            for (File file : files) {
22337                final String packageName = file.getName();
22338                try {
22339                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22340                } catch (PackageManagerException e) {
22341                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22342                    try {
22343                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22344                                StorageManager.FLAG_STORAGE_DE, 0);
22345                    } catch (InstallerException e2) {
22346                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22347                    }
22348                }
22349            }
22350        }
22351
22352        // Ensure that data directories are ready to roll for all packages
22353        // installed for this volume and user
22354        final List<PackageSetting> packages;
22355        synchronized (mPackages) {
22356            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22357        }
22358        int preparedCount = 0;
22359        for (PackageSetting ps : packages) {
22360            final String packageName = ps.name;
22361            if (ps.pkg == null) {
22362                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22363                // TODO: might be due to legacy ASEC apps; we should circle back
22364                // and reconcile again once they're scanned
22365                continue;
22366            }
22367            // Skip non-core apps if requested
22368            if (onlyCoreApps && !ps.pkg.coreApp) {
22369                result.add(packageName);
22370                continue;
22371            }
22372
22373            if (ps.getInstalled(userId)) {
22374                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22375                preparedCount++;
22376            }
22377        }
22378
22379        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22380        return result;
22381    }
22382
22383    /**
22384     * Prepare app data for the given app just after it was installed or
22385     * upgraded. This method carefully only touches users that it's installed
22386     * for, and it forces a restorecon to handle any seinfo changes.
22387     * <p>
22388     * Verifies that directories exist and that ownership and labeling is
22389     * correct for all installed apps. If there is an ownership mismatch, it
22390     * will try recovering system apps by wiping data; third-party app data is
22391     * left intact.
22392     * <p>
22393     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22394     */
22395    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22396        final PackageSetting ps;
22397        synchronized (mPackages) {
22398            ps = mSettings.mPackages.get(pkg.packageName);
22399            mSettings.writeKernelMappingLPr(ps);
22400        }
22401
22402        final UserManager um = mContext.getSystemService(UserManager.class);
22403        UserManagerInternal umInternal = getUserManagerInternal();
22404        for (UserInfo user : um.getUsers()) {
22405            final int flags;
22406            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22407                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22408            } else if (umInternal.isUserRunning(user.id)) {
22409                flags = StorageManager.FLAG_STORAGE_DE;
22410            } else {
22411                continue;
22412            }
22413
22414            if (ps.getInstalled(user.id)) {
22415                // TODO: when user data is locked, mark that we're still dirty
22416                prepareAppDataLIF(pkg, user.id, flags);
22417            }
22418        }
22419    }
22420
22421    /**
22422     * Prepare app data for the given app.
22423     * <p>
22424     * Verifies that directories exist and that ownership and labeling is
22425     * correct for all installed apps. If there is an ownership mismatch, this
22426     * will try recovering system apps by wiping data; third-party app data is
22427     * left intact.
22428     */
22429    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22430        if (pkg == null) {
22431            Slog.wtf(TAG, "Package was null!", new Throwable());
22432            return;
22433        }
22434        prepareAppDataLeafLIF(pkg, userId, flags);
22435        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22436        for (int i = 0; i < childCount; i++) {
22437            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22438        }
22439    }
22440
22441    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22442            boolean maybeMigrateAppData) {
22443        prepareAppDataLIF(pkg, userId, flags);
22444
22445        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22446            // We may have just shuffled around app data directories, so
22447            // prepare them one more time
22448            prepareAppDataLIF(pkg, userId, flags);
22449        }
22450    }
22451
22452    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22453        if (DEBUG_APP_DATA) {
22454            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22455                    + Integer.toHexString(flags));
22456        }
22457
22458        final String volumeUuid = pkg.volumeUuid;
22459        final String packageName = pkg.packageName;
22460        final ApplicationInfo app = pkg.applicationInfo;
22461        final int appId = UserHandle.getAppId(app.uid);
22462
22463        Preconditions.checkNotNull(app.seInfo);
22464
22465        long ceDataInode = -1;
22466        try {
22467            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22468                    appId, app.seInfo, app.targetSdkVersion);
22469        } catch (InstallerException e) {
22470            if (app.isSystemApp()) {
22471                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22472                        + ", but trying to recover: " + e);
22473                destroyAppDataLeafLIF(pkg, userId, flags);
22474                try {
22475                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22476                            appId, app.seInfo, app.targetSdkVersion);
22477                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22478                } catch (InstallerException e2) {
22479                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22480                }
22481            } else {
22482                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22483            }
22484        }
22485
22486        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22487            // TODO: mark this structure as dirty so we persist it!
22488            synchronized (mPackages) {
22489                final PackageSetting ps = mSettings.mPackages.get(packageName);
22490                if (ps != null) {
22491                    ps.setCeDataInode(ceDataInode, userId);
22492                }
22493            }
22494        }
22495
22496        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22497    }
22498
22499    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22500        if (pkg == null) {
22501            Slog.wtf(TAG, "Package was null!", new Throwable());
22502            return;
22503        }
22504        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22505        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22506        for (int i = 0; i < childCount; i++) {
22507            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22508        }
22509    }
22510
22511    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22512        final String volumeUuid = pkg.volumeUuid;
22513        final String packageName = pkg.packageName;
22514        final ApplicationInfo app = pkg.applicationInfo;
22515
22516        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22517            // Create a native library symlink only if we have native libraries
22518            // and if the native libraries are 32 bit libraries. We do not provide
22519            // this symlink for 64 bit libraries.
22520            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22521                final String nativeLibPath = app.nativeLibraryDir;
22522                try {
22523                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22524                            nativeLibPath, userId);
22525                } catch (InstallerException e) {
22526                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22527                }
22528            }
22529        }
22530    }
22531
22532    /**
22533     * For system apps on non-FBE devices, this method migrates any existing
22534     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22535     * requested by the app.
22536     */
22537    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22538        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22539                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22540            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22541                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22542            try {
22543                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22544                        storageTarget);
22545            } catch (InstallerException e) {
22546                logCriticalInfo(Log.WARN,
22547                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22548            }
22549            return true;
22550        } else {
22551            return false;
22552        }
22553    }
22554
22555    public PackageFreezer freezePackage(String packageName, String killReason) {
22556        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22557    }
22558
22559    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22560        return new PackageFreezer(packageName, userId, killReason);
22561    }
22562
22563    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22564            String killReason) {
22565        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22566    }
22567
22568    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22569            String killReason) {
22570        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22571            return new PackageFreezer();
22572        } else {
22573            return freezePackage(packageName, userId, killReason);
22574        }
22575    }
22576
22577    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22578            String killReason) {
22579        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22580    }
22581
22582    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22583            String killReason) {
22584        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22585            return new PackageFreezer();
22586        } else {
22587            return freezePackage(packageName, userId, killReason);
22588        }
22589    }
22590
22591    /**
22592     * Class that freezes and kills the given package upon creation, and
22593     * unfreezes it upon closing. This is typically used when doing surgery on
22594     * app code/data to prevent the app from running while you're working.
22595     */
22596    private class PackageFreezer implements AutoCloseable {
22597        private final String mPackageName;
22598        private final PackageFreezer[] mChildren;
22599
22600        private final boolean mWeFroze;
22601
22602        private final AtomicBoolean mClosed = new AtomicBoolean();
22603        private final CloseGuard mCloseGuard = CloseGuard.get();
22604
22605        /**
22606         * Create and return a stub freezer that doesn't actually do anything,
22607         * typically used when someone requested
22608         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22609         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22610         */
22611        public PackageFreezer() {
22612            mPackageName = null;
22613            mChildren = null;
22614            mWeFroze = false;
22615            mCloseGuard.open("close");
22616        }
22617
22618        public PackageFreezer(String packageName, int userId, String killReason) {
22619            synchronized (mPackages) {
22620                mPackageName = packageName;
22621                mWeFroze = mFrozenPackages.add(mPackageName);
22622
22623                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22624                if (ps != null) {
22625                    killApplication(ps.name, ps.appId, userId, killReason);
22626                }
22627
22628                final PackageParser.Package p = mPackages.get(packageName);
22629                if (p != null && p.childPackages != null) {
22630                    final int N = p.childPackages.size();
22631                    mChildren = new PackageFreezer[N];
22632                    for (int i = 0; i < N; i++) {
22633                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22634                                userId, killReason);
22635                    }
22636                } else {
22637                    mChildren = null;
22638                }
22639            }
22640            mCloseGuard.open("close");
22641        }
22642
22643        @Override
22644        protected void finalize() throws Throwable {
22645            try {
22646                mCloseGuard.warnIfOpen();
22647                close();
22648            } finally {
22649                super.finalize();
22650            }
22651        }
22652
22653        @Override
22654        public void close() {
22655            mCloseGuard.close();
22656            if (mClosed.compareAndSet(false, true)) {
22657                synchronized (mPackages) {
22658                    if (mWeFroze) {
22659                        mFrozenPackages.remove(mPackageName);
22660                    }
22661
22662                    if (mChildren != null) {
22663                        for (PackageFreezer freezer : mChildren) {
22664                            freezer.close();
22665                        }
22666                    }
22667                }
22668            }
22669        }
22670    }
22671
22672    /**
22673     * Verify that given package is currently frozen.
22674     */
22675    private void checkPackageFrozen(String packageName) {
22676        synchronized (mPackages) {
22677            if (!mFrozenPackages.contains(packageName)) {
22678                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22679            }
22680        }
22681    }
22682
22683    @Override
22684    public int movePackage(final String packageName, final String volumeUuid) {
22685        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22686
22687        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22688        final int moveId = mNextMoveId.getAndIncrement();
22689        mHandler.post(new Runnable() {
22690            @Override
22691            public void run() {
22692                try {
22693                    movePackageInternal(packageName, volumeUuid, moveId, user);
22694                } catch (PackageManagerException e) {
22695                    Slog.w(TAG, "Failed to move " + packageName, e);
22696                    mMoveCallbacks.notifyStatusChanged(moveId,
22697                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22698                }
22699            }
22700        });
22701        return moveId;
22702    }
22703
22704    private void movePackageInternal(final String packageName, final String volumeUuid,
22705            final int moveId, UserHandle user) throws PackageManagerException {
22706        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22707        final PackageManager pm = mContext.getPackageManager();
22708
22709        final boolean currentAsec;
22710        final String currentVolumeUuid;
22711        final File codeFile;
22712        final String installerPackageName;
22713        final String packageAbiOverride;
22714        final int appId;
22715        final String seinfo;
22716        final String label;
22717        final int targetSdkVersion;
22718        final PackageFreezer freezer;
22719        final int[] installedUserIds;
22720
22721        // reader
22722        synchronized (mPackages) {
22723            final PackageParser.Package pkg = mPackages.get(packageName);
22724            final PackageSetting ps = mSettings.mPackages.get(packageName);
22725            if (pkg == null || ps == null) {
22726                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22727            }
22728
22729            if (pkg.applicationInfo.isSystemApp()) {
22730                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22731                        "Cannot move system application");
22732            }
22733
22734            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22735            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22736                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22737            if (isInternalStorage && !allow3rdPartyOnInternal) {
22738                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22739                        "3rd party apps are not allowed on internal storage");
22740            }
22741
22742            if (pkg.applicationInfo.isExternalAsec()) {
22743                currentAsec = true;
22744                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22745            } else if (pkg.applicationInfo.isForwardLocked()) {
22746                currentAsec = true;
22747                currentVolumeUuid = "forward_locked";
22748            } else {
22749                currentAsec = false;
22750                currentVolumeUuid = ps.volumeUuid;
22751
22752                final File probe = new File(pkg.codePath);
22753                final File probeOat = new File(probe, "oat");
22754                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22755                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22756                            "Move only supported for modern cluster style installs");
22757                }
22758            }
22759
22760            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22761                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22762                        "Package already moved to " + volumeUuid);
22763            }
22764            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22765                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22766                        "Device admin cannot be moved");
22767            }
22768
22769            if (mFrozenPackages.contains(packageName)) {
22770                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22771                        "Failed to move already frozen package");
22772            }
22773
22774            codeFile = new File(pkg.codePath);
22775            installerPackageName = ps.installerPackageName;
22776            packageAbiOverride = ps.cpuAbiOverrideString;
22777            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22778            seinfo = pkg.applicationInfo.seInfo;
22779            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22780            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22781            freezer = freezePackage(packageName, "movePackageInternal");
22782            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22783        }
22784
22785        final Bundle extras = new Bundle();
22786        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22787        extras.putString(Intent.EXTRA_TITLE, label);
22788        mMoveCallbacks.notifyCreated(moveId, extras);
22789
22790        int installFlags;
22791        final boolean moveCompleteApp;
22792        final File measurePath;
22793
22794        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22795            installFlags = INSTALL_INTERNAL;
22796            moveCompleteApp = !currentAsec;
22797            measurePath = Environment.getDataAppDirectory(volumeUuid);
22798        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22799            installFlags = INSTALL_EXTERNAL;
22800            moveCompleteApp = false;
22801            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22802        } else {
22803            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22804            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22805                    || !volume.isMountedWritable()) {
22806                freezer.close();
22807                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22808                        "Move location not mounted private volume");
22809            }
22810
22811            Preconditions.checkState(!currentAsec);
22812
22813            installFlags = INSTALL_INTERNAL;
22814            moveCompleteApp = true;
22815            measurePath = Environment.getDataAppDirectory(volumeUuid);
22816        }
22817
22818        final PackageStats stats = new PackageStats(null, -1);
22819        synchronized (mInstaller) {
22820            for (int userId : installedUserIds) {
22821                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22822                    freezer.close();
22823                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22824                            "Failed to measure package size");
22825                }
22826            }
22827        }
22828
22829        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22830                + stats.dataSize);
22831
22832        final long startFreeBytes = measurePath.getUsableSpace();
22833        final long sizeBytes;
22834        if (moveCompleteApp) {
22835            sizeBytes = stats.codeSize + stats.dataSize;
22836        } else {
22837            sizeBytes = stats.codeSize;
22838        }
22839
22840        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22841            freezer.close();
22842            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22843                    "Not enough free space to move");
22844        }
22845
22846        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22847
22848        final CountDownLatch installedLatch = new CountDownLatch(1);
22849        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22850            @Override
22851            public void onUserActionRequired(Intent intent) throws RemoteException {
22852                throw new IllegalStateException();
22853            }
22854
22855            @Override
22856            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22857                    Bundle extras) throws RemoteException {
22858                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22859                        + PackageManager.installStatusToString(returnCode, msg));
22860
22861                installedLatch.countDown();
22862                freezer.close();
22863
22864                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22865                switch (status) {
22866                    case PackageInstaller.STATUS_SUCCESS:
22867                        mMoveCallbacks.notifyStatusChanged(moveId,
22868                                PackageManager.MOVE_SUCCEEDED);
22869                        break;
22870                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22871                        mMoveCallbacks.notifyStatusChanged(moveId,
22872                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22873                        break;
22874                    default:
22875                        mMoveCallbacks.notifyStatusChanged(moveId,
22876                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22877                        break;
22878                }
22879            }
22880        };
22881
22882        final MoveInfo move;
22883        if (moveCompleteApp) {
22884            // Kick off a thread to report progress estimates
22885            new Thread() {
22886                @Override
22887                public void run() {
22888                    while (true) {
22889                        try {
22890                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22891                                break;
22892                            }
22893                        } catch (InterruptedException ignored) {
22894                        }
22895
22896                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22897                        final int progress = 10 + (int) MathUtils.constrain(
22898                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22899                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22900                    }
22901                }
22902            }.start();
22903
22904            final String dataAppName = codeFile.getName();
22905            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22906                    dataAppName, appId, seinfo, targetSdkVersion);
22907        } else {
22908            move = null;
22909        }
22910
22911        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22912
22913        final Message msg = mHandler.obtainMessage(INIT_COPY);
22914        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22915        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22916                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22917                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22918                PackageManager.INSTALL_REASON_UNKNOWN);
22919        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22920        msg.obj = params;
22921
22922        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22923                System.identityHashCode(msg.obj));
22924        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22925                System.identityHashCode(msg.obj));
22926
22927        mHandler.sendMessage(msg);
22928    }
22929
22930    @Override
22931    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22932        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22933
22934        final int realMoveId = mNextMoveId.getAndIncrement();
22935        final Bundle extras = new Bundle();
22936        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22937        mMoveCallbacks.notifyCreated(realMoveId, extras);
22938
22939        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22940            @Override
22941            public void onCreated(int moveId, Bundle extras) {
22942                // Ignored
22943            }
22944
22945            @Override
22946            public void onStatusChanged(int moveId, int status, long estMillis) {
22947                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22948            }
22949        };
22950
22951        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22952        storage.setPrimaryStorageUuid(volumeUuid, callback);
22953        return realMoveId;
22954    }
22955
22956    @Override
22957    public int getMoveStatus(int moveId) {
22958        mContext.enforceCallingOrSelfPermission(
22959                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22960        return mMoveCallbacks.mLastStatus.get(moveId);
22961    }
22962
22963    @Override
22964    public void registerMoveCallback(IPackageMoveObserver callback) {
22965        mContext.enforceCallingOrSelfPermission(
22966                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22967        mMoveCallbacks.register(callback);
22968    }
22969
22970    @Override
22971    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22972        mContext.enforceCallingOrSelfPermission(
22973                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22974        mMoveCallbacks.unregister(callback);
22975    }
22976
22977    @Override
22978    public boolean setInstallLocation(int loc) {
22979        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22980                null);
22981        if (getInstallLocation() == loc) {
22982            return true;
22983        }
22984        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22985                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22986            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22987                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22988            return true;
22989        }
22990        return false;
22991   }
22992
22993    @Override
22994    public int getInstallLocation() {
22995        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22996                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22997                PackageHelper.APP_INSTALL_AUTO);
22998    }
22999
23000    /** Called by UserManagerService */
23001    void cleanUpUser(UserManagerService userManager, int userHandle) {
23002        synchronized (mPackages) {
23003            mDirtyUsers.remove(userHandle);
23004            mUserNeedsBadging.delete(userHandle);
23005            mSettings.removeUserLPw(userHandle);
23006            mPendingBroadcasts.remove(userHandle);
23007            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23008            removeUnusedPackagesLPw(userManager, userHandle);
23009        }
23010    }
23011
23012    /**
23013     * We're removing userHandle and would like to remove any downloaded packages
23014     * that are no longer in use by any other user.
23015     * @param userHandle the user being removed
23016     */
23017    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23018        final boolean DEBUG_CLEAN_APKS = false;
23019        int [] users = userManager.getUserIds();
23020        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23021        while (psit.hasNext()) {
23022            PackageSetting ps = psit.next();
23023            if (ps.pkg == null) {
23024                continue;
23025            }
23026            final String packageName = ps.pkg.packageName;
23027            // Skip over if system app
23028            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23029                continue;
23030            }
23031            if (DEBUG_CLEAN_APKS) {
23032                Slog.i(TAG, "Checking package " + packageName);
23033            }
23034            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23035            if (keep) {
23036                if (DEBUG_CLEAN_APKS) {
23037                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23038                }
23039            } else {
23040                for (int i = 0; i < users.length; i++) {
23041                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23042                        keep = true;
23043                        if (DEBUG_CLEAN_APKS) {
23044                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23045                                    + users[i]);
23046                        }
23047                        break;
23048                    }
23049                }
23050            }
23051            if (!keep) {
23052                if (DEBUG_CLEAN_APKS) {
23053                    Slog.i(TAG, "  Removing package " + packageName);
23054                }
23055                mHandler.post(new Runnable() {
23056                    public void run() {
23057                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23058                                userHandle, 0);
23059                    } //end run
23060                });
23061            }
23062        }
23063    }
23064
23065    /** Called by UserManagerService */
23066    void createNewUser(int userId, String[] disallowedPackages) {
23067        synchronized (mInstallLock) {
23068            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23069        }
23070        synchronized (mPackages) {
23071            scheduleWritePackageRestrictionsLocked(userId);
23072            scheduleWritePackageListLocked(userId);
23073            applyFactoryDefaultBrowserLPw(userId);
23074            primeDomainVerificationsLPw(userId);
23075        }
23076    }
23077
23078    void onNewUserCreated(final int userId) {
23079        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23080        // If permission review for legacy apps is required, we represent
23081        // dagerous permissions for such apps as always granted runtime
23082        // permissions to keep per user flag state whether review is needed.
23083        // Hence, if a new user is added we have to propagate dangerous
23084        // permission grants for these legacy apps.
23085        if (mPermissionReviewRequired) {
23086            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23087                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23088        }
23089    }
23090
23091    @Override
23092    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23093        mContext.enforceCallingOrSelfPermission(
23094                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23095                "Only package verification agents can read the verifier device identity");
23096
23097        synchronized (mPackages) {
23098            return mSettings.getVerifierDeviceIdentityLPw();
23099        }
23100    }
23101
23102    @Override
23103    public void setPermissionEnforced(String permission, boolean enforced) {
23104        // TODO: Now that we no longer change GID for storage, this should to away.
23105        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23106                "setPermissionEnforced");
23107        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23108            synchronized (mPackages) {
23109                if (mSettings.mReadExternalStorageEnforced == null
23110                        || mSettings.mReadExternalStorageEnforced != enforced) {
23111                    mSettings.mReadExternalStorageEnforced = enforced;
23112                    mSettings.writeLPr();
23113                }
23114            }
23115            // kill any non-foreground processes so we restart them and
23116            // grant/revoke the GID.
23117            final IActivityManager am = ActivityManager.getService();
23118            if (am != null) {
23119                final long token = Binder.clearCallingIdentity();
23120                try {
23121                    am.killProcessesBelowForeground("setPermissionEnforcement");
23122                } catch (RemoteException e) {
23123                } finally {
23124                    Binder.restoreCallingIdentity(token);
23125                }
23126            }
23127        } else {
23128            throw new IllegalArgumentException("No selective enforcement for " + permission);
23129        }
23130    }
23131
23132    @Override
23133    @Deprecated
23134    public boolean isPermissionEnforced(String permission) {
23135        return true;
23136    }
23137
23138    @Override
23139    public boolean isStorageLow() {
23140        final long token = Binder.clearCallingIdentity();
23141        try {
23142            final DeviceStorageMonitorInternal
23143                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23144            if (dsm != null) {
23145                return dsm.isMemoryLow();
23146            } else {
23147                return false;
23148            }
23149        } finally {
23150            Binder.restoreCallingIdentity(token);
23151        }
23152    }
23153
23154    @Override
23155    public IPackageInstaller getPackageInstaller() {
23156        return mInstallerService;
23157    }
23158
23159    private boolean userNeedsBadging(int userId) {
23160        int index = mUserNeedsBadging.indexOfKey(userId);
23161        if (index < 0) {
23162            final UserInfo userInfo;
23163            final long token = Binder.clearCallingIdentity();
23164            try {
23165                userInfo = sUserManager.getUserInfo(userId);
23166            } finally {
23167                Binder.restoreCallingIdentity(token);
23168            }
23169            final boolean b;
23170            if (userInfo != null && userInfo.isManagedProfile()) {
23171                b = true;
23172            } else {
23173                b = false;
23174            }
23175            mUserNeedsBadging.put(userId, b);
23176            return b;
23177        }
23178        return mUserNeedsBadging.valueAt(index);
23179    }
23180
23181    @Override
23182    public KeySet getKeySetByAlias(String packageName, String alias) {
23183        if (packageName == null || alias == null) {
23184            return null;
23185        }
23186        synchronized(mPackages) {
23187            final PackageParser.Package pkg = mPackages.get(packageName);
23188            if (pkg == null) {
23189                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23190                throw new IllegalArgumentException("Unknown package: " + packageName);
23191            }
23192            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23193            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23194        }
23195    }
23196
23197    @Override
23198    public KeySet getSigningKeySet(String packageName) {
23199        if (packageName == null) {
23200            return null;
23201        }
23202        synchronized(mPackages) {
23203            final PackageParser.Package pkg = mPackages.get(packageName);
23204            if (pkg == null) {
23205                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23206                throw new IllegalArgumentException("Unknown package: " + packageName);
23207            }
23208            if (pkg.applicationInfo.uid != Binder.getCallingUid()
23209                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
23210                throw new SecurityException("May not access signing KeySet of other apps.");
23211            }
23212            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23213            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23214        }
23215    }
23216
23217    @Override
23218    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23219        if (packageName == null || ks == null) {
23220            return false;
23221        }
23222        synchronized(mPackages) {
23223            final PackageParser.Package pkg = mPackages.get(packageName);
23224            if (pkg == null) {
23225                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23226                throw new IllegalArgumentException("Unknown package: " + packageName);
23227            }
23228            IBinder ksh = ks.getToken();
23229            if (ksh instanceof KeySetHandle) {
23230                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23231                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23232            }
23233            return false;
23234        }
23235    }
23236
23237    @Override
23238    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23239        if (packageName == null || ks == null) {
23240            return false;
23241        }
23242        synchronized(mPackages) {
23243            final PackageParser.Package pkg = mPackages.get(packageName);
23244            if (pkg == null) {
23245                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23246                throw new IllegalArgumentException("Unknown package: " + packageName);
23247            }
23248            IBinder ksh = ks.getToken();
23249            if (ksh instanceof KeySetHandle) {
23250                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23251                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23252            }
23253            return false;
23254        }
23255    }
23256
23257    private void deletePackageIfUnusedLPr(final String packageName) {
23258        PackageSetting ps = mSettings.mPackages.get(packageName);
23259        if (ps == null) {
23260            return;
23261        }
23262        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23263            // TODO Implement atomic delete if package is unused
23264            // It is currently possible that the package will be deleted even if it is installed
23265            // after this method returns.
23266            mHandler.post(new Runnable() {
23267                public void run() {
23268                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23269                            0, PackageManager.DELETE_ALL_USERS);
23270                }
23271            });
23272        }
23273    }
23274
23275    /**
23276     * Check and throw if the given before/after packages would be considered a
23277     * downgrade.
23278     */
23279    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23280            throws PackageManagerException {
23281        if (after.versionCode < before.mVersionCode) {
23282            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23283                    "Update version code " + after.versionCode + " is older than current "
23284                    + before.mVersionCode);
23285        } else if (after.versionCode == before.mVersionCode) {
23286            if (after.baseRevisionCode < before.baseRevisionCode) {
23287                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23288                        "Update base revision code " + after.baseRevisionCode
23289                        + " is older than current " + before.baseRevisionCode);
23290            }
23291
23292            if (!ArrayUtils.isEmpty(after.splitNames)) {
23293                for (int i = 0; i < after.splitNames.length; i++) {
23294                    final String splitName = after.splitNames[i];
23295                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23296                    if (j != -1) {
23297                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23298                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23299                                    "Update split " + splitName + " revision code "
23300                                    + after.splitRevisionCodes[i] + " is older than current "
23301                                    + before.splitRevisionCodes[j]);
23302                        }
23303                    }
23304                }
23305            }
23306        }
23307    }
23308
23309    private static class MoveCallbacks extends Handler {
23310        private static final int MSG_CREATED = 1;
23311        private static final int MSG_STATUS_CHANGED = 2;
23312
23313        private final RemoteCallbackList<IPackageMoveObserver>
23314                mCallbacks = new RemoteCallbackList<>();
23315
23316        private final SparseIntArray mLastStatus = new SparseIntArray();
23317
23318        public MoveCallbacks(Looper looper) {
23319            super(looper);
23320        }
23321
23322        public void register(IPackageMoveObserver callback) {
23323            mCallbacks.register(callback);
23324        }
23325
23326        public void unregister(IPackageMoveObserver callback) {
23327            mCallbacks.unregister(callback);
23328        }
23329
23330        @Override
23331        public void handleMessage(Message msg) {
23332            final SomeArgs args = (SomeArgs) msg.obj;
23333            final int n = mCallbacks.beginBroadcast();
23334            for (int i = 0; i < n; i++) {
23335                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23336                try {
23337                    invokeCallback(callback, msg.what, args);
23338                } catch (RemoteException ignored) {
23339                }
23340            }
23341            mCallbacks.finishBroadcast();
23342            args.recycle();
23343        }
23344
23345        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23346                throws RemoteException {
23347            switch (what) {
23348                case MSG_CREATED: {
23349                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23350                    break;
23351                }
23352                case MSG_STATUS_CHANGED: {
23353                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23354                    break;
23355                }
23356            }
23357        }
23358
23359        private void notifyCreated(int moveId, Bundle extras) {
23360            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23361
23362            final SomeArgs args = SomeArgs.obtain();
23363            args.argi1 = moveId;
23364            args.arg2 = extras;
23365            obtainMessage(MSG_CREATED, args).sendToTarget();
23366        }
23367
23368        private void notifyStatusChanged(int moveId, int status) {
23369            notifyStatusChanged(moveId, status, -1);
23370        }
23371
23372        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23373            Slog.v(TAG, "Move " + moveId + " status " + status);
23374
23375            final SomeArgs args = SomeArgs.obtain();
23376            args.argi1 = moveId;
23377            args.argi2 = status;
23378            args.arg3 = estMillis;
23379            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23380
23381            synchronized (mLastStatus) {
23382                mLastStatus.put(moveId, status);
23383            }
23384        }
23385    }
23386
23387    private final static class OnPermissionChangeListeners extends Handler {
23388        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23389
23390        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23391                new RemoteCallbackList<>();
23392
23393        public OnPermissionChangeListeners(Looper looper) {
23394            super(looper);
23395        }
23396
23397        @Override
23398        public void handleMessage(Message msg) {
23399            switch (msg.what) {
23400                case MSG_ON_PERMISSIONS_CHANGED: {
23401                    final int uid = msg.arg1;
23402                    handleOnPermissionsChanged(uid);
23403                } break;
23404            }
23405        }
23406
23407        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23408            mPermissionListeners.register(listener);
23409
23410        }
23411
23412        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23413            mPermissionListeners.unregister(listener);
23414        }
23415
23416        public void onPermissionsChanged(int uid) {
23417            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23418                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23419            }
23420        }
23421
23422        private void handleOnPermissionsChanged(int uid) {
23423            final int count = mPermissionListeners.beginBroadcast();
23424            try {
23425                for (int i = 0; i < count; i++) {
23426                    IOnPermissionsChangeListener callback = mPermissionListeners
23427                            .getBroadcastItem(i);
23428                    try {
23429                        callback.onPermissionsChanged(uid);
23430                    } catch (RemoteException e) {
23431                        Log.e(TAG, "Permission listener is dead", e);
23432                    }
23433                }
23434            } finally {
23435                mPermissionListeners.finishBroadcast();
23436            }
23437        }
23438    }
23439
23440    private class PackageManagerInternalImpl extends PackageManagerInternal {
23441        @Override
23442        public void setLocationPackagesProvider(PackagesProvider provider) {
23443            synchronized (mPackages) {
23444                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
23445            }
23446        }
23447
23448        @Override
23449        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23450            synchronized (mPackages) {
23451                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
23452            }
23453        }
23454
23455        @Override
23456        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23457            synchronized (mPackages) {
23458                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
23459            }
23460        }
23461
23462        @Override
23463        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23464            synchronized (mPackages) {
23465                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
23466            }
23467        }
23468
23469        @Override
23470        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23471            synchronized (mPackages) {
23472                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
23473            }
23474        }
23475
23476        @Override
23477        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23478            synchronized (mPackages) {
23479                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
23480            }
23481        }
23482
23483        @Override
23484        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23485            synchronized (mPackages) {
23486                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
23487                        packageName, userId);
23488            }
23489        }
23490
23491        @Override
23492        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23493            synchronized (mPackages) {
23494                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23495                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
23496                        packageName, userId);
23497            }
23498        }
23499
23500        @Override
23501        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23502            synchronized (mPackages) {
23503                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
23504                        packageName, userId);
23505            }
23506        }
23507
23508        @Override
23509        public void setKeepUninstalledPackages(final List<String> packageList) {
23510            Preconditions.checkNotNull(packageList);
23511            List<String> removedFromList = null;
23512            synchronized (mPackages) {
23513                if (mKeepUninstalledPackages != null) {
23514                    final int packagesCount = mKeepUninstalledPackages.size();
23515                    for (int i = 0; i < packagesCount; i++) {
23516                        String oldPackage = mKeepUninstalledPackages.get(i);
23517                        if (packageList != null && packageList.contains(oldPackage)) {
23518                            continue;
23519                        }
23520                        if (removedFromList == null) {
23521                            removedFromList = new ArrayList<>();
23522                        }
23523                        removedFromList.add(oldPackage);
23524                    }
23525                }
23526                mKeepUninstalledPackages = new ArrayList<>(packageList);
23527                if (removedFromList != null) {
23528                    final int removedCount = removedFromList.size();
23529                    for (int i = 0; i < removedCount; i++) {
23530                        deletePackageIfUnusedLPr(removedFromList.get(i));
23531                    }
23532                }
23533            }
23534        }
23535
23536        @Override
23537        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23538            synchronized (mPackages) {
23539                // If we do not support permission review, done.
23540                if (!mPermissionReviewRequired) {
23541                    return false;
23542                }
23543
23544                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23545                if (packageSetting == null) {
23546                    return false;
23547                }
23548
23549                // Permission review applies only to apps not supporting the new permission model.
23550                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23551                    return false;
23552                }
23553
23554                // Legacy apps have the permission and get user consent on launch.
23555                PermissionsState permissionsState = packageSetting.getPermissionsState();
23556                return permissionsState.isPermissionReviewRequired(userId);
23557            }
23558        }
23559
23560        @Override
23561        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
23562            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
23563        }
23564
23565        @Override
23566        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23567                int userId) {
23568            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23569        }
23570
23571        @Override
23572        public void setDeviceAndProfileOwnerPackages(
23573                int deviceOwnerUserId, String deviceOwnerPackage,
23574                SparseArray<String> profileOwnerPackages) {
23575            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23576                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23577        }
23578
23579        @Override
23580        public boolean isPackageDataProtected(int userId, String packageName) {
23581            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23582        }
23583
23584        @Override
23585        public boolean isPackageEphemeral(int userId, String packageName) {
23586            synchronized (mPackages) {
23587                final PackageSetting ps = mSettings.mPackages.get(packageName);
23588                return ps != null ? ps.getInstantApp(userId) : false;
23589            }
23590        }
23591
23592        @Override
23593        public boolean wasPackageEverLaunched(String packageName, int userId) {
23594            synchronized (mPackages) {
23595                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23596            }
23597        }
23598
23599        @Override
23600        public void grantRuntimePermission(String packageName, String name, int userId,
23601                boolean overridePolicy) {
23602            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23603                    overridePolicy);
23604        }
23605
23606        @Override
23607        public void revokeRuntimePermission(String packageName, String name, int userId,
23608                boolean overridePolicy) {
23609            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23610                    overridePolicy);
23611        }
23612
23613        @Override
23614        public String getNameForUid(int uid) {
23615            return PackageManagerService.this.getNameForUid(uid);
23616        }
23617
23618        @Override
23619        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23620                Intent origIntent, String resolvedType, String callingPackage,
23621                Bundle verificationBundle, int userId) {
23622            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23623                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23624                    userId);
23625        }
23626
23627        @Override
23628        public void grantEphemeralAccess(int userId, Intent intent,
23629                int targetAppId, int ephemeralAppId) {
23630            synchronized (mPackages) {
23631                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23632                        targetAppId, ephemeralAppId);
23633            }
23634        }
23635
23636        @Override
23637        public boolean isInstantAppInstallerComponent(ComponentName component) {
23638            synchronized (mPackages) {
23639                return mInstantAppInstallerActivity != null
23640                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23641            }
23642        }
23643
23644        @Override
23645        public void pruneInstantApps() {
23646            synchronized (mPackages) {
23647                mInstantAppRegistry.pruneInstantAppsLPw();
23648            }
23649        }
23650
23651        @Override
23652        public String getSetupWizardPackageName() {
23653            return mSetupWizardPackage;
23654        }
23655
23656        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23657            if (policy != null) {
23658                mExternalSourcesPolicy = policy;
23659            }
23660        }
23661
23662        @Override
23663        public boolean isPackagePersistent(String packageName) {
23664            synchronized (mPackages) {
23665                PackageParser.Package pkg = mPackages.get(packageName);
23666                return pkg != null
23667                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23668                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23669                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23670                        : false;
23671            }
23672        }
23673
23674        @Override
23675        public List<PackageInfo> getOverlayPackages(int userId) {
23676            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23677            synchronized (mPackages) {
23678                for (PackageParser.Package p : mPackages.values()) {
23679                    if (p.mOverlayTarget != null) {
23680                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23681                        if (pkg != null) {
23682                            overlayPackages.add(pkg);
23683                        }
23684                    }
23685                }
23686            }
23687            return overlayPackages;
23688        }
23689
23690        @Override
23691        public List<String> getTargetPackageNames(int userId) {
23692            List<String> targetPackages = new ArrayList<>();
23693            synchronized (mPackages) {
23694                for (PackageParser.Package p : mPackages.values()) {
23695                    if (p.mOverlayTarget == null) {
23696                        targetPackages.add(p.packageName);
23697                    }
23698                }
23699            }
23700            return targetPackages;
23701        }
23702
23703        @Override
23704        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23705                @Nullable List<String> overlayPackageNames) {
23706            synchronized (mPackages) {
23707                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23708                    Slog.e(TAG, "failed to find package " + targetPackageName);
23709                    return false;
23710                }
23711
23712                ArrayList<String> paths = null;
23713                if (overlayPackageNames != null) {
23714                    final int N = overlayPackageNames.size();
23715                    paths = new ArrayList<>(N);
23716                    for (int i = 0; i < N; i++) {
23717                        final String packageName = overlayPackageNames.get(i);
23718                        final PackageParser.Package pkg = mPackages.get(packageName);
23719                        if (pkg == null) {
23720                            Slog.e(TAG, "failed to find package " + packageName);
23721                            return false;
23722                        }
23723                        paths.add(pkg.baseCodePath);
23724                    }
23725                }
23726
23727                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23728                    mEnabledOverlayPaths.get(userId);
23729                if (userSpecificOverlays == null) {
23730                    userSpecificOverlays = new ArrayMap<>();
23731                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23732                }
23733
23734                if (paths != null && paths.size() > 0) {
23735                    userSpecificOverlays.put(targetPackageName, paths);
23736                } else {
23737                    userSpecificOverlays.remove(targetPackageName);
23738                }
23739                return true;
23740            }
23741        }
23742
23743        @Override
23744        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23745                int flags, int userId) {
23746            return resolveIntentInternal(
23747                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
23748        }
23749
23750        @Override
23751        public ResolveInfo resolveService(Intent intent, String resolvedType,
23752                int flags, int userId, int callingUid) {
23753            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23754        }
23755
23756        @Override
23757        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23758            synchronized (mPackages) {
23759                mIsolatedOwners.put(isolatedUid, ownerUid);
23760            }
23761        }
23762
23763        @Override
23764        public void removeIsolatedUid(int isolatedUid) {
23765            synchronized (mPackages) {
23766                mIsolatedOwners.delete(isolatedUid);
23767            }
23768        }
23769
23770        @Override
23771        public int getUidTargetSdkVersion(int uid) {
23772            synchronized (mPackages) {
23773                return getUidTargetSdkVersionLockedLPr(uid);
23774            }
23775        }
23776    }
23777
23778    @Override
23779    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23780        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23781        synchronized (mPackages) {
23782            final long identity = Binder.clearCallingIdentity();
23783            try {
23784                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23785                        packageNames, userId);
23786            } finally {
23787                Binder.restoreCallingIdentity(identity);
23788            }
23789        }
23790    }
23791
23792    @Override
23793    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23794        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23795        synchronized (mPackages) {
23796            final long identity = Binder.clearCallingIdentity();
23797            try {
23798                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23799                        packageNames, userId);
23800            } finally {
23801                Binder.restoreCallingIdentity(identity);
23802            }
23803        }
23804    }
23805
23806    private static void enforceSystemOrPhoneCaller(String tag) {
23807        int callingUid = Binder.getCallingUid();
23808        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23809            throw new SecurityException(
23810                    "Cannot call " + tag + " from UID " + callingUid);
23811        }
23812    }
23813
23814    boolean isHistoricalPackageUsageAvailable() {
23815        return mPackageUsage.isHistoricalPackageUsageAvailable();
23816    }
23817
23818    /**
23819     * Return a <b>copy</b> of the collection of packages known to the package manager.
23820     * @return A copy of the values of mPackages.
23821     */
23822    Collection<PackageParser.Package> getPackages() {
23823        synchronized (mPackages) {
23824            return new ArrayList<>(mPackages.values());
23825        }
23826    }
23827
23828    /**
23829     * Logs process start information (including base APK hash) to the security log.
23830     * @hide
23831     */
23832    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23833            String apkFile, int pid) {
23834        if (!SecurityLog.isLoggingEnabled()) {
23835            return;
23836        }
23837        Bundle data = new Bundle();
23838        data.putLong("startTimestamp", System.currentTimeMillis());
23839        data.putString("processName", processName);
23840        data.putInt("uid", uid);
23841        data.putString("seinfo", seinfo);
23842        data.putString("apkFile", apkFile);
23843        data.putInt("pid", pid);
23844        Message msg = mProcessLoggingHandler.obtainMessage(
23845                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23846        msg.setData(data);
23847        mProcessLoggingHandler.sendMessage(msg);
23848    }
23849
23850    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23851        return mCompilerStats.getPackageStats(pkgName);
23852    }
23853
23854    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23855        return getOrCreateCompilerPackageStats(pkg.packageName);
23856    }
23857
23858    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23859        return mCompilerStats.getOrCreatePackageStats(pkgName);
23860    }
23861
23862    public void deleteCompilerPackageStats(String pkgName) {
23863        mCompilerStats.deletePackageStats(pkgName);
23864    }
23865
23866    @Override
23867    public int getInstallReason(String packageName, int userId) {
23868        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23869                true /* requireFullPermission */, false /* checkShell */,
23870                "get install reason");
23871        synchronized (mPackages) {
23872            final PackageSetting ps = mSettings.mPackages.get(packageName);
23873            if (ps != null) {
23874                return ps.getInstallReason(userId);
23875            }
23876        }
23877        return PackageManager.INSTALL_REASON_UNKNOWN;
23878    }
23879
23880    @Override
23881    public boolean canRequestPackageInstalls(String packageName, int userId) {
23882        int callingUid = Binder.getCallingUid();
23883        int uid = getPackageUid(packageName, 0, userId);
23884        if (callingUid != uid && callingUid != Process.ROOT_UID
23885                && callingUid != Process.SYSTEM_UID) {
23886            throw new SecurityException(
23887                    "Caller uid " + callingUid + " does not own package " + packageName);
23888        }
23889        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23890        if (info == null) {
23891            return false;
23892        }
23893        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23894            throw new UnsupportedOperationException(
23895                    "Operation only supported on apps targeting Android O or higher");
23896        }
23897        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23898        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23899        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23900            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23901        }
23902        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23903            return false;
23904        }
23905        if (mExternalSourcesPolicy != null) {
23906            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23907            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23908                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23909            }
23910        }
23911        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23912    }
23913
23914    @Override
23915    public ComponentName getInstantAppResolverSettingsComponent() {
23916        return mInstantAppResolverSettingsComponent;
23917    }
23918
23919    @Override
23920    public ComponentName getInstantAppInstallerComponent() {
23921        return mInstantAppInstallerActivity == null
23922                ? null : mInstantAppInstallerActivity.getComponentName();
23923    }
23924
23925    @Override
23926    public String getInstantAppAndroidId(String packageName, int userId) {
23927        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23928                "getInstantAppAndroidId");
23929        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23930                true /* requireFullPermission */, false /* checkShell */,
23931                "getInstantAppAndroidId");
23932        // Make sure the target is an Instant App.
23933        if (!isInstantApp(packageName, userId)) {
23934            return null;
23935        }
23936        synchronized (mPackages) {
23937            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23938        }
23939    }
23940}
23941
23942interface PackageSender {
23943    void sendPackageBroadcast(final String action, final String pkg,
23944        final Bundle extras, final int flags, final String targetPkg,
23945        final IIntentReceiver finishedReceiver, final int[] userIds);
23946    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
23947        int appId, int... userIds);
23948}
23949