PackageManagerService.java revision 7210f130dbd37dc42f65ade897d6e7e5a3b445c3
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.WRITE_EXTERNAL_STORAGE;
24import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
30import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
38import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
39import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
40import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
41import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
48import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
53import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
55import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
56import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
57import static android.content.pm.PackageManager.INSTALL_INTERNAL;
58import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
64import static android.content.pm.PackageManager.MATCH_ALL;
65import static android.content.pm.PackageManager.MATCH_ANY_USER;
66import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
67import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
69import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
70import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
71import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
72import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
73import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
74import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
75import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
76import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
77import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
78import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
79import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
80import static android.content.pm.PackageManager.PERMISSION_DENIED;
81import static android.content.pm.PackageManager.PERMISSION_GRANTED;
82import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
83import static android.content.pm.PackageParser.isApkFile;
84import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
85import static android.system.OsConstants.O_CREAT;
86import static android.system.OsConstants.O_RDWR;
87import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
89import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
90import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
91import static com.android.internal.util.ArrayUtils.appendInt;
92import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
95import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
96import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
102import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
103
104import android.Manifest;
105import android.annotation.NonNull;
106import android.annotation.Nullable;
107import android.app.ActivityManager;
108import android.app.AppOpsManager;
109import android.app.IActivityManager;
110import android.app.ResourcesManager;
111import android.app.admin.IDevicePolicyManager;
112import android.app.admin.SecurityLog;
113import android.app.backup.IBackupManager;
114import android.content.BroadcastReceiver;
115import android.content.ComponentName;
116import android.content.ContentResolver;
117import android.content.Context;
118import android.content.IIntentReceiver;
119import android.content.Intent;
120import android.content.IntentFilter;
121import android.content.IntentSender;
122import android.content.IntentSender.SendIntentException;
123import android.content.ServiceConnection;
124import android.content.pm.ActivityInfo;
125import android.content.pm.ApplicationInfo;
126import android.content.pm.AppsQueryHelper;
127import android.content.pm.AuxiliaryResolveInfo;
128import android.content.pm.ChangedPackages;
129import android.content.pm.FallbackCategoryProvider;
130import android.content.pm.FeatureInfo;
131import android.content.pm.IOnPermissionsChangeListener;
132import android.content.pm.IPackageDataObserver;
133import android.content.pm.IPackageDeleteObserver;
134import android.content.pm.IPackageDeleteObserver2;
135import android.content.pm.IPackageInstallObserver2;
136import android.content.pm.IPackageInstaller;
137import android.content.pm.IPackageManager;
138import android.content.pm.IPackageMoveObserver;
139import android.content.pm.IPackageStatsObserver;
140import android.content.pm.InstantAppInfo;
141import android.content.pm.InstantAppRequest;
142import android.content.pm.InstantAppResolveInfo;
143import android.content.pm.InstrumentationInfo;
144import android.content.pm.IntentFilterVerificationInfo;
145import android.content.pm.KeySet;
146import android.content.pm.PackageCleanItem;
147import android.content.pm.PackageInfo;
148import android.content.pm.PackageInfoLite;
149import android.content.pm.PackageInstaller;
150import android.content.pm.PackageManager;
151import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
152import android.content.pm.PackageManagerInternal;
153import android.content.pm.PackageParser;
154import android.content.pm.PackageParser.ActivityIntentInfo;
155import android.content.pm.PackageParser.PackageLite;
156import android.content.pm.PackageParser.PackageParserException;
157import android.content.pm.PackageStats;
158import android.content.pm.PackageUserState;
159import android.content.pm.ParceledListSlice;
160import android.content.pm.PermissionGroupInfo;
161import android.content.pm.PermissionInfo;
162import android.content.pm.ProviderInfo;
163import android.content.pm.ResolveInfo;
164import android.content.pm.ServiceInfo;
165import android.content.pm.SharedLibraryInfo;
166import android.content.pm.Signature;
167import android.content.pm.UserInfo;
168import android.content.pm.VerifierDeviceIdentity;
169import android.content.pm.VerifierInfo;
170import android.content.pm.VersionedPackage;
171import android.content.res.Resources;
172import android.database.ContentObserver;
173import android.graphics.Bitmap;
174import android.hardware.display.DisplayManager;
175import android.net.Uri;
176import android.os.Binder;
177import android.os.Build;
178import android.os.Bundle;
179import android.os.Debug;
180import android.os.Environment;
181import android.os.Environment.UserEnvironment;
182import android.os.FileUtils;
183import android.os.Handler;
184import android.os.IBinder;
185import android.os.Looper;
186import android.os.Message;
187import android.os.Parcel;
188import android.os.ParcelFileDescriptor;
189import android.os.PatternMatcher;
190import android.os.Process;
191import android.os.RemoteCallbackList;
192import android.os.RemoteException;
193import android.os.ResultReceiver;
194import android.os.SELinux;
195import android.os.ServiceManager;
196import android.os.ShellCallback;
197import android.os.SystemClock;
198import android.os.SystemProperties;
199import android.os.Trace;
200import android.os.UserHandle;
201import android.os.UserManager;
202import android.os.UserManagerInternal;
203import android.os.storage.IStorageManager;
204import android.os.storage.StorageEventListener;
205import android.os.storage.StorageManager;
206import android.os.storage.StorageManagerInternal;
207import android.os.storage.VolumeInfo;
208import android.os.storage.VolumeRecord;
209import android.provider.Settings.Global;
210import android.provider.Settings.Secure;
211import android.security.KeyStore;
212import android.security.SystemKeyStore;
213import android.service.pm.PackageServiceDumpProto;
214import android.system.ErrnoException;
215import android.system.Os;
216import android.text.TextUtils;
217import android.text.format.DateUtils;
218import android.util.ArrayMap;
219import android.util.ArraySet;
220import android.util.Base64;
221import android.util.BootTimingsTraceLog;
222import android.util.DisplayMetrics;
223import android.util.EventLog;
224import android.util.ExceptionUtils;
225import android.util.Log;
226import android.util.LogPrinter;
227import android.util.MathUtils;
228import android.util.PackageUtils;
229import android.util.Pair;
230import android.util.PrintStreamPrinter;
231import android.util.Slog;
232import android.util.SparseArray;
233import android.util.SparseBooleanArray;
234import android.util.SparseIntArray;
235import android.util.Xml;
236import android.util.jar.StrictJarFile;
237import android.util.proto.ProtoOutputStream;
238import android.view.Display;
239
240import com.android.internal.R;
241import com.android.internal.annotations.GuardedBy;
242import com.android.internal.app.IMediaContainerService;
243import com.android.internal.app.ResolverActivity;
244import com.android.internal.content.NativeLibraryHelper;
245import com.android.internal.content.PackageHelper;
246import com.android.internal.logging.MetricsLogger;
247import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
248import com.android.internal.os.IParcelFileDescriptorFactory;
249import com.android.internal.os.RoSystemProperties;
250import com.android.internal.os.SomeArgs;
251import com.android.internal.os.Zygote;
252import com.android.internal.telephony.CarrierAppUtils;
253import com.android.internal.util.ArrayUtils;
254import com.android.internal.util.ConcurrentUtils;
255import com.android.internal.util.DumpUtils;
256import com.android.internal.util.FastPrintWriter;
257import com.android.internal.util.FastXmlSerializer;
258import com.android.internal.util.IndentingPrintWriter;
259import com.android.internal.util.Preconditions;
260import com.android.internal.util.XmlUtils;
261import com.android.server.AttributeCache;
262import com.android.server.DeviceIdleController;
263import com.android.server.EventLogTags;
264import com.android.server.FgThread;
265import com.android.server.IntentResolver;
266import com.android.server.LocalServices;
267import com.android.server.LockGuard;
268import com.android.server.ServiceThread;
269import com.android.server.SystemConfig;
270import com.android.server.SystemServerInitThreadPool;
271import com.android.server.Watchdog;
272import com.android.server.net.NetworkPolicyManagerInternal;
273import com.android.server.pm.Installer.InstallerException;
274import com.android.server.pm.PermissionsState.PermissionState;
275import com.android.server.pm.Settings.DatabaseVersion;
276import com.android.server.pm.Settings.VersionInfo;
277import com.android.server.pm.dex.DexManager;
278import com.android.server.storage.DeviceStorageMonitorInternal;
279
280import dalvik.system.CloseGuard;
281import dalvik.system.DexFile;
282import dalvik.system.VMRuntime;
283
284import libcore.io.IoUtils;
285import libcore.util.EmptyArray;
286
287import org.xmlpull.v1.XmlPullParser;
288import org.xmlpull.v1.XmlPullParserException;
289import org.xmlpull.v1.XmlSerializer;
290
291import java.io.BufferedOutputStream;
292import java.io.BufferedReader;
293import java.io.ByteArrayInputStream;
294import java.io.ByteArrayOutputStream;
295import java.io.File;
296import java.io.FileDescriptor;
297import java.io.FileInputStream;
298import java.io.FileOutputStream;
299import java.io.FileReader;
300import java.io.FilenameFilter;
301import java.io.IOException;
302import java.io.PrintWriter;
303import java.nio.charset.StandardCharsets;
304import java.security.DigestInputStream;
305import java.security.MessageDigest;
306import java.security.NoSuchAlgorithmException;
307import java.security.PublicKey;
308import java.security.SecureRandom;
309import java.security.cert.Certificate;
310import java.security.cert.CertificateEncodingException;
311import java.security.cert.CertificateException;
312import java.text.SimpleDateFormat;
313import java.util.ArrayList;
314import java.util.Arrays;
315import java.util.Collection;
316import java.util.Collections;
317import java.util.Comparator;
318import java.util.Date;
319import java.util.HashMap;
320import java.util.HashSet;
321import java.util.Iterator;
322import java.util.List;
323import java.util.Map;
324import java.util.Objects;
325import java.util.Set;
326import java.util.concurrent.CountDownLatch;
327import java.util.concurrent.Future;
328import java.util.concurrent.TimeUnit;
329import java.util.concurrent.atomic.AtomicBoolean;
330import java.util.concurrent.atomic.AtomicInteger;
331
332/**
333 * Keep track of all those APKs everywhere.
334 * <p>
335 * Internally there are two important locks:
336 * <ul>
337 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
338 * and other related state. It is a fine-grained lock that should only be held
339 * momentarily, as it's one of the most contended locks in the system.
340 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
341 * operations typically involve heavy lifting of application data on disk. Since
342 * {@code installd} is single-threaded, and it's operations can often be slow,
343 * this lock should never be acquired while already holding {@link #mPackages}.
344 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
345 * holding {@link #mInstallLock}.
346 * </ul>
347 * Many internal methods rely on the caller to hold the appropriate locks, and
348 * this contract is expressed through method name suffixes:
349 * <ul>
350 * <li>fooLI(): the caller must hold {@link #mInstallLock}
351 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
352 * being modified must be frozen
353 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
354 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
355 * </ul>
356 * <p>
357 * Because this class is very central to the platform's security; please run all
358 * CTS and unit tests whenever making modifications:
359 *
360 * <pre>
361 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
362 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
363 * </pre>
364 */
365public class PackageManagerService extends IPackageManager.Stub
366        implements PackageSender {
367    static final String TAG = "PackageManager";
368    static final boolean DEBUG_SETTINGS = false;
369    static final boolean DEBUG_PREFERRED = false;
370    static final boolean DEBUG_UPGRADE = false;
371    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
372    private static final boolean DEBUG_BACKUP = false;
373    private static final boolean DEBUG_INSTALL = false;
374    private static final boolean DEBUG_REMOVE = false;
375    private static final boolean DEBUG_BROADCASTS = false;
376    private static final boolean DEBUG_SHOW_INFO = false;
377    private static final boolean DEBUG_PACKAGE_INFO = false;
378    private static final boolean DEBUG_INTENT_MATCHING = false;
379    private static final boolean DEBUG_PACKAGE_SCANNING = false;
380    private static final boolean DEBUG_VERIFY = false;
381    private static final boolean DEBUG_FILTERS = false;
382    private static final boolean DEBUG_PERMISSIONS = false;
383    private static final boolean DEBUG_SHARED_LIBRARIES = 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            // Remove the replaced package's older resources safely now
2027            // We delete after a gc for applications  on sdcard.
2028            if (res.removedInfo != null && res.removedInfo.args != null) {
2029                Runtime.getRuntime().gc();
2030                synchronized (mInstallLock) {
2031                    res.removedInfo.args.doPostDeleteLI(true);
2032                }
2033            } else {
2034                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2035                // and not block here.
2036                VMRuntime.getRuntime().requestConcurrentGC();
2037            }
2038
2039            // Notify DexManager that the package was installed for new users.
2040            // The updated users should already be indexed and the package code paths
2041            // should not change.
2042            // Don't notify the manager for ephemeral apps as they are not expected to
2043            // survive long enough to benefit of background optimizations.
2044            for (int userId : firstUsers) {
2045                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2046                // There's a race currently where some install events may interleave with an uninstall.
2047                // This can lead to package info being null (b/36642664).
2048                if (info != null) {
2049                    mDexManager.notifyPackageInstalled(info, userId);
2050                }
2051            }
2052        }
2053
2054        // If someone is watching installs - notify them
2055        if (installObserver != null) {
2056            try {
2057                Bundle extras = extrasForInstallResult(res);
2058                installObserver.onPackageInstalled(res.name, res.returnCode,
2059                        res.returnMsg, extras);
2060            } catch (RemoteException e) {
2061                Slog.i(TAG, "Observer no longer exists.");
2062            }
2063        }
2064    }
2065
2066    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2067            PackageParser.Package pkg) {
2068        if (pkg.parentPackage == null) {
2069            return;
2070        }
2071        if (pkg.requestedPermissions == null) {
2072            return;
2073        }
2074        final PackageSetting disabledSysParentPs = mSettings
2075                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2076        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2077                || !disabledSysParentPs.isPrivileged()
2078                || (disabledSysParentPs.childPackageNames != null
2079                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2080            return;
2081        }
2082        final int[] allUserIds = sUserManager.getUserIds();
2083        final int permCount = pkg.requestedPermissions.size();
2084        for (int i = 0; i < permCount; i++) {
2085            String permission = pkg.requestedPermissions.get(i);
2086            BasePermission bp = mSettings.mPermissions.get(permission);
2087            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2088                continue;
2089            }
2090            for (int userId : allUserIds) {
2091                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2092                        permission, userId)) {
2093                    grantRuntimePermission(pkg.packageName, permission, userId);
2094                }
2095            }
2096        }
2097    }
2098
2099    private StorageEventListener mStorageListener = new StorageEventListener() {
2100        @Override
2101        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2102            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2103                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2104                    final String volumeUuid = vol.getFsUuid();
2105
2106                    // Clean up any users or apps that were removed or recreated
2107                    // while this volume was missing
2108                    sUserManager.reconcileUsers(volumeUuid);
2109                    reconcileApps(volumeUuid);
2110
2111                    // Clean up any install sessions that expired or were
2112                    // cancelled while this volume was missing
2113                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2114
2115                    loadPrivatePackages(vol);
2116
2117                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2118                    unloadPrivatePackages(vol);
2119                }
2120            }
2121
2122            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2123                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2124                    updateExternalMediaStatus(true, false);
2125                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2126                    updateExternalMediaStatus(false, false);
2127                }
2128            }
2129        }
2130
2131        @Override
2132        public void onVolumeForgotten(String fsUuid) {
2133            if (TextUtils.isEmpty(fsUuid)) {
2134                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2135                return;
2136            }
2137
2138            // Remove any apps installed on the forgotten volume
2139            synchronized (mPackages) {
2140                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2141                for (PackageSetting ps : packages) {
2142                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2143                    deletePackageVersioned(new VersionedPackage(ps.name,
2144                            PackageManager.VERSION_CODE_HIGHEST),
2145                            new LegacyPackageDeleteObserver(null).getBinder(),
2146                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2147                    // Try very hard to release any references to this package
2148                    // so we don't risk the system server being killed due to
2149                    // open FDs
2150                    AttributeCache.instance().removePackage(ps.name);
2151                }
2152
2153                mSettings.onVolumeForgotten(fsUuid);
2154                mSettings.writeLPr();
2155            }
2156        }
2157    };
2158
2159    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2160            String[] grantedPermissions) {
2161        for (int userId : userIds) {
2162            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2163        }
2164    }
2165
2166    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2167            String[] grantedPermissions) {
2168        SettingBase sb = (SettingBase) pkg.mExtras;
2169        if (sb == null) {
2170            return;
2171        }
2172
2173        PermissionsState permissionsState = sb.getPermissionsState();
2174
2175        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2176                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2177
2178        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2179                >= Build.VERSION_CODES.M;
2180
2181        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2182
2183        for (String permission : pkg.requestedPermissions) {
2184            final BasePermission bp;
2185            synchronized (mPackages) {
2186                bp = mSettings.mPermissions.get(permission);
2187            }
2188            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2189                    && (!instantApp || bp.isInstant())
2190                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2191                    && (grantedPermissions == null
2192                           || ArrayUtils.contains(grantedPermissions, permission))) {
2193                final int flags = permissionsState.getPermissionFlags(permission, userId);
2194                if (supportsRuntimePermissions) {
2195                    // Installer cannot change immutable permissions.
2196                    if ((flags & immutableFlags) == 0) {
2197                        grantRuntimePermission(pkg.packageName, permission, userId);
2198                    }
2199                } else if (mPermissionReviewRequired) {
2200                    // In permission review mode we clear the review flag when we
2201                    // are asked to install the app with all permissions granted.
2202                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2203                        updatePermissionFlags(permission, pkg.packageName,
2204                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2205                    }
2206                }
2207            }
2208        }
2209    }
2210
2211    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2212        Bundle extras = null;
2213        switch (res.returnCode) {
2214            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2215                extras = new Bundle();
2216                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2217                        res.origPermission);
2218                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2219                        res.origPackage);
2220                break;
2221            }
2222            case PackageManager.INSTALL_SUCCEEDED: {
2223                extras = new Bundle();
2224                extras.putBoolean(Intent.EXTRA_REPLACING,
2225                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2226                break;
2227            }
2228        }
2229        return extras;
2230    }
2231
2232    void scheduleWriteSettingsLocked() {
2233        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2234            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2235        }
2236    }
2237
2238    void scheduleWritePackageListLocked(int userId) {
2239        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2240            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2241            msg.arg1 = userId;
2242            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2243        }
2244    }
2245
2246    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2247        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2248        scheduleWritePackageRestrictionsLocked(userId);
2249    }
2250
2251    void scheduleWritePackageRestrictionsLocked(int userId) {
2252        final int[] userIds = (userId == UserHandle.USER_ALL)
2253                ? sUserManager.getUserIds() : new int[]{userId};
2254        for (int nextUserId : userIds) {
2255            if (!sUserManager.exists(nextUserId)) return;
2256            mDirtyUsers.add(nextUserId);
2257            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2258                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2259            }
2260        }
2261    }
2262
2263    public static PackageManagerService main(Context context, Installer installer,
2264            boolean factoryTest, boolean onlyCore) {
2265        // Self-check for initial settings.
2266        PackageManagerServiceCompilerMapping.checkProperties();
2267
2268        PackageManagerService m = new PackageManagerService(context, installer,
2269                factoryTest, onlyCore);
2270        m.enableSystemUserPackages();
2271        ServiceManager.addService("package", m);
2272        return m;
2273    }
2274
2275    private void enableSystemUserPackages() {
2276        if (!UserManager.isSplitSystemUser()) {
2277            return;
2278        }
2279        // For system user, enable apps based on the following conditions:
2280        // - app is whitelisted or belong to one of these groups:
2281        //   -- system app which has no launcher icons
2282        //   -- system app which has INTERACT_ACROSS_USERS permission
2283        //   -- system IME app
2284        // - app is not in the blacklist
2285        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2286        Set<String> enableApps = new ArraySet<>();
2287        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2288                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2289                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2290        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2291        enableApps.addAll(wlApps);
2292        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2293                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2294        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2295        enableApps.removeAll(blApps);
2296        Log.i(TAG, "Applications installed for system user: " + enableApps);
2297        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2298                UserHandle.SYSTEM);
2299        final int allAppsSize = allAps.size();
2300        synchronized (mPackages) {
2301            for (int i = 0; i < allAppsSize; i++) {
2302                String pName = allAps.get(i);
2303                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2304                // Should not happen, but we shouldn't be failing if it does
2305                if (pkgSetting == null) {
2306                    continue;
2307                }
2308                boolean install = enableApps.contains(pName);
2309                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2310                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2311                            + " for system user");
2312                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2313                }
2314            }
2315            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2316        }
2317    }
2318
2319    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2320        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2321                Context.DISPLAY_SERVICE);
2322        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2323    }
2324
2325    /**
2326     * Requests that files preopted on a secondary system partition be copied to the data partition
2327     * if possible.  Note that the actual copying of the files is accomplished by init for security
2328     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2329     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2330     */
2331    private static void requestCopyPreoptedFiles() {
2332        final int WAIT_TIME_MS = 100;
2333        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2334        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2335            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2336            // We will wait for up to 100 seconds.
2337            final long timeStart = SystemClock.uptimeMillis();
2338            final long timeEnd = timeStart + 100 * 1000;
2339            long timeNow = timeStart;
2340            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2341                try {
2342                    Thread.sleep(WAIT_TIME_MS);
2343                } catch (InterruptedException e) {
2344                    // Do nothing
2345                }
2346                timeNow = SystemClock.uptimeMillis();
2347                if (timeNow > timeEnd) {
2348                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2349                    Slog.wtf(TAG, "cppreopt did not finish!");
2350                    break;
2351                }
2352            }
2353
2354            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2355        }
2356    }
2357
2358    public PackageManagerService(Context context, Installer installer,
2359            boolean factoryTest, boolean onlyCore) {
2360        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2361        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2362        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2363                SystemClock.uptimeMillis());
2364
2365        if (mSdkVersion <= 0) {
2366            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2367        }
2368
2369        mContext = context;
2370
2371        mPermissionReviewRequired = context.getResources().getBoolean(
2372                R.bool.config_permissionReviewRequired);
2373
2374        mFactoryTest = factoryTest;
2375        mOnlyCore = onlyCore;
2376        mMetrics = new DisplayMetrics();
2377        mSettings = new Settings(mPackages);
2378        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2379                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2380        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2381                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2382        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2383                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2384        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2385                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2386        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2387                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2388        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2389                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2390
2391        String separateProcesses = SystemProperties.get("debug.separate_processes");
2392        if (separateProcesses != null && separateProcesses.length() > 0) {
2393            if ("*".equals(separateProcesses)) {
2394                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2395                mSeparateProcesses = null;
2396                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2397            } else {
2398                mDefParseFlags = 0;
2399                mSeparateProcesses = separateProcesses.split(",");
2400                Slog.w(TAG, "Running with debug.separate_processes: "
2401                        + separateProcesses);
2402            }
2403        } else {
2404            mDefParseFlags = 0;
2405            mSeparateProcesses = null;
2406        }
2407
2408        mInstaller = installer;
2409        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2410                "*dexopt*");
2411        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2412        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2413
2414        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2415                FgThread.get().getLooper());
2416
2417        getDefaultDisplayMetrics(context, mMetrics);
2418
2419        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2420        SystemConfig systemConfig = SystemConfig.getInstance();
2421        mGlobalGids = systemConfig.getGlobalGids();
2422        mSystemPermissions = systemConfig.getSystemPermissions();
2423        mAvailableFeatures = systemConfig.getAvailableFeatures();
2424        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2425
2426        mProtectedPackages = new ProtectedPackages(mContext);
2427
2428        synchronized (mInstallLock) {
2429        // writer
2430        synchronized (mPackages) {
2431            mHandlerThread = new ServiceThread(TAG,
2432                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2433            mHandlerThread.start();
2434            mHandler = new PackageHandler(mHandlerThread.getLooper());
2435            mProcessLoggingHandler = new ProcessLoggingHandler();
2436            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2437
2438            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2439            mInstantAppRegistry = new InstantAppRegistry(this);
2440
2441            File dataDir = Environment.getDataDirectory();
2442            mAppInstallDir = new File(dataDir, "app");
2443            mAppLib32InstallDir = new File(dataDir, "app-lib");
2444            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2445            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2446            sUserManager = new UserManagerService(context, this,
2447                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2448
2449            // Propagate permission configuration in to package manager.
2450            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2451                    = systemConfig.getPermissions();
2452            for (int i=0; i<permConfig.size(); i++) {
2453                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2454                BasePermission bp = mSettings.mPermissions.get(perm.name);
2455                if (bp == null) {
2456                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2457                    mSettings.mPermissions.put(perm.name, bp);
2458                }
2459                if (perm.gids != null) {
2460                    bp.setGids(perm.gids, perm.perUser);
2461                }
2462            }
2463
2464            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2465            final int builtInLibCount = libConfig.size();
2466            for (int i = 0; i < builtInLibCount; i++) {
2467                String name = libConfig.keyAt(i);
2468                String path = libConfig.valueAt(i);
2469                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2470                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2471            }
2472
2473            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2474
2475            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2476            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2477            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2478
2479            // Clean up orphaned packages for which the code path doesn't exist
2480            // and they are an update to a system app - caused by bug/32321269
2481            final int packageSettingCount = mSettings.mPackages.size();
2482            for (int i = packageSettingCount - 1; i >= 0; i--) {
2483                PackageSetting ps = mSettings.mPackages.valueAt(i);
2484                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2485                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2486                    mSettings.mPackages.removeAt(i);
2487                    mSettings.enableSystemPackageLPw(ps.name);
2488                }
2489            }
2490
2491            if (mFirstBoot) {
2492                requestCopyPreoptedFiles();
2493            }
2494
2495            String customResolverActivity = Resources.getSystem().getString(
2496                    R.string.config_customResolverActivity);
2497            if (TextUtils.isEmpty(customResolverActivity)) {
2498                customResolverActivity = null;
2499            } else {
2500                mCustomResolverComponentName = ComponentName.unflattenFromString(
2501                        customResolverActivity);
2502            }
2503
2504            long startTime = SystemClock.uptimeMillis();
2505
2506            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2507                    startTime);
2508
2509            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2510            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2511
2512            if (bootClassPath == null) {
2513                Slog.w(TAG, "No BOOTCLASSPATH found!");
2514            }
2515
2516            if (systemServerClassPath == null) {
2517                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2518            }
2519
2520            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2521
2522            final VersionInfo ver = mSettings.getInternalVersion();
2523            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2524            if (mIsUpgrade) {
2525                logCriticalInfo(Log.INFO,
2526                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2527            }
2528
2529            // when upgrading from pre-M, promote system app permissions from install to runtime
2530            mPromoteSystemApps =
2531                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2532
2533            // When upgrading from pre-N, we need to handle package extraction like first boot,
2534            // as there is no profiling data available.
2535            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2536
2537            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2538
2539            // save off the names of pre-existing system packages prior to scanning; we don't
2540            // want to automatically grant runtime permissions for new system apps
2541            if (mPromoteSystemApps) {
2542                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2543                while (pkgSettingIter.hasNext()) {
2544                    PackageSetting ps = pkgSettingIter.next();
2545                    if (isSystemApp(ps)) {
2546                        mExistingSystemPackages.add(ps.name);
2547                    }
2548                }
2549            }
2550
2551            mCacheDir = preparePackageParserCache(mIsUpgrade);
2552
2553            // Set flag to monitor and not change apk file paths when
2554            // scanning install directories.
2555            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2556
2557            if (mIsUpgrade || mFirstBoot) {
2558                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2559            }
2560
2561            // Collect vendor overlay packages. (Do this before scanning any apps.)
2562            // For security and version matching reason, only consider
2563            // overlay packages if they reside in the right directory.
2564            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2565                    | PackageParser.PARSE_IS_SYSTEM
2566                    | PackageParser.PARSE_IS_SYSTEM_DIR
2567                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2568
2569            mParallelPackageParserCallback.findStaticOverlayPackages();
2570
2571            // Find base frameworks (resource packages without code).
2572            scanDirTracedLI(frameworkDir, mDefParseFlags
2573                    | PackageParser.PARSE_IS_SYSTEM
2574                    | PackageParser.PARSE_IS_SYSTEM_DIR
2575                    | PackageParser.PARSE_IS_PRIVILEGED,
2576                    scanFlags | SCAN_NO_DEX, 0);
2577
2578            // Collected privileged system packages.
2579            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2580            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2581                    | PackageParser.PARSE_IS_SYSTEM
2582                    | PackageParser.PARSE_IS_SYSTEM_DIR
2583                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2584
2585            // Collect ordinary system packages.
2586            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2587            scanDirTracedLI(systemAppDir, mDefParseFlags
2588                    | PackageParser.PARSE_IS_SYSTEM
2589                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2590
2591            // Collect all vendor packages.
2592            File vendorAppDir = new File("/vendor/app");
2593            try {
2594                vendorAppDir = vendorAppDir.getCanonicalFile();
2595            } catch (IOException e) {
2596                // failed to look up canonical path, continue with original one
2597            }
2598            scanDirTracedLI(vendorAppDir, mDefParseFlags
2599                    | PackageParser.PARSE_IS_SYSTEM
2600                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2601
2602            // Collect all OEM packages.
2603            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2604            scanDirTracedLI(oemAppDir, mDefParseFlags
2605                    | PackageParser.PARSE_IS_SYSTEM
2606                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2607
2608            // Prune any system packages that no longer exist.
2609            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2610            if (!mOnlyCore) {
2611                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2612                while (psit.hasNext()) {
2613                    PackageSetting ps = psit.next();
2614
2615                    /*
2616                     * If this is not a system app, it can't be a
2617                     * disable system app.
2618                     */
2619                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2620                        continue;
2621                    }
2622
2623                    /*
2624                     * If the package is scanned, it's not erased.
2625                     */
2626                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2627                    if (scannedPkg != null) {
2628                        /*
2629                         * If the system app is both scanned and in the
2630                         * disabled packages list, then it must have been
2631                         * added via OTA. Remove it from the currently
2632                         * scanned package so the previously user-installed
2633                         * application can be scanned.
2634                         */
2635                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2636                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2637                                    + ps.name + "; removing system app.  Last known codePath="
2638                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2639                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2640                                    + scannedPkg.mVersionCode);
2641                            removePackageLI(scannedPkg, true);
2642                            mExpectingBetter.put(ps.name, ps.codePath);
2643                        }
2644
2645                        continue;
2646                    }
2647
2648                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2649                        psit.remove();
2650                        logCriticalInfo(Log.WARN, "System package " + ps.name
2651                                + " no longer exists; it's data will be wiped");
2652                        // Actual deletion of code and data will be handled by later
2653                        // reconciliation step
2654                    } else {
2655                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2656                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2657                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2658                        }
2659                    }
2660                }
2661            }
2662
2663            //look for any incomplete package installations
2664            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2665            for (int i = 0; i < deletePkgsList.size(); i++) {
2666                // Actual deletion of code and data will be handled by later
2667                // reconciliation step
2668                final String packageName = deletePkgsList.get(i).name;
2669                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2670                synchronized (mPackages) {
2671                    mSettings.removePackageLPw(packageName);
2672                }
2673            }
2674
2675            //delete tmp files
2676            deleteTempPackageFiles();
2677
2678            // Remove any shared userIDs that have no associated packages
2679            mSettings.pruneSharedUsersLPw();
2680
2681            if (!mOnlyCore) {
2682                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2683                        SystemClock.uptimeMillis());
2684                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2685
2686                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2687                        | PackageParser.PARSE_FORWARD_LOCK,
2688                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2689
2690                /**
2691                 * Remove disable package settings for any updated system
2692                 * apps that were removed via an OTA. If they're not a
2693                 * previously-updated app, remove them completely.
2694                 * Otherwise, just revoke their system-level permissions.
2695                 */
2696                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2697                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2698                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2699
2700                    String msg;
2701                    if (deletedPkg == null) {
2702                        msg = "Updated system package " + deletedAppName
2703                                + " no longer exists; it's data will be wiped";
2704                        // Actual deletion of code and data will be handled by later
2705                        // reconciliation step
2706                    } else {
2707                        msg = "Updated system app + " + deletedAppName
2708                                + " no longer present; removing system privileges for "
2709                                + deletedAppName;
2710
2711                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2712
2713                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2714                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2715                    }
2716                    logCriticalInfo(Log.WARN, msg);
2717                }
2718
2719                /**
2720                 * Make sure all system apps that we expected to appear on
2721                 * the userdata partition actually showed up. If they never
2722                 * appeared, crawl back and revive the system version.
2723                 */
2724                for (int i = 0; i < mExpectingBetter.size(); i++) {
2725                    final String packageName = mExpectingBetter.keyAt(i);
2726                    if (!mPackages.containsKey(packageName)) {
2727                        final File scanFile = mExpectingBetter.valueAt(i);
2728
2729                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2730                                + " but never showed up; reverting to system");
2731
2732                        int reparseFlags = mDefParseFlags;
2733                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2734                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2735                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2736                                    | PackageParser.PARSE_IS_PRIVILEGED;
2737                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2738                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2739                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2740                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2741                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2742                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2743                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2744                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2745                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2746                        } else {
2747                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2748                            continue;
2749                        }
2750
2751                        mSettings.enableSystemPackageLPw(packageName);
2752
2753                        try {
2754                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2755                        } catch (PackageManagerException e) {
2756                            Slog.e(TAG, "Failed to parse original system package: "
2757                                    + e.getMessage());
2758                        }
2759                    }
2760                }
2761            }
2762            mExpectingBetter.clear();
2763
2764            // Resolve the storage manager.
2765            mStorageManagerPackage = getStorageManagerPackageName();
2766
2767            // Resolve protected action filters. Only the setup wizard is allowed to
2768            // have a high priority filter for these actions.
2769            mSetupWizardPackage = getSetupWizardPackageName();
2770            if (mProtectedFilters.size() > 0) {
2771                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2772                    Slog.i(TAG, "No setup wizard;"
2773                        + " All protected intents capped to priority 0");
2774                }
2775                for (ActivityIntentInfo filter : mProtectedFilters) {
2776                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2777                        if (DEBUG_FILTERS) {
2778                            Slog.i(TAG, "Found setup wizard;"
2779                                + " allow priority " + filter.getPriority() + ";"
2780                                + " package: " + filter.activity.info.packageName
2781                                + " activity: " + filter.activity.className
2782                                + " priority: " + filter.getPriority());
2783                        }
2784                        // skip setup wizard; allow it to keep the high priority filter
2785                        continue;
2786                    }
2787                    if (DEBUG_FILTERS) {
2788                        Slog.i(TAG, "Protected action; cap priority to 0;"
2789                                + " package: " + filter.activity.info.packageName
2790                                + " activity: " + filter.activity.className
2791                                + " origPrio: " + filter.getPriority());
2792                    }
2793                    filter.setPriority(0);
2794                }
2795            }
2796            mDeferProtectedFilters = false;
2797            mProtectedFilters.clear();
2798
2799            // Now that we know all of the shared libraries, update all clients to have
2800            // the correct library paths.
2801            updateAllSharedLibrariesLPw(null);
2802
2803            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2804                // NOTE: We ignore potential failures here during a system scan (like
2805                // the rest of the commands above) because there's precious little we
2806                // can do about it. A settings error is reported, though.
2807                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2808            }
2809
2810            // Now that we know all the packages we are keeping,
2811            // read and update their last usage times.
2812            mPackageUsage.read(mPackages);
2813            mCompilerStats.read();
2814
2815            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2816                    SystemClock.uptimeMillis());
2817            Slog.i(TAG, "Time to scan packages: "
2818                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2819                    + " seconds");
2820
2821            // If the platform SDK has changed since the last time we booted,
2822            // we need to re-grant app permission to catch any new ones that
2823            // appear.  This is really a hack, and means that apps can in some
2824            // cases get permissions that the user didn't initially explicitly
2825            // allow...  it would be nice to have some better way to handle
2826            // this situation.
2827            int updateFlags = UPDATE_PERMISSIONS_ALL;
2828            if (ver.sdkVersion != mSdkVersion) {
2829                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2830                        + mSdkVersion + "; regranting permissions for internal storage");
2831                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2832            }
2833            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2834            ver.sdkVersion = mSdkVersion;
2835
2836            // If this is the first boot or an update from pre-M, and it is a normal
2837            // boot, then we need to initialize the default preferred apps across
2838            // all defined users.
2839            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2840                for (UserInfo user : sUserManager.getUsers(true)) {
2841                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2842                    applyFactoryDefaultBrowserLPw(user.id);
2843                    primeDomainVerificationsLPw(user.id);
2844                }
2845            }
2846
2847            // Prepare storage for system user really early during boot,
2848            // since core system apps like SettingsProvider and SystemUI
2849            // can't wait for user to start
2850            final int storageFlags;
2851            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2852                storageFlags = StorageManager.FLAG_STORAGE_DE;
2853            } else {
2854                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2855            }
2856            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2857                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2858                    true /* onlyCoreApps */);
2859            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2860                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2861                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2862                traceLog.traceBegin("AppDataFixup");
2863                try {
2864                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2865                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2866                } catch (InstallerException e) {
2867                    Slog.w(TAG, "Trouble fixing GIDs", e);
2868                }
2869                traceLog.traceEnd();
2870
2871                traceLog.traceBegin("AppDataPrepare");
2872                if (deferPackages == null || deferPackages.isEmpty()) {
2873                    return;
2874                }
2875                int count = 0;
2876                for (String pkgName : deferPackages) {
2877                    PackageParser.Package pkg = null;
2878                    synchronized (mPackages) {
2879                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2880                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2881                            pkg = ps.pkg;
2882                        }
2883                    }
2884                    if (pkg != null) {
2885                        synchronized (mInstallLock) {
2886                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2887                                    true /* maybeMigrateAppData */);
2888                        }
2889                        count++;
2890                    }
2891                }
2892                traceLog.traceEnd();
2893                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2894            }, "prepareAppData");
2895
2896            // If this is first boot after an OTA, and a normal boot, then
2897            // we need to clear code cache directories.
2898            // Note that we do *not* clear the application profiles. These remain valid
2899            // across OTAs and are used to drive profile verification (post OTA) and
2900            // profile compilation (without waiting to collect a fresh set of profiles).
2901            if (mIsUpgrade && !onlyCore) {
2902                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2903                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2904                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2905                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2906                        // No apps are running this early, so no need to freeze
2907                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2908                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2909                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2910                    }
2911                }
2912                ver.fingerprint = Build.FINGERPRINT;
2913            }
2914
2915            checkDefaultBrowser();
2916
2917            // clear only after permissions and other defaults have been updated
2918            mExistingSystemPackages.clear();
2919            mPromoteSystemApps = false;
2920
2921            // All the changes are done during package scanning.
2922            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2923
2924            // can downgrade to reader
2925            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2926            mSettings.writeLPr();
2927            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2928
2929            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2930                    SystemClock.uptimeMillis());
2931
2932            if (!mOnlyCore) {
2933                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2934                mRequiredInstallerPackage = getRequiredInstallerLPr();
2935                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2936                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2937                if (mIntentFilterVerifierComponent != null) {
2938                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2939                            mIntentFilterVerifierComponent);
2940                } else {
2941                    mIntentFilterVerifier = null;
2942                }
2943                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2944                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2945                        SharedLibraryInfo.VERSION_UNDEFINED);
2946                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2947                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2948                        SharedLibraryInfo.VERSION_UNDEFINED);
2949            } else {
2950                mRequiredVerifierPackage = null;
2951                mRequiredInstallerPackage = null;
2952                mRequiredUninstallerPackage = null;
2953                mIntentFilterVerifierComponent = null;
2954                mIntentFilterVerifier = null;
2955                mServicesSystemSharedLibraryPackageName = null;
2956                mSharedSystemSharedLibraryPackageName = null;
2957            }
2958
2959            mInstallerService = new PackageInstallerService(context, this);
2960            final Pair<ComponentName, String> instantAppResolverComponent =
2961                    getInstantAppResolverLPr();
2962            if (instantAppResolverComponent != null) {
2963                if (DEBUG_EPHEMERAL) {
2964                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2965                }
2966                mInstantAppResolverConnection = new EphemeralResolverConnection(
2967                        mContext, instantAppResolverComponent.first,
2968                        instantAppResolverComponent.second);
2969                mInstantAppResolverSettingsComponent =
2970                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2971            } else {
2972                mInstantAppResolverConnection = null;
2973                mInstantAppResolverSettingsComponent = null;
2974            }
2975            updateInstantAppInstallerLocked(null);
2976
2977            // Read and update the usage of dex files.
2978            // Do this at the end of PM init so that all the packages have their
2979            // data directory reconciled.
2980            // At this point we know the code paths of the packages, so we can validate
2981            // the disk file and build the internal cache.
2982            // The usage file is expected to be small so loading and verifying it
2983            // should take a fairly small time compare to the other activities (e.g. package
2984            // scanning).
2985            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2986            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2987            for (int userId : currentUserIds) {
2988                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2989            }
2990            mDexManager.load(userPackages);
2991        } // synchronized (mPackages)
2992        } // synchronized (mInstallLock)
2993
2994        // Now after opening every single application zip, make sure they
2995        // are all flushed.  Not really needed, but keeps things nice and
2996        // tidy.
2997        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2998        Runtime.getRuntime().gc();
2999        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3000
3001        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3002        FallbackCategoryProvider.loadFallbacks();
3003        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3004
3005        // The initial scanning above does many calls into installd while
3006        // holding the mPackages lock, but we're mostly interested in yelling
3007        // once we have a booted system.
3008        mInstaller.setWarnIfHeld(mPackages);
3009
3010        // Expose private service for system components to use.
3011        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3012        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3013    }
3014
3015    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3016        // we're only interested in updating the installer appliction when 1) it's not
3017        // already set or 2) the modified package is the installer
3018        if (mInstantAppInstallerActivity != null
3019                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3020                        .equals(modifiedPackage)) {
3021            return;
3022        }
3023        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3024    }
3025
3026    private static File preparePackageParserCache(boolean isUpgrade) {
3027        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3028            return null;
3029        }
3030
3031        // Disable package parsing on eng builds to allow for faster incremental development.
3032        if ("eng".equals(Build.TYPE)) {
3033            return null;
3034        }
3035
3036        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3037            Slog.i(TAG, "Disabling package parser cache due to system property.");
3038            return null;
3039        }
3040
3041        // The base directory for the package parser cache lives under /data/system/.
3042        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3043                "package_cache");
3044        if (cacheBaseDir == null) {
3045            return null;
3046        }
3047
3048        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3049        // This also serves to "GC" unused entries when the package cache version changes (which
3050        // can only happen during upgrades).
3051        if (isUpgrade) {
3052            FileUtils.deleteContents(cacheBaseDir);
3053        }
3054
3055
3056        // Return the versioned package cache directory. This is something like
3057        // "/data/system/package_cache/1"
3058        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3059
3060        // The following is a workaround to aid development on non-numbered userdebug
3061        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3062        // the system partition is newer.
3063        //
3064        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3065        // that starts with "eng." to signify that this is an engineering build and not
3066        // destined for release.
3067        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3068            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3069
3070            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3071            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3072            // in general and should not be used for production changes. In this specific case,
3073            // we know that they will work.
3074            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3075            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3076                FileUtils.deleteContents(cacheBaseDir);
3077                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3078            }
3079        }
3080
3081        return cacheDir;
3082    }
3083
3084    @Override
3085    public boolean isFirstBoot() {
3086        // allow instant applications
3087        return mFirstBoot;
3088    }
3089
3090    @Override
3091    public boolean isOnlyCoreApps() {
3092        // allow instant applications
3093        return mOnlyCore;
3094    }
3095
3096    @Override
3097    public boolean isUpgrade() {
3098        // allow instant applications
3099        return mIsUpgrade;
3100    }
3101
3102    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3103        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3104
3105        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3106                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3107                UserHandle.USER_SYSTEM);
3108        if (matches.size() == 1) {
3109            return matches.get(0).getComponentInfo().packageName;
3110        } else if (matches.size() == 0) {
3111            Log.e(TAG, "There should probably be a verifier, but, none were found");
3112            return null;
3113        }
3114        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3115    }
3116
3117    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3118        synchronized (mPackages) {
3119            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3120            if (libraryEntry == null) {
3121                throw new IllegalStateException("Missing required shared library:" + name);
3122            }
3123            return libraryEntry.apk;
3124        }
3125    }
3126
3127    private @NonNull String getRequiredInstallerLPr() {
3128        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3129        intent.addCategory(Intent.CATEGORY_DEFAULT);
3130        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3131
3132        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3133                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3134                UserHandle.USER_SYSTEM);
3135        if (matches.size() == 1) {
3136            ResolveInfo resolveInfo = matches.get(0);
3137            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3138                throw new RuntimeException("The installer must be a privileged app");
3139            }
3140            return matches.get(0).getComponentInfo().packageName;
3141        } else {
3142            throw new RuntimeException("There must be exactly one installer; found " + matches);
3143        }
3144    }
3145
3146    private @NonNull String getRequiredUninstallerLPr() {
3147        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3148        intent.addCategory(Intent.CATEGORY_DEFAULT);
3149        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3150
3151        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3152                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3153                UserHandle.USER_SYSTEM);
3154        if (resolveInfo == null ||
3155                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3156            throw new RuntimeException("There must be exactly one uninstaller; found "
3157                    + resolveInfo);
3158        }
3159        return resolveInfo.getComponentInfo().packageName;
3160    }
3161
3162    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3163        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3164
3165        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3166                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3167                UserHandle.USER_SYSTEM);
3168        ResolveInfo best = null;
3169        final int N = matches.size();
3170        for (int i = 0; i < N; i++) {
3171            final ResolveInfo cur = matches.get(i);
3172            final String packageName = cur.getComponentInfo().packageName;
3173            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3174                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3175                continue;
3176            }
3177
3178            if (best == null || cur.priority > best.priority) {
3179                best = cur;
3180            }
3181        }
3182
3183        if (best != null) {
3184            return best.getComponentInfo().getComponentName();
3185        }
3186        Slog.w(TAG, "Intent filter verifier not found");
3187        return null;
3188    }
3189
3190    @Override
3191    public @Nullable ComponentName getInstantAppResolverComponent() {
3192        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3193            return null;
3194        }
3195        synchronized (mPackages) {
3196            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3197            if (instantAppResolver == null) {
3198                return null;
3199            }
3200            return instantAppResolver.first;
3201        }
3202    }
3203
3204    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3205        final String[] packageArray =
3206                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3207        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3208            if (DEBUG_EPHEMERAL) {
3209                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3210            }
3211            return null;
3212        }
3213
3214        final int callingUid = Binder.getCallingUid();
3215        final int resolveFlags =
3216                MATCH_DIRECT_BOOT_AWARE
3217                | MATCH_DIRECT_BOOT_UNAWARE
3218                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3219        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3220        final Intent resolverIntent = new Intent(actionName);
3221        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3222                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3223        // temporarily look for the old action
3224        if (resolvers.size() == 0) {
3225            if (DEBUG_EPHEMERAL) {
3226                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3227            }
3228            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3229            resolverIntent.setAction(actionName);
3230            resolvers = queryIntentServicesInternal(resolverIntent, null,
3231                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3232        }
3233        final int N = resolvers.size();
3234        if (N == 0) {
3235            if (DEBUG_EPHEMERAL) {
3236                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3237            }
3238            return null;
3239        }
3240
3241        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3242        for (int i = 0; i < N; i++) {
3243            final ResolveInfo info = resolvers.get(i);
3244
3245            if (info.serviceInfo == null) {
3246                continue;
3247            }
3248
3249            final String packageName = info.serviceInfo.packageName;
3250            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3251                if (DEBUG_EPHEMERAL) {
3252                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3253                            + " pkg: " + packageName + ", info:" + info);
3254                }
3255                continue;
3256            }
3257
3258            if (DEBUG_EPHEMERAL) {
3259                Slog.v(TAG, "Ephemeral resolver found;"
3260                        + " pkg: " + packageName + ", info:" + info);
3261            }
3262            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3263        }
3264        if (DEBUG_EPHEMERAL) {
3265            Slog.v(TAG, "Ephemeral resolver NOT found");
3266        }
3267        return null;
3268    }
3269
3270    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3271        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3272        intent.addCategory(Intent.CATEGORY_DEFAULT);
3273        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3274
3275        final int resolveFlags =
3276                MATCH_DIRECT_BOOT_AWARE
3277                | MATCH_DIRECT_BOOT_UNAWARE
3278                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3279        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3280                resolveFlags, UserHandle.USER_SYSTEM);
3281        // temporarily look for the old action
3282        if (matches.isEmpty()) {
3283            if (DEBUG_EPHEMERAL) {
3284                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3285            }
3286            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3287            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3288                    resolveFlags, UserHandle.USER_SYSTEM);
3289        }
3290        Iterator<ResolveInfo> iter = matches.iterator();
3291        while (iter.hasNext()) {
3292            final ResolveInfo rInfo = iter.next();
3293            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3294            if (ps != null) {
3295                final PermissionsState permissionsState = ps.getPermissionsState();
3296                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3297                    continue;
3298                }
3299            }
3300            iter.remove();
3301        }
3302        if (matches.size() == 0) {
3303            return null;
3304        } else if (matches.size() == 1) {
3305            return (ActivityInfo) matches.get(0).getComponentInfo();
3306        } else {
3307            throw new RuntimeException(
3308                    "There must be at most one ephemeral installer; found " + matches);
3309        }
3310    }
3311
3312    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3313            @NonNull ComponentName resolver) {
3314        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3315                .addCategory(Intent.CATEGORY_DEFAULT)
3316                .setPackage(resolver.getPackageName());
3317        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3318        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3319                UserHandle.USER_SYSTEM);
3320        // temporarily look for the old action
3321        if (matches.isEmpty()) {
3322            if (DEBUG_EPHEMERAL) {
3323                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3324            }
3325            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3326            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3327                    UserHandle.USER_SYSTEM);
3328        }
3329        if (matches.isEmpty()) {
3330            return null;
3331        }
3332        return matches.get(0).getComponentInfo().getComponentName();
3333    }
3334
3335    private void primeDomainVerificationsLPw(int userId) {
3336        if (DEBUG_DOMAIN_VERIFICATION) {
3337            Slog.d(TAG, "Priming domain verifications in user " + userId);
3338        }
3339
3340        SystemConfig systemConfig = SystemConfig.getInstance();
3341        ArraySet<String> packages = systemConfig.getLinkedApps();
3342
3343        for (String packageName : packages) {
3344            PackageParser.Package pkg = mPackages.get(packageName);
3345            if (pkg != null) {
3346                if (!pkg.isSystemApp()) {
3347                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3348                    continue;
3349                }
3350
3351                ArraySet<String> domains = null;
3352                for (PackageParser.Activity a : pkg.activities) {
3353                    for (ActivityIntentInfo filter : a.intents) {
3354                        if (hasValidDomains(filter)) {
3355                            if (domains == null) {
3356                                domains = new ArraySet<String>();
3357                            }
3358                            domains.addAll(filter.getHostsList());
3359                        }
3360                    }
3361                }
3362
3363                if (domains != null && domains.size() > 0) {
3364                    if (DEBUG_DOMAIN_VERIFICATION) {
3365                        Slog.v(TAG, "      + " + packageName);
3366                    }
3367                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3368                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3369                    // and then 'always' in the per-user state actually used for intent resolution.
3370                    final IntentFilterVerificationInfo ivi;
3371                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3372                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3373                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3374                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3375                } else {
3376                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3377                            + "' does not handle web links");
3378                }
3379            } else {
3380                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3381            }
3382        }
3383
3384        scheduleWritePackageRestrictionsLocked(userId);
3385        scheduleWriteSettingsLocked();
3386    }
3387
3388    private void applyFactoryDefaultBrowserLPw(int userId) {
3389        // The default browser app's package name is stored in a string resource,
3390        // with a product-specific overlay used for vendor customization.
3391        String browserPkg = mContext.getResources().getString(
3392                com.android.internal.R.string.default_browser);
3393        if (!TextUtils.isEmpty(browserPkg)) {
3394            // non-empty string => required to be a known package
3395            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3396            if (ps == null) {
3397                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3398                browserPkg = null;
3399            } else {
3400                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3401            }
3402        }
3403
3404        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3405        // default.  If there's more than one, just leave everything alone.
3406        if (browserPkg == null) {
3407            calculateDefaultBrowserLPw(userId);
3408        }
3409    }
3410
3411    private void calculateDefaultBrowserLPw(int userId) {
3412        List<String> allBrowsers = resolveAllBrowserApps(userId);
3413        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3414        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3415    }
3416
3417    private List<String> resolveAllBrowserApps(int userId) {
3418        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3419        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3420                PackageManager.MATCH_ALL, userId);
3421
3422        final int count = list.size();
3423        List<String> result = new ArrayList<String>(count);
3424        for (int i=0; i<count; i++) {
3425            ResolveInfo info = list.get(i);
3426            if (info.activityInfo == null
3427                    || !info.handleAllWebDataURI
3428                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3429                    || result.contains(info.activityInfo.packageName)) {
3430                continue;
3431            }
3432            result.add(info.activityInfo.packageName);
3433        }
3434
3435        return result;
3436    }
3437
3438    private boolean packageIsBrowser(String packageName, int userId) {
3439        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3440                PackageManager.MATCH_ALL, userId);
3441        final int N = list.size();
3442        for (int i = 0; i < N; i++) {
3443            ResolveInfo info = list.get(i);
3444            if (packageName.equals(info.activityInfo.packageName)) {
3445                return true;
3446            }
3447        }
3448        return false;
3449    }
3450
3451    private void checkDefaultBrowser() {
3452        final int myUserId = UserHandle.myUserId();
3453        final String packageName = getDefaultBrowserPackageName(myUserId);
3454        if (packageName != null) {
3455            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3456            if (info == null) {
3457                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3458                synchronized (mPackages) {
3459                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3460                }
3461            }
3462        }
3463    }
3464
3465    @Override
3466    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3467            throws RemoteException {
3468        try {
3469            return super.onTransact(code, data, reply, flags);
3470        } catch (RuntimeException e) {
3471            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3472                Slog.wtf(TAG, "Package Manager Crash", e);
3473            }
3474            throw e;
3475        }
3476    }
3477
3478    static int[] appendInts(int[] cur, int[] add) {
3479        if (add == null) return cur;
3480        if (cur == null) return add;
3481        final int N = add.length;
3482        for (int i=0; i<N; i++) {
3483            cur = appendInt(cur, add[i]);
3484        }
3485        return cur;
3486    }
3487
3488    /**
3489     * Returns whether or not a full application can see an instant application.
3490     * <p>
3491     * Currently, there are three cases in which this can occur:
3492     * <ol>
3493     * <li>The calling application is a "special" process. The special
3494     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3495     *     and {@code 0}</li>
3496     * <li>The calling application has the permission
3497     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3498     * <li>[TODO] The calling application is the default launcher on the
3499     *     system partition.</li>
3500     * </ol>
3501     */
3502    private boolean canAccessInstantApps(int callingUid) {
3503        final boolean isSpecialProcess =
3504                callingUid == Process.SYSTEM_UID
3505                        || callingUid == Process.SHELL_UID
3506                        || callingUid == Process.ROOT_UID;
3507        final boolean allowMatchInstant =
3508                isSpecialProcess
3509                        || mContext.checkCallingOrSelfPermission(
3510                        android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
3511        return allowMatchInstant;
3512    }
3513
3514    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3515        if (!sUserManager.exists(userId)) return null;
3516        if (ps == null) {
3517            return null;
3518        }
3519        PackageParser.Package p = ps.pkg;
3520        if (p == null) {
3521            return null;
3522        }
3523        final int callingUid = Binder.getCallingUid();
3524        // Filter out ephemeral app metadata:
3525        //   * The system/shell/root can see metadata for any app
3526        //   * An installed app can see metadata for 1) other installed apps
3527        //     and 2) ephemeral apps that have explicitly interacted with it
3528        //   * Ephemeral apps can only see their own data and exposed installed apps
3529        //   * Holding a signature permission allows seeing instant apps
3530        if (!canAccessInstantApps(callingUid)) {
3531            final String instantAppPackageName = getInstantAppPackageName(callingUid);
3532            if (instantAppPackageName != null) {
3533                // ephemeral apps can only get information on themselves or
3534                // installed apps that are exposed.
3535                if (!instantAppPackageName.equals(p.packageName)
3536                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3537                    return null;
3538                }
3539            } else {
3540                if (ps.getInstantApp(userId)) {
3541                    // only get access to the ephemeral app if we've been granted access
3542                    final int callingAppId = UserHandle.getAppId(callingUid);
3543                    if (!mInstantAppRegistry.isInstantAccessGranted(
3544                            userId, callingAppId, ps.appId)) {
3545                        return null;
3546                    }
3547                }
3548            }
3549        }
3550
3551        final PermissionsState permissionsState = ps.getPermissionsState();
3552
3553        // Compute GIDs only if requested
3554        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3555                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3556        // Compute granted permissions only if package has requested permissions
3557        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3558                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3559        final PackageUserState state = ps.readUserState(userId);
3560
3561        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3562                && ps.isSystem()) {
3563            flags |= MATCH_ANY_USER;
3564        }
3565
3566        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3567                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3568
3569        if (packageInfo == null) {
3570            return null;
3571        }
3572
3573        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3574
3575        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3576                resolveExternalPackageNameLPr(p);
3577
3578        return packageInfo;
3579    }
3580
3581    @Override
3582    public void checkPackageStartable(String packageName, int userId) {
3583        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3584            throw new SecurityException("Instant applications don't have access to this method");
3585        }
3586        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3587        synchronized (mPackages) {
3588            final PackageSetting ps = mSettings.mPackages.get(packageName);
3589            if (ps == null) {
3590                throw new SecurityException("Package " + packageName + " was not found!");
3591            }
3592
3593            if (!ps.getInstalled(userId)) {
3594                throw new SecurityException(
3595                        "Package " + packageName + " was not installed for user " + userId + "!");
3596            }
3597
3598            if (mSafeMode && !ps.isSystem()) {
3599                throw new SecurityException("Package " + packageName + " not a system app!");
3600            }
3601
3602            if (mFrozenPackages.contains(packageName)) {
3603                throw new SecurityException("Package " + packageName + " is currently frozen!");
3604            }
3605
3606            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3607                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3608                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3609            }
3610        }
3611    }
3612
3613    @Override
3614    public boolean isPackageAvailable(String packageName, int userId) {
3615        if (!sUserManager.exists(userId)) return false;
3616        final int callingUid = Binder.getCallingUid();
3617        enforceCrossUserPermission(callingUid, userId,
3618                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3619        synchronized (mPackages) {
3620            PackageParser.Package p = mPackages.get(packageName);
3621            if (p != null) {
3622                final PackageSetting ps = (PackageSetting) p.mExtras;
3623                if (filterAppAccessLPr(ps, callingUid, userId)) {
3624                    return false;
3625                }
3626                if (ps != null) {
3627                    final PackageUserState state = ps.readUserState(userId);
3628                    if (state != null) {
3629                        return PackageParser.isAvailable(state);
3630                    }
3631                }
3632            }
3633        }
3634        return false;
3635    }
3636
3637    @Override
3638    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3639        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3640                flags, userId);
3641    }
3642
3643    @Override
3644    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3645            int flags, int userId) {
3646        return getPackageInfoInternal(versionedPackage.getPackageName(),
3647                versionedPackage.getVersionCode(), flags, userId);
3648    }
3649
3650    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3651            int flags, int userId) {
3652        if (!sUserManager.exists(userId)) return null;
3653        final int callingUid = Binder.getCallingUid();
3654        flags = updateFlagsForPackage(flags, userId, packageName);
3655        enforceCrossUserPermission(callingUid, userId,
3656                false /* requireFullPermission */, false /* checkShell */, "get package info");
3657
3658        // reader
3659        synchronized (mPackages) {
3660            // Normalize package name to handle renamed packages and static libs
3661            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3662
3663            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3664            if (matchFactoryOnly) {
3665                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3666                if (ps != null) {
3667                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
3668                        return null;
3669                    }
3670                    if (filterAppAccessLPr(ps, callingUid, userId)) {
3671                        return null;
3672                    }
3673                    return generatePackageInfo(ps, flags, userId);
3674                }
3675            }
3676
3677            PackageParser.Package p = mPackages.get(packageName);
3678            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3679                return null;
3680            }
3681            if (DEBUG_PACKAGE_INFO)
3682                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3683            if (p != null) {
3684                final PackageSetting ps = (PackageSetting) p.mExtras;
3685                if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
3686                    return null;
3687                }
3688                if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
3689                    return null;
3690                }
3691                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3692            }
3693            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3694                final PackageSetting ps = mSettings.mPackages.get(packageName);
3695                if (ps == null) return null;
3696                if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
3697                    return null;
3698                }
3699                if (filterAppAccessLPr(ps, callingUid, userId)) {
3700                    return null;
3701                }
3702                return generatePackageInfo(ps, flags, userId);
3703            }
3704        }
3705        return null;
3706    }
3707
3708    /**
3709     * Returns whether or not access to the application should be filtered.
3710     * <p>
3711     * Access may be limited based upon whether the calling or target applications
3712     * are instant applications.
3713     *
3714     * @see #canAccessInstantApps(int)
3715     */
3716    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3717            @Nullable ComponentName component, boolean componentVisibleToInstantApp, int userId) {
3718        // if we're in an isolated process, get the real calling UID
3719        if (Process.isIsolated(callingUid)) {
3720            callingUid = mIsolatedOwners.get(callingUid);
3721        }
3722        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3723        final boolean callerIsInstantApp = instantAppPkgName != null;
3724        if (ps == null) {
3725            if (callerIsInstantApp) {
3726                // pretend the application exists, but, needs to be filtered
3727                return true;
3728            }
3729            return false;
3730        }
3731        // if the target and caller are the same application, don't filter
3732        if (isCallerSameApp(ps.name, callingUid)) {
3733            return false;
3734        }
3735        if (callerIsInstantApp) {
3736            // request for a specific component; if it hasn't been explicitly exposed, filter
3737            if (component != null) {
3738                return !componentVisibleToInstantApp;
3739            }
3740            // request for application; if no components have been explicitly exposed, filter
3741            return !ps.pkg.visibleToInstantApps;
3742        }
3743        if (ps.getInstantApp(userId)) {
3744            // caller can see all components of all instant applications, don't filter
3745            if (canAccessInstantApps(callingUid)) {
3746                return false;
3747            }
3748            // request for a specific instant application component, filter
3749            if (component != null) {
3750                return true;
3751            }
3752            // request for an instant application; if the caller hasn't been granted access, filter
3753            return !mInstantAppRegistry.isInstantAccessGranted(
3754                    userId, UserHandle.getAppId(callingUid), ps.appId);
3755        }
3756        return false;
3757    }
3758
3759    /**
3760     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3761     */
3762    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3763        return filterAppAccessLPr(ps, callingUid, null, false, userId);
3764    }
3765
3766    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3767            int flags) {
3768        // Callers can access only the libs they depend on, otherwise they need to explicitly
3769        // ask for the shared libraries given the caller is allowed to access all static libs.
3770        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3771            // System/shell/root get to see all static libs
3772            final int appId = UserHandle.getAppId(uid);
3773            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3774                    || appId == Process.ROOT_UID) {
3775                return false;
3776            }
3777        }
3778
3779        // No package means no static lib as it is always on internal storage
3780        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3781            return false;
3782        }
3783
3784        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3785                ps.pkg.staticSharedLibVersion);
3786        if (libEntry == null) {
3787            return false;
3788        }
3789
3790        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3791        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3792        if (uidPackageNames == null) {
3793            return true;
3794        }
3795
3796        for (String uidPackageName : uidPackageNames) {
3797            if (ps.name.equals(uidPackageName)) {
3798                return false;
3799            }
3800            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3801            if (uidPs != null) {
3802                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3803                        libEntry.info.getName());
3804                if (index < 0) {
3805                    continue;
3806                }
3807                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3808                    return false;
3809                }
3810            }
3811        }
3812        return true;
3813    }
3814
3815    @Override
3816    public String[] currentToCanonicalPackageNames(String[] names) {
3817        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3818            return names;
3819        }
3820        String[] out = new String[names.length];
3821        // reader
3822        synchronized (mPackages) {
3823            for (int i=names.length-1; i>=0; i--) {
3824                PackageSetting ps = mSettings.mPackages.get(names[i]);
3825                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3826            }
3827        }
3828        return out;
3829    }
3830
3831    @Override
3832    public String[] canonicalToCurrentPackageNames(String[] names) {
3833        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3834            return names;
3835        }
3836        String[] out = new String[names.length];
3837        // reader
3838        synchronized (mPackages) {
3839            for (int i=names.length-1; i>=0; i--) {
3840                String cur = mSettings.getRenamedPackageLPr(names[i]);
3841                out[i] = cur != null ? cur : names[i];
3842            }
3843        }
3844        return out;
3845    }
3846
3847    @Override
3848    public int getPackageUid(String packageName, int flags, int userId) {
3849        if (!sUserManager.exists(userId)) return -1;
3850        final int callingUid = Binder.getCallingUid();
3851        flags = updateFlagsForPackage(flags, userId, packageName);
3852        enforceCrossUserPermission(callingUid, userId,
3853                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3854
3855        // reader
3856        synchronized (mPackages) {
3857            final PackageParser.Package p = mPackages.get(packageName);
3858            if (p != null && p.isMatch(flags)) {
3859                PackageSetting ps = (PackageSetting) p.mExtras;
3860                if (filterAppAccessLPr(ps, callingUid, userId)) {
3861                    return -1;
3862                }
3863                return UserHandle.getUid(userId, p.applicationInfo.uid);
3864            }
3865            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3866                final PackageSetting ps = mSettings.mPackages.get(packageName);
3867                if (ps != null && ps.isMatch(flags)
3868                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3869                    return UserHandle.getUid(userId, ps.appId);
3870                }
3871            }
3872        }
3873
3874        return -1;
3875    }
3876
3877    @Override
3878    public int[] getPackageGids(String packageName, int flags, int userId) {
3879        if (!sUserManager.exists(userId)) return null;
3880        final int callingUid = Binder.getCallingUid();
3881        flags = updateFlagsForPackage(flags, userId, packageName);
3882        enforceCrossUserPermission(callingUid, userId,
3883                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3884
3885        // reader
3886        synchronized (mPackages) {
3887            final PackageParser.Package p = mPackages.get(packageName);
3888            if (p != null && p.isMatch(flags)) {
3889                PackageSetting ps = (PackageSetting) p.mExtras;
3890                if (filterAppAccessLPr(ps, callingUid, userId)) {
3891                    return null;
3892                }
3893                // TODO: Shouldn't this be checking for package installed state for userId and
3894                // return null?
3895                return ps.getPermissionsState().computeGids(userId);
3896            }
3897            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3898                final PackageSetting ps = mSettings.mPackages.get(packageName);
3899                if (ps != null && ps.isMatch(flags)
3900                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3901                    return ps.getPermissionsState().computeGids(userId);
3902                }
3903            }
3904        }
3905
3906        return null;
3907    }
3908
3909    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3910        if (bp.perm != null) {
3911            return PackageParser.generatePermissionInfo(bp.perm, flags);
3912        }
3913        PermissionInfo pi = new PermissionInfo();
3914        pi.name = bp.name;
3915        pi.packageName = bp.sourcePackage;
3916        pi.nonLocalizedLabel = bp.name;
3917        pi.protectionLevel = bp.protectionLevel;
3918        return pi;
3919    }
3920
3921    @Override
3922    public PermissionInfo getPermissionInfo(String name, int flags) {
3923        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3924            return null;
3925        }
3926        // reader
3927        synchronized (mPackages) {
3928            final BasePermission p = mSettings.mPermissions.get(name);
3929            if (p != null) {
3930                return generatePermissionInfo(p, flags);
3931            }
3932            return null;
3933        }
3934    }
3935
3936    @Override
3937    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3938            int flags) {
3939        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3940            return null;
3941        }
3942        // reader
3943        synchronized (mPackages) {
3944            if (group != null && !mPermissionGroups.containsKey(group)) {
3945                // This is thrown as NameNotFoundException
3946                return null;
3947            }
3948
3949            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3950            for (BasePermission p : mSettings.mPermissions.values()) {
3951                if (group == null) {
3952                    if (p.perm == null || p.perm.info.group == null) {
3953                        out.add(generatePermissionInfo(p, flags));
3954                    }
3955                } else {
3956                    if (p.perm != null && group.equals(p.perm.info.group)) {
3957                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3958                    }
3959                }
3960            }
3961            return new ParceledListSlice<>(out);
3962        }
3963    }
3964
3965    @Override
3966    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3967        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3968            return null;
3969        }
3970        // reader
3971        synchronized (mPackages) {
3972            return PackageParser.generatePermissionGroupInfo(
3973                    mPermissionGroups.get(name), flags);
3974        }
3975    }
3976
3977    @Override
3978    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3979        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3980            return ParceledListSlice.emptyList();
3981        }
3982        // reader
3983        synchronized (mPackages) {
3984            final int N = mPermissionGroups.size();
3985            ArrayList<PermissionGroupInfo> out
3986                    = new ArrayList<PermissionGroupInfo>(N);
3987            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3988                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3989            }
3990            return new ParceledListSlice<>(out);
3991        }
3992    }
3993
3994    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3995            int uid, int userId) {
3996        if (!sUserManager.exists(userId)) return null;
3997        PackageSetting ps = mSettings.mPackages.get(packageName);
3998        if (ps != null) {
3999            if (filterSharedLibPackageLPr(ps, uid, userId, flags)) {
4000                return null;
4001            }
4002            if (filterAppAccessLPr(ps, uid, userId)) {
4003                return null;
4004            }
4005            if (ps.pkg == null) {
4006                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4007                if (pInfo != null) {
4008                    return pInfo.applicationInfo;
4009                }
4010                return null;
4011            }
4012            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4013                    ps.readUserState(userId), userId);
4014            if (ai != null) {
4015                rebaseEnabledOverlays(ai, userId);
4016                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4017            }
4018            return ai;
4019        }
4020        return null;
4021    }
4022
4023    @Override
4024    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4025        if (!sUserManager.exists(userId)) return null;
4026        flags = updateFlagsForApplication(flags, userId, packageName);
4027        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4028                false /* requireFullPermission */, false /* checkShell */, "get application info");
4029
4030        // writer
4031        synchronized (mPackages) {
4032            // Normalize package name to handle renamed packages and static libs
4033            packageName = resolveInternalPackageNameLPr(packageName,
4034                    PackageManager.VERSION_CODE_HIGHEST);
4035
4036            PackageParser.Package p = mPackages.get(packageName);
4037            if (DEBUG_PACKAGE_INFO) Log.v(
4038                    TAG, "getApplicationInfo " + packageName
4039                    + ": " + p);
4040            if (p != null) {
4041                PackageSetting ps = mSettings.mPackages.get(packageName);
4042                if (ps == null) return null;
4043                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
4044                    return null;
4045                }
4046                if (filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
4047                    return null;
4048                }
4049                // Note: isEnabledLP() does not apply here - always return info
4050                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4051                        p, flags, ps.readUserState(userId), userId);
4052                if (ai != null) {
4053                    rebaseEnabledOverlays(ai, userId);
4054                    ai.packageName = resolveExternalPackageNameLPr(p);
4055                }
4056                return ai;
4057            }
4058            if ("android".equals(packageName)||"system".equals(packageName)) {
4059                return mAndroidApplication;
4060            }
4061            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4062                // Already generates the external package name
4063                return generateApplicationInfoFromSettingsLPw(packageName,
4064                        Binder.getCallingUid(), flags, userId);
4065            }
4066        }
4067        return null;
4068    }
4069
4070    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
4071        List<String> paths = new ArrayList<>();
4072        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
4073            mEnabledOverlayPaths.get(userId);
4074        if (userSpecificOverlays != null) {
4075            if (!"android".equals(ai.packageName)) {
4076                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
4077                if (frameworkOverlays != null) {
4078                    paths.addAll(frameworkOverlays);
4079                }
4080            }
4081
4082            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
4083            if (appOverlays != null) {
4084                paths.addAll(appOverlays);
4085            }
4086        }
4087        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
4088    }
4089
4090    private String normalizePackageNameLPr(String packageName) {
4091        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4092        return normalizedPackageName != null ? normalizedPackageName : packageName;
4093    }
4094
4095    @Override
4096    public void deletePreloadsFileCache() {
4097        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4098            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4099        }
4100        File dir = Environment.getDataPreloadsFileCacheDirectory();
4101        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4102        FileUtils.deleteContents(dir);
4103    }
4104
4105    @Override
4106    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4107            final IPackageDataObserver observer) {
4108        mContext.enforceCallingOrSelfPermission(
4109                android.Manifest.permission.CLEAR_APP_CACHE, null);
4110        mHandler.post(() -> {
4111            boolean success = false;
4112            try {
4113                freeStorage(volumeUuid, freeStorageSize, 0);
4114                success = true;
4115            } catch (IOException e) {
4116                Slog.w(TAG, e);
4117            }
4118            if (observer != null) {
4119                try {
4120                    observer.onRemoveCompleted(null, success);
4121                } catch (RemoteException e) {
4122                    Slog.w(TAG, e);
4123                }
4124            }
4125        });
4126    }
4127
4128    @Override
4129    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4130            final IntentSender pi) {
4131        mContext.enforceCallingOrSelfPermission(
4132                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4133        mHandler.post(() -> {
4134            boolean success = false;
4135            try {
4136                freeStorage(volumeUuid, freeStorageSize, 0);
4137                success = true;
4138            } catch (IOException e) {
4139                Slog.w(TAG, e);
4140            }
4141            if (pi != null) {
4142                try {
4143                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4144                } catch (SendIntentException e) {
4145                    Slog.w(TAG, e);
4146                }
4147            }
4148        });
4149    }
4150
4151    /**
4152     * Blocking call to clear various types of cached data across the system
4153     * until the requested bytes are available.
4154     */
4155    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4156        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4157        final File file = storage.findPathForUuid(volumeUuid);
4158        if (file.getUsableSpace() >= bytes) return;
4159
4160        if (ENABLE_FREE_CACHE_V2) {
4161            final boolean aggressive = (storageFlags
4162                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4163            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4164                    volumeUuid);
4165
4166            // 1. Pre-flight to determine if we have any chance to succeed
4167            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4168            if (internalVolume && (aggressive || SystemProperties
4169                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4170                deletePreloadsFileCache();
4171                if (file.getUsableSpace() >= bytes) return;
4172            }
4173
4174            // 3. Consider parsed APK data (aggressive only)
4175            if (internalVolume && aggressive) {
4176                FileUtils.deleteContents(mCacheDir);
4177                if (file.getUsableSpace() >= bytes) return;
4178            }
4179
4180            // 4. Consider cached app data (above quotas)
4181            try {
4182                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
4183            } catch (InstallerException ignored) {
4184            }
4185            if (file.getUsableSpace() >= bytes) return;
4186
4187            // 5. Consider shared libraries with refcount=0 and age>2h
4188            // 6. Consider dexopt output (aggressive only)
4189            // 7. Consider ephemeral apps not used in last week
4190
4191            // 8. Consider cached app data (below quotas)
4192            try {
4193                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
4194                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4195            } catch (InstallerException ignored) {
4196            }
4197            if (file.getUsableSpace() >= bytes) return;
4198
4199            // 9. Consider DropBox entries
4200            // 10. Consider ephemeral cookies
4201
4202        } else {
4203            try {
4204                mInstaller.freeCache(volumeUuid, bytes, 0);
4205            } catch (InstallerException ignored) {
4206            }
4207            if (file.getUsableSpace() >= bytes) return;
4208        }
4209
4210        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4211    }
4212
4213    /**
4214     * Update given flags based on encryption status of current user.
4215     */
4216    private int updateFlags(int flags, int userId) {
4217        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4218                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4219            // Caller expressed an explicit opinion about what encryption
4220            // aware/unaware components they want to see, so fall through and
4221            // give them what they want
4222        } else {
4223            // Caller expressed no opinion, so match based on user state
4224            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4225                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4226            } else {
4227                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4228            }
4229        }
4230        return flags;
4231    }
4232
4233    private UserManagerInternal getUserManagerInternal() {
4234        if (mUserManagerInternal == null) {
4235            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4236        }
4237        return mUserManagerInternal;
4238    }
4239
4240    private DeviceIdleController.LocalService getDeviceIdleController() {
4241        if (mDeviceIdleController == null) {
4242            mDeviceIdleController =
4243                    LocalServices.getService(DeviceIdleController.LocalService.class);
4244        }
4245        return mDeviceIdleController;
4246    }
4247
4248    /**
4249     * Update given flags when being used to request {@link PackageInfo}.
4250     */
4251    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4252        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4253        boolean triaged = true;
4254        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4255                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4256            // Caller is asking for component details, so they'd better be
4257            // asking for specific encryption matching behavior, or be triaged
4258            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4259                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4260                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4261                triaged = false;
4262            }
4263        }
4264        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4265                | PackageManager.MATCH_SYSTEM_ONLY
4266                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4267            triaged = false;
4268        }
4269        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4270            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4271                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4272                    + Debug.getCallers(5));
4273        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4274                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4275            // If the caller wants all packages and has a restricted profile associated with it,
4276            // then match all users. This is to make sure that launchers that need to access work
4277            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4278            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4279            flags |= PackageManager.MATCH_ANY_USER;
4280        }
4281        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4282            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4283                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4284        }
4285        return updateFlags(flags, userId);
4286    }
4287
4288    /**
4289     * Update given flags when being used to request {@link ApplicationInfo}.
4290     */
4291    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4292        return updateFlagsForPackage(flags, userId, cookie);
4293    }
4294
4295    /**
4296     * Update given flags when being used to request {@link ComponentInfo}.
4297     */
4298    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4299        if (cookie instanceof Intent) {
4300            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4301                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4302            }
4303        }
4304
4305        boolean triaged = true;
4306        // Caller is asking for component details, so they'd better be
4307        // asking for specific encryption matching behavior, or be triaged
4308        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4309                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4310                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4311            triaged = false;
4312        }
4313        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4314            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4315                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4316        }
4317
4318        return updateFlags(flags, userId);
4319    }
4320
4321    /**
4322     * Update given intent when being used to request {@link ResolveInfo}.
4323     */
4324    private Intent updateIntentForResolve(Intent intent) {
4325        if (intent.getSelector() != null) {
4326            intent = intent.getSelector();
4327        }
4328        if (DEBUG_PREFERRED) {
4329            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4330        }
4331        return intent;
4332    }
4333
4334    /**
4335     * Update given flags when being used to request {@link ResolveInfo}.
4336     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4337     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4338     * flag set. However, this flag is only honoured in three circumstances:
4339     * <ul>
4340     * <li>when called from a system process</li>
4341     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4342     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4343     * action and a {@code android.intent.category.BROWSABLE} category</li>
4344     * </ul>
4345     */
4346    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4347        return updateFlagsForResolve(flags, userId, intent, callingUid,
4348                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4349    }
4350    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4351            boolean wantInstantApps) {
4352        return updateFlagsForResolve(flags, userId, intent, callingUid,
4353                wantInstantApps, false /*onlyExposedExplicitly*/);
4354    }
4355    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4356            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4357        // Safe mode means we shouldn't match any third-party components
4358        if (mSafeMode) {
4359            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4360        }
4361        if (getInstantAppPackageName(callingUid) != null) {
4362            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4363            if (onlyExposedExplicitly) {
4364                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4365            }
4366            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4367            flags |= PackageManager.MATCH_INSTANT;
4368        } else {
4369            final boolean allowMatchInstant =
4370                    (wantInstantApps
4371                            && Intent.ACTION_VIEW.equals(intent.getAction())
4372                            && hasWebURI(intent))
4373                    || canAccessInstantApps(callingUid);
4374            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4375                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4376            if (!allowMatchInstant) {
4377                flags &= ~PackageManager.MATCH_INSTANT;
4378            }
4379        }
4380        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4381    }
4382
4383    private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state,
4384            int userId) {
4385        ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId);
4386        if (ret != null) {
4387            rebaseEnabledOverlays(ret.applicationInfo, userId);
4388        }
4389        return ret;
4390    }
4391
4392    private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags,
4393            PackageUserState state, int userId) {
4394        ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId);
4395        if (ai != null) {
4396            rebaseEnabledOverlays(ai.applicationInfo, userId);
4397        }
4398        return ai;
4399    }
4400
4401    @Override
4402    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4403        if (!sUserManager.exists(userId)) return null;
4404        final int callingUid = Binder.getCallingUid();
4405        flags = updateFlagsForComponent(flags, userId, component);
4406        enforceCrossUserPermission(callingUid, userId,
4407                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4408        synchronized (mPackages) {
4409            PackageParser.Activity a = mActivities.mActivities.get(component);
4410
4411            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4412            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4413                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4414                if (ps == null) return null;
4415                final boolean visibleToInstantApp =
4416                        (a.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4417                if (filterAppAccessLPr(ps, callingUid, component, visibleToInstantApp, userId)) {
4418                    return null;
4419                }
4420                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4421            }
4422            if (mResolveComponentName.equals(component)) {
4423                return generateActivityInfo(mResolveActivity, flags, new PackageUserState(),
4424                        userId);
4425            }
4426        }
4427        return null;
4428    }
4429
4430    @Override
4431    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4432            String resolvedType) {
4433        synchronized (mPackages) {
4434            if (component.equals(mResolveComponentName)) {
4435                // The resolver supports EVERYTHING!
4436                return true;
4437            }
4438            final int callingUid = Binder.getCallingUid();
4439            final int callingUserId = UserHandle.getUserId(callingUid);
4440            PackageParser.Activity a = mActivities.mActivities.get(component);
4441            if (a == null) {
4442                return false;
4443            }
4444            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4445            if (ps == null) {
4446                return false;
4447            }
4448            final boolean visibleToInstantApp =
4449                    (a.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4450            if (filterAppAccessLPr(ps, callingUid, component, visibleToInstantApp, callingUserId)) {
4451                return false;
4452            }
4453            for (int i=0; i<a.intents.size(); i++) {
4454                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4455                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4456                    return true;
4457                }
4458            }
4459            return false;
4460        }
4461    }
4462
4463    @Override
4464    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4465        if (!sUserManager.exists(userId)) return null;
4466        flags = updateFlagsForComponent(flags, userId, component);
4467        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4468                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4469        synchronized (mPackages) {
4470            PackageParser.Activity a = mReceivers.mActivities.get(component);
4471            if (DEBUG_PACKAGE_INFO) Log.v(
4472                TAG, "getReceiverInfo " + component + ": " + a);
4473            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4474                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4475                if (ps == null) return null;
4476                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4477            }
4478        }
4479        return null;
4480    }
4481
4482    @Override
4483    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4484            int flags, int userId) {
4485        if (!sUserManager.exists(userId)) return null;
4486        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4487        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4488            return null;
4489        }
4490
4491        flags = updateFlagsForPackage(flags, userId, null);
4492
4493        final boolean canSeeStaticLibraries =
4494                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4495                        == PERMISSION_GRANTED
4496                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4497                        == PERMISSION_GRANTED
4498                || canRequestPackageInstallsInternal(packageName,
4499                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4500                        false  /* throwIfPermNotDeclared*/)
4501                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4502                        == PERMISSION_GRANTED;
4503
4504        synchronized (mPackages) {
4505            List<SharedLibraryInfo> result = null;
4506
4507            final int libCount = mSharedLibraries.size();
4508            for (int i = 0; i < libCount; i++) {
4509                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4510                if (versionedLib == null) {
4511                    continue;
4512                }
4513
4514                final int versionCount = versionedLib.size();
4515                for (int j = 0; j < versionCount; j++) {
4516                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4517                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4518                        break;
4519                    }
4520                    final long identity = Binder.clearCallingIdentity();
4521                    try {
4522                        PackageInfo packageInfo = getPackageInfoVersioned(
4523                                libInfo.getDeclaringPackage(), flags
4524                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4525                        if (packageInfo == null) {
4526                            continue;
4527                        }
4528                    } finally {
4529                        Binder.restoreCallingIdentity(identity);
4530                    }
4531
4532                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4533                            libInfo.getVersion(), libInfo.getType(),
4534                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4535                            flags, userId));
4536
4537                    if (result == null) {
4538                        result = new ArrayList<>();
4539                    }
4540                    result.add(resLibInfo);
4541                }
4542            }
4543
4544            return result != null ? new ParceledListSlice<>(result) : null;
4545        }
4546    }
4547
4548    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4549            SharedLibraryInfo libInfo, int flags, int userId) {
4550        List<VersionedPackage> versionedPackages = null;
4551        final int packageCount = mSettings.mPackages.size();
4552        for (int i = 0; i < packageCount; i++) {
4553            PackageSetting ps = mSettings.mPackages.valueAt(i);
4554
4555            if (ps == null) {
4556                continue;
4557            }
4558
4559            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4560                continue;
4561            }
4562
4563            final String libName = libInfo.getName();
4564            if (libInfo.isStatic()) {
4565                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4566                if (libIdx < 0) {
4567                    continue;
4568                }
4569                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4570                    continue;
4571                }
4572                if (versionedPackages == null) {
4573                    versionedPackages = new ArrayList<>();
4574                }
4575                // If the dependent is a static shared lib, use the public package name
4576                String dependentPackageName = ps.name;
4577                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4578                    dependentPackageName = ps.pkg.manifestPackageName;
4579                }
4580                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4581            } else if (ps.pkg != null) {
4582                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4583                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4584                    if (versionedPackages == null) {
4585                        versionedPackages = new ArrayList<>();
4586                    }
4587                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4588                }
4589            }
4590        }
4591
4592        return versionedPackages;
4593    }
4594
4595    @Override
4596    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4597        if (!sUserManager.exists(userId)) return null;
4598        final int callingUid = Binder.getCallingUid();
4599        flags = updateFlagsForComponent(flags, userId, component);
4600        enforceCrossUserPermission(callingUid, userId,
4601                false /* requireFullPermission */, false /* checkShell */, "get service info");
4602        synchronized (mPackages) {
4603            PackageParser.Service s = mServices.mServices.get(component);
4604            if (DEBUG_PACKAGE_INFO) Log.v(
4605                TAG, "getServiceInfo " + component + ": " + s);
4606            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4607                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4608                if (ps == null) return null;
4609                final boolean visibleToInstantApp =
4610                        (s.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4611                if (filterAppAccessLPr(ps, callingUid, component, visibleToInstantApp, userId)) {
4612                    return null;
4613                }
4614                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4615                        ps.readUserState(userId), userId);
4616                if (si != null) {
4617                    rebaseEnabledOverlays(si.applicationInfo, userId);
4618                }
4619                return si;
4620            }
4621        }
4622        return null;
4623    }
4624
4625    @Override
4626    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4627        if (!sUserManager.exists(userId)) return null;
4628        final int callingUid = Binder.getCallingUid();
4629        flags = updateFlagsForComponent(flags, userId, component);
4630        enforceCrossUserPermission(callingUid, userId,
4631                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4632        synchronized (mPackages) {
4633            PackageParser.Provider p = mProviders.mProviders.get(component);
4634            if (DEBUG_PACKAGE_INFO) Log.v(
4635                TAG, "getProviderInfo " + component + ": " + p);
4636            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4637                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4638                if (ps == null) return null;
4639                final boolean visibleToInstantApp =
4640                        (p.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4641                if (filterAppAccessLPr(ps, callingUid, component, visibleToInstantApp, userId)) {
4642                    return null;
4643                }
4644                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4645                        ps.readUserState(userId), userId);
4646                if (pi != null) {
4647                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4648                }
4649                return pi;
4650            }
4651        }
4652        return null;
4653    }
4654
4655    @Override
4656    public String[] getSystemSharedLibraryNames() {
4657        // allow instant applications
4658        synchronized (mPackages) {
4659            Set<String> libs = null;
4660            final int libCount = mSharedLibraries.size();
4661            for (int i = 0; i < libCount; i++) {
4662                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4663                if (versionedLib == null) {
4664                    continue;
4665                }
4666                final int versionCount = versionedLib.size();
4667                for (int j = 0; j < versionCount; j++) {
4668                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4669                    if (!libEntry.info.isStatic()) {
4670                        if (libs == null) {
4671                            libs = new ArraySet<>();
4672                        }
4673                        libs.add(libEntry.info.getName());
4674                        break;
4675                    }
4676                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4677                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4678                            UserHandle.getUserId(Binder.getCallingUid()),
4679                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4680                        if (libs == null) {
4681                            libs = new ArraySet<>();
4682                        }
4683                        libs.add(libEntry.info.getName());
4684                        break;
4685                    }
4686                }
4687            }
4688
4689            if (libs != null) {
4690                String[] libsArray = new String[libs.size()];
4691                libs.toArray(libsArray);
4692                return libsArray;
4693            }
4694
4695            return null;
4696        }
4697    }
4698
4699    @Override
4700    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4701        // allow instant applications
4702        synchronized (mPackages) {
4703            return mServicesSystemSharedLibraryPackageName;
4704        }
4705    }
4706
4707    @Override
4708    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4709        // allow instant applications
4710        synchronized (mPackages) {
4711            return mSharedSystemSharedLibraryPackageName;
4712        }
4713    }
4714
4715    private void updateSequenceNumberLP(String packageName, int[] userList) {
4716        for (int i = userList.length - 1; i >= 0; --i) {
4717            final int userId = userList[i];
4718            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4719            if (changedPackages == null) {
4720                changedPackages = new SparseArray<>();
4721                mChangedPackages.put(userId, changedPackages);
4722            }
4723            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4724            if (sequenceNumbers == null) {
4725                sequenceNumbers = new HashMap<>();
4726                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4727            }
4728            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4729            if (sequenceNumber != null) {
4730                changedPackages.remove(sequenceNumber);
4731            }
4732            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4733            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4734        }
4735        mChangedPackagesSequenceNumber++;
4736    }
4737
4738    @Override
4739    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4740        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4741            return null;
4742        }
4743        synchronized (mPackages) {
4744            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4745                return null;
4746            }
4747            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4748            if (changedPackages == null) {
4749                return null;
4750            }
4751            final List<String> packageNames =
4752                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4753            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4754                final String packageName = changedPackages.get(i);
4755                if (packageName != null) {
4756                    packageNames.add(packageName);
4757                }
4758            }
4759            return packageNames.isEmpty()
4760                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4761        }
4762    }
4763
4764    @Override
4765    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4766        // allow instant applications
4767        ArrayList<FeatureInfo> res;
4768        synchronized (mAvailableFeatures) {
4769            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4770            res.addAll(mAvailableFeatures.values());
4771        }
4772        final FeatureInfo fi = new FeatureInfo();
4773        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4774                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4775        res.add(fi);
4776
4777        return new ParceledListSlice<>(res);
4778    }
4779
4780    @Override
4781    public boolean hasSystemFeature(String name, int version) {
4782        // allow instant applications
4783        synchronized (mAvailableFeatures) {
4784            final FeatureInfo feat = mAvailableFeatures.get(name);
4785            if (feat == null) {
4786                return false;
4787            } else {
4788                return feat.version >= version;
4789            }
4790        }
4791    }
4792
4793    @Override
4794    public int checkPermission(String permName, String pkgName, int userId) {
4795        if (!sUserManager.exists(userId)) {
4796            return PackageManager.PERMISSION_DENIED;
4797        }
4798        final int callingUid = Binder.getCallingUid();
4799
4800        synchronized (mPackages) {
4801            final PackageParser.Package p = mPackages.get(pkgName);
4802            if (p != null && p.mExtras != null) {
4803                final PackageSetting ps = (PackageSetting) p.mExtras;
4804                if (filterAppAccessLPr(ps, callingUid, userId)) {
4805                    return PackageManager.PERMISSION_DENIED;
4806                }
4807                final PermissionsState permissionsState = ps.getPermissionsState();
4808                if (permissionsState.hasPermission(permName, userId)) {
4809                    return PackageManager.PERMISSION_GRANTED;
4810                }
4811                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4812                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4813                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4814                    return PackageManager.PERMISSION_GRANTED;
4815                }
4816            }
4817        }
4818
4819        return PackageManager.PERMISSION_DENIED;
4820    }
4821
4822    @Override
4823    public int checkUidPermission(String permName, int uid) {
4824        final int callingUid = Binder.getCallingUid();
4825        final int callingUserId = UserHandle.getUserId(callingUid);
4826        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
4827        final int userId = UserHandle.getUserId(uid);
4828        if (!sUserManager.exists(userId)) {
4829            return PackageManager.PERMISSION_DENIED;
4830        }
4831
4832        synchronized (mPackages) {
4833            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4834            if (obj != null) {
4835                if (obj instanceof SharedUserSetting) {
4836                    if (isCallerInstantApp) {
4837                        return PackageManager.PERMISSION_DENIED;
4838                    }
4839                } else if (obj instanceof PackageSetting) {
4840                    final PackageSetting ps = (PackageSetting) obj;
4841                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
4842                        return PackageManager.PERMISSION_DENIED;
4843                    }
4844                }
4845                final SettingBase settingBase = (SettingBase) obj;
4846                final PermissionsState permissionsState = settingBase.getPermissionsState();
4847                if (permissionsState.hasPermission(permName, userId)) {
4848                    return PackageManager.PERMISSION_GRANTED;
4849                }
4850                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4851                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4852                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4853                    return PackageManager.PERMISSION_GRANTED;
4854                }
4855            } else {
4856                ArraySet<String> perms = mSystemPermissions.get(uid);
4857                if (perms != null) {
4858                    if (perms.contains(permName)) {
4859                        return PackageManager.PERMISSION_GRANTED;
4860                    }
4861                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4862                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4863                        return PackageManager.PERMISSION_GRANTED;
4864                    }
4865                }
4866            }
4867        }
4868
4869        return PackageManager.PERMISSION_DENIED;
4870    }
4871
4872    @Override
4873    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4874        if (UserHandle.getCallingUserId() != userId) {
4875            mContext.enforceCallingPermission(
4876                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4877                    "isPermissionRevokedByPolicy for user " + userId);
4878        }
4879
4880        if (checkPermission(permission, packageName, userId)
4881                == PackageManager.PERMISSION_GRANTED) {
4882            return false;
4883        }
4884
4885        final int callingUid = Binder.getCallingUid();
4886        if (getInstantAppPackageName(callingUid) != null) {
4887            if (!isCallerSameApp(packageName, callingUid)) {
4888                return false;
4889            }
4890        } else {
4891            if (isInstantApp(packageName, userId)) {
4892                return false;
4893            }
4894        }
4895
4896        final long identity = Binder.clearCallingIdentity();
4897        try {
4898            final int flags = getPermissionFlags(permission, packageName, userId);
4899            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4900        } finally {
4901            Binder.restoreCallingIdentity(identity);
4902        }
4903    }
4904
4905    @Override
4906    public String getPermissionControllerPackageName() {
4907        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4908            throw new SecurityException("Instant applications don't have access to this method");
4909        }
4910        synchronized (mPackages) {
4911            return mRequiredInstallerPackage;
4912        }
4913    }
4914
4915    /**
4916     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4917     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4918     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4919     * @param message the message to log on security exception
4920     */
4921    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4922            boolean checkShell, String message) {
4923        if (userId < 0) {
4924            throw new IllegalArgumentException("Invalid userId " + userId);
4925        }
4926        if (checkShell) {
4927            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4928        }
4929        if (userId == UserHandle.getUserId(callingUid)) return;
4930        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4931            if (requireFullPermission) {
4932                mContext.enforceCallingOrSelfPermission(
4933                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4934            } else {
4935                try {
4936                    mContext.enforceCallingOrSelfPermission(
4937                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4938                } catch (SecurityException se) {
4939                    mContext.enforceCallingOrSelfPermission(
4940                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4941                }
4942            }
4943        }
4944    }
4945
4946    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4947        if (callingUid == Process.SHELL_UID) {
4948            if (userHandle >= 0
4949                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4950                throw new SecurityException("Shell does not have permission to access user "
4951                        + userHandle);
4952            } else if (userHandle < 0) {
4953                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4954                        + Debug.getCallers(3));
4955            }
4956        }
4957    }
4958
4959    private BasePermission findPermissionTreeLP(String permName) {
4960        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4961            if (permName.startsWith(bp.name) &&
4962                    permName.length() > bp.name.length() &&
4963                    permName.charAt(bp.name.length()) == '.') {
4964                return bp;
4965            }
4966        }
4967        return null;
4968    }
4969
4970    private BasePermission checkPermissionTreeLP(String permName) {
4971        if (permName != null) {
4972            BasePermission bp = findPermissionTreeLP(permName);
4973            if (bp != null) {
4974                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4975                    return bp;
4976                }
4977                throw new SecurityException("Calling uid "
4978                        + Binder.getCallingUid()
4979                        + " is not allowed to add to permission tree "
4980                        + bp.name + " owned by uid " + bp.uid);
4981            }
4982        }
4983        throw new SecurityException("No permission tree found for " + permName);
4984    }
4985
4986    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4987        if (s1 == null) {
4988            return s2 == null;
4989        }
4990        if (s2 == null) {
4991            return false;
4992        }
4993        if (s1.getClass() != s2.getClass()) {
4994            return false;
4995        }
4996        return s1.equals(s2);
4997    }
4998
4999    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5000        if (pi1.icon != pi2.icon) return false;
5001        if (pi1.logo != pi2.logo) return false;
5002        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5003        if (!compareStrings(pi1.name, pi2.name)) return false;
5004        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5005        // We'll take care of setting this one.
5006        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5007        // These are not currently stored in settings.
5008        //if (!compareStrings(pi1.group, pi2.group)) return false;
5009        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5010        //if (pi1.labelRes != pi2.labelRes) return false;
5011        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5012        return true;
5013    }
5014
5015    int permissionInfoFootprint(PermissionInfo info) {
5016        int size = info.name.length();
5017        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5018        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5019        return size;
5020    }
5021
5022    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5023        int size = 0;
5024        for (BasePermission perm : mSettings.mPermissions.values()) {
5025            if (perm.uid == tree.uid) {
5026                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5027            }
5028        }
5029        return size;
5030    }
5031
5032    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5033        // We calculate the max size of permissions defined by this uid and throw
5034        // if that plus the size of 'info' would exceed our stated maximum.
5035        if (tree.uid != Process.SYSTEM_UID) {
5036            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5037            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5038                throw new SecurityException("Permission tree size cap exceeded");
5039            }
5040        }
5041    }
5042
5043    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5044        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5045            throw new SecurityException("Instant apps can't add permissions");
5046        }
5047        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5048            throw new SecurityException("Label must be specified in permission");
5049        }
5050        BasePermission tree = checkPermissionTreeLP(info.name);
5051        BasePermission bp = mSettings.mPermissions.get(info.name);
5052        boolean added = bp == null;
5053        boolean changed = true;
5054        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5055        if (added) {
5056            enforcePermissionCapLocked(info, tree);
5057            bp = new BasePermission(info.name, tree.sourcePackage,
5058                    BasePermission.TYPE_DYNAMIC);
5059        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5060            throw new SecurityException(
5061                    "Not allowed to modify non-dynamic permission "
5062                    + info.name);
5063        } else {
5064            if (bp.protectionLevel == fixedLevel
5065                    && bp.perm.owner.equals(tree.perm.owner)
5066                    && bp.uid == tree.uid
5067                    && comparePermissionInfos(bp.perm.info, info)) {
5068                changed = false;
5069            }
5070        }
5071        bp.protectionLevel = fixedLevel;
5072        info = new PermissionInfo(info);
5073        info.protectionLevel = fixedLevel;
5074        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5075        bp.perm.info.packageName = tree.perm.info.packageName;
5076        bp.uid = tree.uid;
5077        if (added) {
5078            mSettings.mPermissions.put(info.name, bp);
5079        }
5080        if (changed) {
5081            if (!async) {
5082                mSettings.writeLPr();
5083            } else {
5084                scheduleWriteSettingsLocked();
5085            }
5086        }
5087        return added;
5088    }
5089
5090    @Override
5091    public boolean addPermission(PermissionInfo info) {
5092        synchronized (mPackages) {
5093            return addPermissionLocked(info, false);
5094        }
5095    }
5096
5097    @Override
5098    public boolean addPermissionAsync(PermissionInfo info) {
5099        synchronized (mPackages) {
5100            return addPermissionLocked(info, true);
5101        }
5102    }
5103
5104    @Override
5105    public void removePermission(String name) {
5106        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5107            throw new SecurityException("Instant applications don't have access to this method");
5108        }
5109        synchronized (mPackages) {
5110            checkPermissionTreeLP(name);
5111            BasePermission bp = mSettings.mPermissions.get(name);
5112            if (bp != null) {
5113                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5114                    throw new SecurityException(
5115                            "Not allowed to modify non-dynamic permission "
5116                            + name);
5117                }
5118                mSettings.mPermissions.remove(name);
5119                mSettings.writeLPr();
5120            }
5121        }
5122    }
5123
5124    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5125            PackageParser.Package pkg, BasePermission bp) {
5126        int index = pkg.requestedPermissions.indexOf(bp.name);
5127        if (index == -1) {
5128            throw new SecurityException("Package " + pkg.packageName
5129                    + " has not requested permission " + bp.name);
5130        }
5131        if (!bp.isRuntime() && !bp.isDevelopment()) {
5132            throw new SecurityException("Permission " + bp.name
5133                    + " is not a changeable permission type");
5134        }
5135    }
5136
5137    @Override
5138    public void grantRuntimePermission(String packageName, String name, final int userId) {
5139        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5140    }
5141
5142    private void grantRuntimePermission(String packageName, String name, final int userId,
5143            boolean overridePolicy) {
5144        if (!sUserManager.exists(userId)) {
5145            Log.e(TAG, "No such user:" + userId);
5146            return;
5147        }
5148
5149        mContext.enforceCallingOrSelfPermission(
5150                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5151                "grantRuntimePermission");
5152
5153        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5154                true /* requireFullPermission */, true /* checkShell */,
5155                "grantRuntimePermission");
5156
5157        final int uid;
5158        final SettingBase sb;
5159
5160        synchronized (mPackages) {
5161            final PackageParser.Package pkg = mPackages.get(packageName);
5162            if (pkg == null) {
5163                throw new IllegalArgumentException("Unknown package: " + packageName);
5164            }
5165
5166            final BasePermission bp = mSettings.mPermissions.get(name);
5167            if (bp == null) {
5168                throw new IllegalArgumentException("Unknown permission: " + name);
5169            }
5170
5171            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5172
5173            // If a permission review is required for legacy apps we represent
5174            // their permissions as always granted runtime ones since we need
5175            // to keep the review required permission flag per user while an
5176            // install permission's state is shared across all users.
5177            if (mPermissionReviewRequired
5178                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5179                    && bp.isRuntime()) {
5180                return;
5181            }
5182
5183            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5184            sb = (SettingBase) pkg.mExtras;
5185            if (sb == null) {
5186                throw new IllegalArgumentException("Unknown package: " + packageName);
5187            }
5188
5189            final PermissionsState permissionsState = sb.getPermissionsState();
5190
5191            final int flags = permissionsState.getPermissionFlags(name, userId);
5192            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5193                throw new SecurityException("Cannot grant system fixed permission "
5194                        + name + " for package " + packageName);
5195            }
5196            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5197                throw new SecurityException("Cannot grant policy fixed permission "
5198                        + name + " for package " + packageName);
5199            }
5200
5201            if (bp.isDevelopment()) {
5202                // Development permissions must be handled specially, since they are not
5203                // normal runtime permissions.  For now they apply to all users.
5204                if (permissionsState.grantInstallPermission(bp) !=
5205                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5206                    scheduleWriteSettingsLocked();
5207                }
5208                return;
5209            }
5210
5211            final PackageSetting ps = mSettings.mPackages.get(packageName);
5212            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5213                throw new SecurityException("Cannot grant non-ephemeral permission"
5214                        + name + " for package " + packageName);
5215            }
5216
5217            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5218                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5219                return;
5220            }
5221
5222            final int result = permissionsState.grantRuntimePermission(bp, userId);
5223            switch (result) {
5224                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5225                    return;
5226                }
5227
5228                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5229                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5230                    mHandler.post(new Runnable() {
5231                        @Override
5232                        public void run() {
5233                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5234                        }
5235                    });
5236                }
5237                break;
5238            }
5239
5240            if (bp.isRuntime()) {
5241                logPermissionGranted(mContext, name, packageName);
5242            }
5243
5244            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5245
5246            // Not critical if that is lost - app has to request again.
5247            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5248        }
5249
5250        // Only need to do this if user is initialized. Otherwise it's a new user
5251        // and there are no processes running as the user yet and there's no need
5252        // to make an expensive call to remount processes for the changed permissions.
5253        if (READ_EXTERNAL_STORAGE.equals(name)
5254                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5255            final long token = Binder.clearCallingIdentity();
5256            try {
5257                if (sUserManager.isInitialized(userId)) {
5258                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5259                            StorageManagerInternal.class);
5260                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5261                }
5262            } finally {
5263                Binder.restoreCallingIdentity(token);
5264            }
5265        }
5266    }
5267
5268    @Override
5269    public void revokeRuntimePermission(String packageName, String name, int userId) {
5270        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5271    }
5272
5273    private void revokeRuntimePermission(String packageName, String name, int userId,
5274            boolean overridePolicy) {
5275        if (!sUserManager.exists(userId)) {
5276            Log.e(TAG, "No such user:" + userId);
5277            return;
5278        }
5279
5280        mContext.enforceCallingOrSelfPermission(
5281                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5282                "revokeRuntimePermission");
5283
5284        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5285                true /* requireFullPermission */, true /* checkShell */,
5286                "revokeRuntimePermission");
5287
5288        final int appId;
5289
5290        synchronized (mPackages) {
5291            final PackageParser.Package pkg = mPackages.get(packageName);
5292            if (pkg == null) {
5293                throw new IllegalArgumentException("Unknown package: " + packageName);
5294            }
5295
5296            final BasePermission bp = mSettings.mPermissions.get(name);
5297            if (bp == null) {
5298                throw new IllegalArgumentException("Unknown permission: " + name);
5299            }
5300
5301            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5302
5303            // If a permission review is required for legacy apps we represent
5304            // their permissions as always granted runtime ones since we need
5305            // to keep the review required permission flag per user while an
5306            // install permission's state is shared across all users.
5307            if (mPermissionReviewRequired
5308                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5309                    && bp.isRuntime()) {
5310                return;
5311            }
5312
5313            SettingBase sb = (SettingBase) pkg.mExtras;
5314            if (sb == null) {
5315                throw new IllegalArgumentException("Unknown package: " + packageName);
5316            }
5317
5318            final PermissionsState permissionsState = sb.getPermissionsState();
5319
5320            final int flags = permissionsState.getPermissionFlags(name, userId);
5321            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5322                throw new SecurityException("Cannot revoke system fixed permission "
5323                        + name + " for package " + packageName);
5324            }
5325            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5326                throw new SecurityException("Cannot revoke policy fixed permission "
5327                        + name + " for package " + packageName);
5328            }
5329
5330            if (bp.isDevelopment()) {
5331                // Development permissions must be handled specially, since they are not
5332                // normal runtime permissions.  For now they apply to all users.
5333                if (permissionsState.revokeInstallPermission(bp) !=
5334                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5335                    scheduleWriteSettingsLocked();
5336                }
5337                return;
5338            }
5339
5340            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5341                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5342                return;
5343            }
5344
5345            if (bp.isRuntime()) {
5346                logPermissionRevoked(mContext, name, packageName);
5347            }
5348
5349            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5350
5351            // Critical, after this call app should never have the permission.
5352            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5353
5354            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5355        }
5356
5357        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5358    }
5359
5360    /**
5361     * Get the first event id for the permission.
5362     *
5363     * <p>There are four events for each permission: <ul>
5364     *     <li>Request permission: first id + 0</li>
5365     *     <li>Grant permission: first id + 1</li>
5366     *     <li>Request for permission denied: first id + 2</li>
5367     *     <li>Revoke permission: first id + 3</li>
5368     * </ul></p>
5369     *
5370     * @param name name of the permission
5371     *
5372     * @return The first event id for the permission
5373     */
5374    private static int getBaseEventId(@NonNull String name) {
5375        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5376
5377        if (eventIdIndex == -1) {
5378            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5379                    || "user".equals(Build.TYPE)) {
5380                Log.i(TAG, "Unknown permission " + name);
5381
5382                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5383            } else {
5384                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5385                //
5386                // Also update
5387                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5388                // - metrics_constants.proto
5389                throw new IllegalStateException("Unknown permission " + name);
5390            }
5391        }
5392
5393        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5394    }
5395
5396    /**
5397     * Log that a permission was revoked.
5398     *
5399     * @param context Context of the caller
5400     * @param name name of the permission
5401     * @param packageName package permission if for
5402     */
5403    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5404            @NonNull String packageName) {
5405        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5406    }
5407
5408    /**
5409     * Log that a permission request was granted.
5410     *
5411     * @param context Context of the caller
5412     * @param name name of the permission
5413     * @param packageName package permission if for
5414     */
5415    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5416            @NonNull String packageName) {
5417        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5418    }
5419
5420    @Override
5421    public void resetRuntimePermissions() {
5422        mContext.enforceCallingOrSelfPermission(
5423                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5424                "revokeRuntimePermission");
5425
5426        int callingUid = Binder.getCallingUid();
5427        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5428            mContext.enforceCallingOrSelfPermission(
5429                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5430                    "resetRuntimePermissions");
5431        }
5432
5433        synchronized (mPackages) {
5434            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5435            for (int userId : UserManagerService.getInstance().getUserIds()) {
5436                final int packageCount = mPackages.size();
5437                for (int i = 0; i < packageCount; i++) {
5438                    PackageParser.Package pkg = mPackages.valueAt(i);
5439                    if (!(pkg.mExtras instanceof PackageSetting)) {
5440                        continue;
5441                    }
5442                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5443                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5444                }
5445            }
5446        }
5447    }
5448
5449    @Override
5450    public int getPermissionFlags(String name, String packageName, int userId) {
5451        if (!sUserManager.exists(userId)) {
5452            return 0;
5453        }
5454
5455        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5456
5457        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5458                true /* requireFullPermission */, false /* checkShell */,
5459                "getPermissionFlags");
5460
5461        synchronized (mPackages) {
5462            final PackageParser.Package pkg = mPackages.get(packageName);
5463            if (pkg == null) {
5464                return 0;
5465            }
5466
5467            final BasePermission bp = mSettings.mPermissions.get(name);
5468            if (bp == null) {
5469                return 0;
5470            }
5471
5472            SettingBase sb = (SettingBase) pkg.mExtras;
5473            if (sb == null) {
5474                return 0;
5475            }
5476
5477            PermissionsState permissionsState = sb.getPermissionsState();
5478            return permissionsState.getPermissionFlags(name, userId);
5479        }
5480    }
5481
5482    @Override
5483    public void updatePermissionFlags(String name, String packageName, int flagMask,
5484            int flagValues, int userId) {
5485        if (!sUserManager.exists(userId)) {
5486            return;
5487        }
5488
5489        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5490
5491        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5492                true /* requireFullPermission */, true /* checkShell */,
5493                "updatePermissionFlags");
5494
5495        // Only the system can change these flags and nothing else.
5496        if (getCallingUid() != Process.SYSTEM_UID) {
5497            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5498            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5499            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5500            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5501            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5502        }
5503
5504        synchronized (mPackages) {
5505            final PackageParser.Package pkg = mPackages.get(packageName);
5506            if (pkg == null) {
5507                throw new IllegalArgumentException("Unknown package: " + packageName);
5508            }
5509
5510            final BasePermission bp = mSettings.mPermissions.get(name);
5511            if (bp == null) {
5512                throw new IllegalArgumentException("Unknown permission: " + name);
5513            }
5514
5515            SettingBase sb = (SettingBase) pkg.mExtras;
5516            if (sb == null) {
5517                throw new IllegalArgumentException("Unknown package: " + packageName);
5518            }
5519
5520            PermissionsState permissionsState = sb.getPermissionsState();
5521
5522            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5523
5524            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5525                // Install and runtime permissions are stored in different places,
5526                // so figure out what permission changed and persist the change.
5527                if (permissionsState.getInstallPermissionState(name) != null) {
5528                    scheduleWriteSettingsLocked();
5529                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5530                        || hadState) {
5531                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5532                }
5533            }
5534        }
5535    }
5536
5537    /**
5538     * Update the permission flags for all packages and runtime permissions of a user in order
5539     * to allow device or profile owner to remove POLICY_FIXED.
5540     */
5541    @Override
5542    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5543        if (!sUserManager.exists(userId)) {
5544            return;
5545        }
5546
5547        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5548
5549        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5550                true /* requireFullPermission */, true /* checkShell */,
5551                "updatePermissionFlagsForAllApps");
5552
5553        // Only the system can change system fixed flags.
5554        if (getCallingUid() != Process.SYSTEM_UID) {
5555            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5556            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5557        }
5558
5559        synchronized (mPackages) {
5560            boolean changed = false;
5561            final int packageCount = mPackages.size();
5562            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5563                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5564                SettingBase sb = (SettingBase) pkg.mExtras;
5565                if (sb == null) {
5566                    continue;
5567                }
5568                PermissionsState permissionsState = sb.getPermissionsState();
5569                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5570                        userId, flagMask, flagValues);
5571            }
5572            if (changed) {
5573                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5574            }
5575        }
5576    }
5577
5578    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5579        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5580                != PackageManager.PERMISSION_GRANTED
5581            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5582                != PackageManager.PERMISSION_GRANTED) {
5583            throw new SecurityException(message + " requires "
5584                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5585                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5586        }
5587    }
5588
5589    @Override
5590    public boolean shouldShowRequestPermissionRationale(String permissionName,
5591            String packageName, int userId) {
5592        if (UserHandle.getCallingUserId() != userId) {
5593            mContext.enforceCallingPermission(
5594                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5595                    "canShowRequestPermissionRationale for user " + userId);
5596        }
5597
5598        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5599        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5600            return false;
5601        }
5602
5603        if (checkPermission(permissionName, packageName, userId)
5604                == PackageManager.PERMISSION_GRANTED) {
5605            return false;
5606        }
5607
5608        final int flags;
5609
5610        final long identity = Binder.clearCallingIdentity();
5611        try {
5612            flags = getPermissionFlags(permissionName,
5613                    packageName, userId);
5614        } finally {
5615            Binder.restoreCallingIdentity(identity);
5616        }
5617
5618        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5619                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5620                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5621
5622        if ((flags & fixedFlags) != 0) {
5623            return false;
5624        }
5625
5626        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5627    }
5628
5629    @Override
5630    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5631        mContext.enforceCallingOrSelfPermission(
5632                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5633                "addOnPermissionsChangeListener");
5634
5635        synchronized (mPackages) {
5636            mOnPermissionChangeListeners.addListenerLocked(listener);
5637        }
5638    }
5639
5640    @Override
5641    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5642        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5643            throw new SecurityException("Instant applications don't have access to this method");
5644        }
5645        synchronized (mPackages) {
5646            mOnPermissionChangeListeners.removeListenerLocked(listener);
5647        }
5648    }
5649
5650    @Override
5651    public boolean isProtectedBroadcast(String actionName) {
5652        // allow instant applications
5653        synchronized (mPackages) {
5654            if (mProtectedBroadcasts.contains(actionName)) {
5655                return true;
5656            } else if (actionName != null) {
5657                // TODO: remove these terrible hacks
5658                if (actionName.startsWith("android.net.netmon.lingerExpired")
5659                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5660                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5661                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5662                    return true;
5663                }
5664            }
5665        }
5666        return false;
5667    }
5668
5669    @Override
5670    public int checkSignatures(String pkg1, String pkg2) {
5671        synchronized (mPackages) {
5672            final PackageParser.Package p1 = mPackages.get(pkg1);
5673            final PackageParser.Package p2 = mPackages.get(pkg2);
5674            if (p1 == null || p1.mExtras == null
5675                    || p2 == null || p2.mExtras == null) {
5676                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5677            }
5678            final int callingUid = Binder.getCallingUid();
5679            final int callingUserId = UserHandle.getUserId(callingUid);
5680            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5681            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5682            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5683                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5684                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5685            }
5686            return compareSignatures(p1.mSignatures, p2.mSignatures);
5687        }
5688    }
5689
5690    @Override
5691    public int checkUidSignatures(int uid1, int uid2) {
5692        final int callingUid = Binder.getCallingUid();
5693        final int callingUserId = UserHandle.getUserId(callingUid);
5694        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5695        // Map to base uids.
5696        uid1 = UserHandle.getAppId(uid1);
5697        uid2 = UserHandle.getAppId(uid2);
5698        // reader
5699        synchronized (mPackages) {
5700            Signature[] s1;
5701            Signature[] s2;
5702            Object obj = mSettings.getUserIdLPr(uid1);
5703            if (obj != null) {
5704                if (obj instanceof SharedUserSetting) {
5705                    if (isCallerInstantApp) {
5706                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5707                    }
5708                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5709                } else if (obj instanceof PackageSetting) {
5710                    final PackageSetting ps = (PackageSetting) obj;
5711                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5712                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5713                    }
5714                    s1 = ps.signatures.mSignatures;
5715                } else {
5716                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5717                }
5718            } else {
5719                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5720            }
5721            obj = mSettings.getUserIdLPr(uid2);
5722            if (obj != null) {
5723                if (obj instanceof SharedUserSetting) {
5724                    if (isCallerInstantApp) {
5725                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5726                    }
5727                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5728                } else if (obj instanceof PackageSetting) {
5729                    final PackageSetting ps = (PackageSetting) obj;
5730                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5731                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5732                    }
5733                    s2 = ps.signatures.mSignatures;
5734                } else {
5735                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5736                }
5737            } else {
5738                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5739            }
5740            return compareSignatures(s1, s2);
5741        }
5742    }
5743
5744    /**
5745     * This method should typically only be used when granting or revoking
5746     * permissions, since the app may immediately restart after this call.
5747     * <p>
5748     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5749     * guard your work against the app being relaunched.
5750     */
5751    private void killUid(int appId, int userId, String reason) {
5752        final long identity = Binder.clearCallingIdentity();
5753        try {
5754            IActivityManager am = ActivityManager.getService();
5755            if (am != null) {
5756                try {
5757                    am.killUid(appId, userId, reason);
5758                } catch (RemoteException e) {
5759                    /* ignore - same process */
5760                }
5761            }
5762        } finally {
5763            Binder.restoreCallingIdentity(identity);
5764        }
5765    }
5766
5767    /**
5768     * Compares two sets of signatures. Returns:
5769     * <br />
5770     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5771     * <br />
5772     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5773     * <br />
5774     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5775     * <br />
5776     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5777     * <br />
5778     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5779     */
5780    static int compareSignatures(Signature[] s1, Signature[] s2) {
5781        if (s1 == null) {
5782            return s2 == null
5783                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5784                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5785        }
5786
5787        if (s2 == null) {
5788            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5789        }
5790
5791        if (s1.length != s2.length) {
5792            return PackageManager.SIGNATURE_NO_MATCH;
5793        }
5794
5795        // Since both signature sets are of size 1, we can compare without HashSets.
5796        if (s1.length == 1) {
5797            return s1[0].equals(s2[0]) ?
5798                    PackageManager.SIGNATURE_MATCH :
5799                    PackageManager.SIGNATURE_NO_MATCH;
5800        }
5801
5802        ArraySet<Signature> set1 = new ArraySet<Signature>();
5803        for (Signature sig : s1) {
5804            set1.add(sig);
5805        }
5806        ArraySet<Signature> set2 = new ArraySet<Signature>();
5807        for (Signature sig : s2) {
5808            set2.add(sig);
5809        }
5810        // Make sure s2 contains all signatures in s1.
5811        if (set1.equals(set2)) {
5812            return PackageManager.SIGNATURE_MATCH;
5813        }
5814        return PackageManager.SIGNATURE_NO_MATCH;
5815    }
5816
5817    /**
5818     * If the database version for this type of package (internal storage or
5819     * external storage) is less than the version where package signatures
5820     * were updated, return true.
5821     */
5822    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5823        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5824        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5825    }
5826
5827    /**
5828     * Used for backward compatibility to make sure any packages with
5829     * certificate chains get upgraded to the new style. {@code existingSigs}
5830     * will be in the old format (since they were stored on disk from before the
5831     * system upgrade) and {@code scannedSigs} will be in the newer format.
5832     */
5833    private int compareSignaturesCompat(PackageSignatures existingSigs,
5834            PackageParser.Package scannedPkg) {
5835        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5836            return PackageManager.SIGNATURE_NO_MATCH;
5837        }
5838
5839        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5840        for (Signature sig : existingSigs.mSignatures) {
5841            existingSet.add(sig);
5842        }
5843        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5844        for (Signature sig : scannedPkg.mSignatures) {
5845            try {
5846                Signature[] chainSignatures = sig.getChainSignatures();
5847                for (Signature chainSig : chainSignatures) {
5848                    scannedCompatSet.add(chainSig);
5849                }
5850            } catch (CertificateEncodingException e) {
5851                scannedCompatSet.add(sig);
5852            }
5853        }
5854        /*
5855         * Make sure the expanded scanned set contains all signatures in the
5856         * existing one.
5857         */
5858        if (scannedCompatSet.equals(existingSet)) {
5859            // Migrate the old signatures to the new scheme.
5860            existingSigs.assignSignatures(scannedPkg.mSignatures);
5861            // The new KeySets will be re-added later in the scanning process.
5862            synchronized (mPackages) {
5863                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5864            }
5865            return PackageManager.SIGNATURE_MATCH;
5866        }
5867        return PackageManager.SIGNATURE_NO_MATCH;
5868    }
5869
5870    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5871        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5872        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5873    }
5874
5875    private int compareSignaturesRecover(PackageSignatures existingSigs,
5876            PackageParser.Package scannedPkg) {
5877        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5878            return PackageManager.SIGNATURE_NO_MATCH;
5879        }
5880
5881        String msg = null;
5882        try {
5883            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5884                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5885                        + scannedPkg.packageName);
5886                return PackageManager.SIGNATURE_MATCH;
5887            }
5888        } catch (CertificateException e) {
5889            msg = e.getMessage();
5890        }
5891
5892        logCriticalInfo(Log.INFO,
5893                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5894        return PackageManager.SIGNATURE_NO_MATCH;
5895    }
5896
5897    @Override
5898    public List<String> getAllPackages() {
5899        final int callingUid = Binder.getCallingUid();
5900        final int callingUserId = UserHandle.getUserId(callingUid);
5901        synchronized (mPackages) {
5902            if (canAccessInstantApps(callingUid)) {
5903                return new ArrayList<String>(mPackages.keySet());
5904            }
5905            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5906            final List<String> result = new ArrayList<>();
5907            if (instantAppPkgName != null) {
5908                // caller is an instant application; filter unexposed applications
5909                for (PackageParser.Package pkg : mPackages.values()) {
5910                    if (!pkg.visibleToInstantApps) {
5911                        continue;
5912                    }
5913                    result.add(pkg.packageName);
5914                }
5915            } else {
5916                // caller is a normal application; filter instant applications
5917                for (PackageParser.Package pkg : mPackages.values()) {
5918                    final PackageSetting ps =
5919                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5920                    if (ps != null
5921                            && ps.getInstantApp(callingUserId)
5922                            && !mInstantAppRegistry.isInstantAccessGranted(
5923                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5924                        continue;
5925                    }
5926                    result.add(pkg.packageName);
5927                }
5928            }
5929            return result;
5930        }
5931    }
5932
5933    @Override
5934    public String[] getPackagesForUid(int uid) {
5935        final int callingUid = Binder.getCallingUid();
5936        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5937        final int userId = UserHandle.getUserId(uid);
5938        uid = UserHandle.getAppId(uid);
5939        // reader
5940        synchronized (mPackages) {
5941            Object obj = mSettings.getUserIdLPr(uid);
5942            if (obj instanceof SharedUserSetting) {
5943                if (isCallerInstantApp) {
5944                    return null;
5945                }
5946                final SharedUserSetting sus = (SharedUserSetting) obj;
5947                final int N = sus.packages.size();
5948                String[] res = new String[N];
5949                final Iterator<PackageSetting> it = sus.packages.iterator();
5950                int i = 0;
5951                while (it.hasNext()) {
5952                    PackageSetting ps = it.next();
5953                    if (ps.getInstalled(userId)) {
5954                        res[i++] = ps.name;
5955                    } else {
5956                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5957                    }
5958                }
5959                return res;
5960            } else if (obj instanceof PackageSetting) {
5961                final PackageSetting ps = (PackageSetting) obj;
5962                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5963                    return new String[]{ps.name};
5964                }
5965            }
5966        }
5967        return null;
5968    }
5969
5970    @Override
5971    public String getNameForUid(int uid) {
5972        final int callingUid = Binder.getCallingUid();
5973        if (getInstantAppPackageName(callingUid) != null) {
5974            return null;
5975        }
5976        synchronized (mPackages) {
5977            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5978            if (obj instanceof SharedUserSetting) {
5979                final SharedUserSetting sus = (SharedUserSetting) obj;
5980                return sus.name + ":" + sus.userId;
5981            } else if (obj instanceof PackageSetting) {
5982                final PackageSetting ps = (PackageSetting) obj;
5983                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5984                    return null;
5985                }
5986                return ps.name;
5987            }
5988        }
5989        return null;
5990    }
5991
5992    @Override
5993    public int getUidForSharedUser(String sharedUserName) {
5994        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5995            return -1;
5996        }
5997        if (sharedUserName == null) {
5998            return -1;
5999        }
6000        // reader
6001        synchronized (mPackages) {
6002            SharedUserSetting suid;
6003            try {
6004                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6005                if (suid != null) {
6006                    return suid.userId;
6007                }
6008            } catch (PackageManagerException ignore) {
6009                // can't happen, but, still need to catch it
6010            }
6011            return -1;
6012        }
6013    }
6014
6015    @Override
6016    public int getFlagsForUid(int uid) {
6017        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6018            return 0;
6019        }
6020        synchronized (mPackages) {
6021            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6022            if (obj instanceof SharedUserSetting) {
6023                final SharedUserSetting sus = (SharedUserSetting) obj;
6024                return sus.pkgFlags;
6025            } else if (obj instanceof PackageSetting) {
6026                final PackageSetting ps = (PackageSetting) obj;
6027                return ps.pkgFlags;
6028            }
6029        }
6030        return 0;
6031    }
6032
6033    @Override
6034    public int getPrivateFlagsForUid(int uid) {
6035        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6036            return 0;
6037        }
6038        synchronized (mPackages) {
6039            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6040            if (obj instanceof SharedUserSetting) {
6041                final SharedUserSetting sus = (SharedUserSetting) obj;
6042                return sus.pkgPrivateFlags;
6043            } else if (obj instanceof PackageSetting) {
6044                final PackageSetting ps = (PackageSetting) obj;
6045                return ps.pkgPrivateFlags;
6046            }
6047        }
6048        return 0;
6049    }
6050
6051    @Override
6052    public boolean isUidPrivileged(int uid) {
6053        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6054            return false;
6055        }
6056        uid = UserHandle.getAppId(uid);
6057        // reader
6058        synchronized (mPackages) {
6059            Object obj = mSettings.getUserIdLPr(uid);
6060            if (obj instanceof SharedUserSetting) {
6061                final SharedUserSetting sus = (SharedUserSetting) obj;
6062                final Iterator<PackageSetting> it = sus.packages.iterator();
6063                while (it.hasNext()) {
6064                    if (it.next().isPrivileged()) {
6065                        return true;
6066                    }
6067                }
6068            } else if (obj instanceof PackageSetting) {
6069                final PackageSetting ps = (PackageSetting) obj;
6070                return ps.isPrivileged();
6071            }
6072        }
6073        return false;
6074    }
6075
6076    @Override
6077    public String[] getAppOpPermissionPackages(String permissionName) {
6078        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6079            return null;
6080        }
6081        synchronized (mPackages) {
6082            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6083            if (pkgs == null) {
6084                return null;
6085            }
6086            return pkgs.toArray(new String[pkgs.size()]);
6087        }
6088    }
6089
6090    @Override
6091    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6092            int flags, int userId) {
6093        return resolveIntentInternal(
6094                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6095    }
6096
6097    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6098            int flags, int userId, boolean resolveForStart) {
6099        try {
6100            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6101
6102            if (!sUserManager.exists(userId)) return null;
6103            final int callingUid = Binder.getCallingUid();
6104            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6105            enforceCrossUserPermission(callingUid, userId,
6106                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6107
6108            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6109            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6110                    flags, userId, resolveForStart);
6111            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6112
6113            final ResolveInfo bestChoice =
6114                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6115            return bestChoice;
6116        } finally {
6117            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6118        }
6119    }
6120
6121    @Override
6122    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6123        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6124            throw new SecurityException(
6125                    "findPersistentPreferredActivity can only be run by the system");
6126        }
6127        if (!sUserManager.exists(userId)) {
6128            return null;
6129        }
6130        final int callingUid = Binder.getCallingUid();
6131        intent = updateIntentForResolve(intent);
6132        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6133        final int flags = updateFlagsForResolve(
6134                0, userId, intent, callingUid, false /*includeInstantApps*/);
6135        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6136                userId);
6137        synchronized (mPackages) {
6138            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6139                    userId);
6140        }
6141    }
6142
6143    @Override
6144    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6145            IntentFilter filter, int match, ComponentName activity) {
6146        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6147            return;
6148        }
6149        final int userId = UserHandle.getCallingUserId();
6150        if (DEBUG_PREFERRED) {
6151            Log.v(TAG, "setLastChosenActivity intent=" + intent
6152                + " resolvedType=" + resolvedType
6153                + " flags=" + flags
6154                + " filter=" + filter
6155                + " match=" + match
6156                + " activity=" + activity);
6157            filter.dump(new PrintStreamPrinter(System.out), "    ");
6158        }
6159        intent.setComponent(null);
6160        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6161                userId);
6162        // Find any earlier preferred or last chosen entries and nuke them
6163        findPreferredActivity(intent, resolvedType,
6164                flags, query, 0, false, true, false, userId);
6165        // Add the new activity as the last chosen for this filter
6166        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6167                "Setting last chosen");
6168    }
6169
6170    @Override
6171    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6172        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6173            return null;
6174        }
6175        final int userId = UserHandle.getCallingUserId();
6176        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6177        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6178                userId);
6179        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6180                false, false, false, userId);
6181    }
6182
6183    /**
6184     * Returns whether or not instant apps have been disabled remotely.
6185     */
6186    private boolean isEphemeralDisabled() {
6187        return mEphemeralAppsDisabled;
6188    }
6189
6190    private boolean isInstantAppAllowed(
6191            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6192            boolean skipPackageCheck) {
6193        if (mInstantAppResolverConnection == null) {
6194            return false;
6195        }
6196        if (mInstantAppInstallerActivity == null) {
6197            return false;
6198        }
6199        if (intent.getComponent() != null) {
6200            return false;
6201        }
6202        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6203            return false;
6204        }
6205        if (!skipPackageCheck && intent.getPackage() != null) {
6206            return false;
6207        }
6208        final boolean isWebUri = hasWebURI(intent);
6209        if (!isWebUri || intent.getData().getHost() == null) {
6210            return false;
6211        }
6212        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6213        // Or if there's already an ephemeral app installed that handles the action
6214        synchronized (mPackages) {
6215            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6216            for (int n = 0; n < count; n++) {
6217                final ResolveInfo info = resolvedActivities.get(n);
6218                final String packageName = info.activityInfo.packageName;
6219                final PackageSetting ps = mSettings.mPackages.get(packageName);
6220                if (ps != null) {
6221                    // only check domain verification status if the app is not a browser
6222                    if (!info.handleAllWebDataURI) {
6223                        // Try to get the status from User settings first
6224                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6225                        final int status = (int) (packedStatus >> 32);
6226                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6227                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6228                            if (DEBUG_EPHEMERAL) {
6229                                Slog.v(TAG, "DENY instant app;"
6230                                    + " pkg: " + packageName + ", status: " + status);
6231                            }
6232                            return false;
6233                        }
6234                    }
6235                    if (ps.getInstantApp(userId)) {
6236                        if (DEBUG_EPHEMERAL) {
6237                            Slog.v(TAG, "DENY instant app installed;"
6238                                    + " pkg: " + packageName);
6239                        }
6240                        return false;
6241                    }
6242                }
6243            }
6244        }
6245        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6246        return true;
6247    }
6248
6249    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6250            Intent origIntent, String resolvedType, String callingPackage,
6251            Bundle verificationBundle, int userId) {
6252        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6253                new InstantAppRequest(responseObj, origIntent, resolvedType,
6254                        callingPackage, userId, verificationBundle));
6255        mHandler.sendMessage(msg);
6256    }
6257
6258    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6259            int flags, List<ResolveInfo> query, int userId) {
6260        if (query != null) {
6261            final int N = query.size();
6262            if (N == 1) {
6263                return query.get(0);
6264            } else if (N > 1) {
6265                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6266                // If there is more than one activity with the same priority,
6267                // then let the user decide between them.
6268                ResolveInfo r0 = query.get(0);
6269                ResolveInfo r1 = query.get(1);
6270                if (DEBUG_INTENT_MATCHING || debug) {
6271                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6272                            + r1.activityInfo.name + "=" + r1.priority);
6273                }
6274                // If the first activity has a higher priority, or a different
6275                // default, then it is always desirable to pick it.
6276                if (r0.priority != r1.priority
6277                        || r0.preferredOrder != r1.preferredOrder
6278                        || r0.isDefault != r1.isDefault) {
6279                    return query.get(0);
6280                }
6281                // If we have saved a preference for a preferred activity for
6282                // this Intent, use that.
6283                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6284                        flags, query, r0.priority, true, false, debug, userId);
6285                if (ri != null) {
6286                    return ri;
6287                }
6288                // If we have an ephemeral app, use it
6289                for (int i = 0; i < N; i++) {
6290                    ri = query.get(i);
6291                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6292                        final String packageName = ri.activityInfo.packageName;
6293                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6294                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6295                        final int status = (int)(packedStatus >> 32);
6296                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6297                            return ri;
6298                        }
6299                    }
6300                }
6301                ri = new ResolveInfo(mResolveInfo);
6302                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6303                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6304                // If all of the options come from the same package, show the application's
6305                // label and icon instead of the generic resolver's.
6306                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6307                // and then throw away the ResolveInfo itself, meaning that the caller loses
6308                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6309                // a fallback for this case; we only set the target package's resources on
6310                // the ResolveInfo, not the ActivityInfo.
6311                final String intentPackage = intent.getPackage();
6312                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6313                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6314                    ri.resolvePackageName = intentPackage;
6315                    if (userNeedsBadging(userId)) {
6316                        ri.noResourceId = true;
6317                    } else {
6318                        ri.icon = appi.icon;
6319                    }
6320                    ri.iconResourceId = appi.icon;
6321                    ri.labelRes = appi.labelRes;
6322                }
6323                ri.activityInfo.applicationInfo = new ApplicationInfo(
6324                        ri.activityInfo.applicationInfo);
6325                if (userId != 0) {
6326                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6327                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6328                }
6329                // Make sure that the resolver is displayable in car mode
6330                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6331                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6332                return ri;
6333            }
6334        }
6335        return null;
6336    }
6337
6338    /**
6339     * Return true if the given list is not empty and all of its contents have
6340     * an activityInfo with the given package name.
6341     */
6342    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6343        if (ArrayUtils.isEmpty(list)) {
6344            return false;
6345        }
6346        for (int i = 0, N = list.size(); i < N; i++) {
6347            final ResolveInfo ri = list.get(i);
6348            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6349            if (ai == null || !packageName.equals(ai.packageName)) {
6350                return false;
6351            }
6352        }
6353        return true;
6354    }
6355
6356    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6357            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6358        final int N = query.size();
6359        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6360                .get(userId);
6361        // Get the list of persistent preferred activities that handle the intent
6362        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6363        List<PersistentPreferredActivity> pprefs = ppir != null
6364                ? ppir.queryIntent(intent, resolvedType,
6365                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6366                        userId)
6367                : null;
6368        if (pprefs != null && pprefs.size() > 0) {
6369            final int M = pprefs.size();
6370            for (int i=0; i<M; i++) {
6371                final PersistentPreferredActivity ppa = pprefs.get(i);
6372                if (DEBUG_PREFERRED || debug) {
6373                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6374                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6375                            + "\n  component=" + ppa.mComponent);
6376                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6377                }
6378                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6379                        flags | MATCH_DISABLED_COMPONENTS, userId);
6380                if (DEBUG_PREFERRED || debug) {
6381                    Slog.v(TAG, "Found persistent preferred activity:");
6382                    if (ai != null) {
6383                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6384                    } else {
6385                        Slog.v(TAG, "  null");
6386                    }
6387                }
6388                if (ai == null) {
6389                    // This previously registered persistent preferred activity
6390                    // component is no longer known. Ignore it and do NOT remove it.
6391                    continue;
6392                }
6393                for (int j=0; j<N; j++) {
6394                    final ResolveInfo ri = query.get(j);
6395                    if (!ri.activityInfo.applicationInfo.packageName
6396                            .equals(ai.applicationInfo.packageName)) {
6397                        continue;
6398                    }
6399                    if (!ri.activityInfo.name.equals(ai.name)) {
6400                        continue;
6401                    }
6402                    //  Found a persistent preference that can handle the intent.
6403                    if (DEBUG_PREFERRED || debug) {
6404                        Slog.v(TAG, "Returning persistent preferred activity: " +
6405                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6406                    }
6407                    return ri;
6408                }
6409            }
6410        }
6411        return null;
6412    }
6413
6414    // TODO: handle preferred activities missing while user has amnesia
6415    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6416            List<ResolveInfo> query, int priority, boolean always,
6417            boolean removeMatches, boolean debug, int userId) {
6418        if (!sUserManager.exists(userId)) return null;
6419        final int callingUid = Binder.getCallingUid();
6420        flags = updateFlagsForResolve(
6421                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6422        intent = updateIntentForResolve(intent);
6423        // writer
6424        synchronized (mPackages) {
6425            // Try to find a matching persistent preferred activity.
6426            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6427                    debug, userId);
6428
6429            // If a persistent preferred activity matched, use it.
6430            if (pri != null) {
6431                return pri;
6432            }
6433
6434            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6435            // Get the list of preferred activities that handle the intent
6436            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6437            List<PreferredActivity> prefs = pir != null
6438                    ? pir.queryIntent(intent, resolvedType,
6439                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6440                            userId)
6441                    : null;
6442            if (prefs != null && prefs.size() > 0) {
6443                boolean changed = false;
6444                try {
6445                    // First figure out how good the original match set is.
6446                    // We will only allow preferred activities that came
6447                    // from the same match quality.
6448                    int match = 0;
6449
6450                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6451
6452                    final int N = query.size();
6453                    for (int j=0; j<N; j++) {
6454                        final ResolveInfo ri = query.get(j);
6455                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6456                                + ": 0x" + Integer.toHexString(match));
6457                        if (ri.match > match) {
6458                            match = ri.match;
6459                        }
6460                    }
6461
6462                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6463                            + Integer.toHexString(match));
6464
6465                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6466                    final int M = prefs.size();
6467                    for (int i=0; i<M; i++) {
6468                        final PreferredActivity pa = prefs.get(i);
6469                        if (DEBUG_PREFERRED || debug) {
6470                            Slog.v(TAG, "Checking PreferredActivity ds="
6471                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6472                                    + "\n  component=" + pa.mPref.mComponent);
6473                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6474                        }
6475                        if (pa.mPref.mMatch != match) {
6476                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6477                                    + Integer.toHexString(pa.mPref.mMatch));
6478                            continue;
6479                        }
6480                        // If it's not an "always" type preferred activity and that's what we're
6481                        // looking for, skip it.
6482                        if (always && !pa.mPref.mAlways) {
6483                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6484                            continue;
6485                        }
6486                        final ActivityInfo ai = getActivityInfo(
6487                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6488                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6489                                userId);
6490                        if (DEBUG_PREFERRED || debug) {
6491                            Slog.v(TAG, "Found preferred activity:");
6492                            if (ai != null) {
6493                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6494                            } else {
6495                                Slog.v(TAG, "  null");
6496                            }
6497                        }
6498                        if (ai == null) {
6499                            // This previously registered preferred activity
6500                            // component is no longer known.  Most likely an update
6501                            // to the app was installed and in the new version this
6502                            // component no longer exists.  Clean it up by removing
6503                            // it from the preferred activities list, and skip it.
6504                            Slog.w(TAG, "Removing dangling preferred activity: "
6505                                    + pa.mPref.mComponent);
6506                            pir.removeFilter(pa);
6507                            changed = true;
6508                            continue;
6509                        }
6510                        for (int j=0; j<N; j++) {
6511                            final ResolveInfo ri = query.get(j);
6512                            if (!ri.activityInfo.applicationInfo.packageName
6513                                    .equals(ai.applicationInfo.packageName)) {
6514                                continue;
6515                            }
6516                            if (!ri.activityInfo.name.equals(ai.name)) {
6517                                continue;
6518                            }
6519
6520                            if (removeMatches) {
6521                                pir.removeFilter(pa);
6522                                changed = true;
6523                                if (DEBUG_PREFERRED) {
6524                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6525                                }
6526                                break;
6527                            }
6528
6529                            // Okay we found a previously set preferred or last chosen app.
6530                            // If the result set is different from when this
6531                            // was created, we need to clear it and re-ask the
6532                            // user their preference, if we're looking for an "always" type entry.
6533                            if (always && !pa.mPref.sameSet(query)) {
6534                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6535                                        + intent + " type " + resolvedType);
6536                                if (DEBUG_PREFERRED) {
6537                                    Slog.v(TAG, "Removing preferred activity since set changed "
6538                                            + pa.mPref.mComponent);
6539                                }
6540                                pir.removeFilter(pa);
6541                                // Re-add the filter as a "last chosen" entry (!always)
6542                                PreferredActivity lastChosen = new PreferredActivity(
6543                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6544                                pir.addFilter(lastChosen);
6545                                changed = true;
6546                                return null;
6547                            }
6548
6549                            // Yay! Either the set matched or we're looking for the last chosen
6550                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6551                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6552                            return ri;
6553                        }
6554                    }
6555                } finally {
6556                    if (changed) {
6557                        if (DEBUG_PREFERRED) {
6558                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6559                        }
6560                        scheduleWritePackageRestrictionsLocked(userId);
6561                    }
6562                }
6563            }
6564        }
6565        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6566        return null;
6567    }
6568
6569    /*
6570     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6571     */
6572    @Override
6573    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6574            int targetUserId) {
6575        mContext.enforceCallingOrSelfPermission(
6576                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6577        List<CrossProfileIntentFilter> matches =
6578                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6579        if (matches != null) {
6580            int size = matches.size();
6581            for (int i = 0; i < size; i++) {
6582                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6583            }
6584        }
6585        if (hasWebURI(intent)) {
6586            // cross-profile app linking works only towards the parent.
6587            final int callingUid = Binder.getCallingUid();
6588            final UserInfo parent = getProfileParent(sourceUserId);
6589            synchronized(mPackages) {
6590                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6591                        false /*includeInstantApps*/);
6592                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6593                        intent, resolvedType, flags, sourceUserId, parent.id);
6594                return xpDomainInfo != null;
6595            }
6596        }
6597        return false;
6598    }
6599
6600    private UserInfo getProfileParent(int userId) {
6601        final long identity = Binder.clearCallingIdentity();
6602        try {
6603            return sUserManager.getProfileParent(userId);
6604        } finally {
6605            Binder.restoreCallingIdentity(identity);
6606        }
6607    }
6608
6609    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6610            String resolvedType, int userId) {
6611        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6612        if (resolver != null) {
6613            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6614        }
6615        return null;
6616    }
6617
6618    @Override
6619    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6620            String resolvedType, int flags, int userId) {
6621        try {
6622            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6623
6624            return new ParceledListSlice<>(
6625                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6626        } finally {
6627            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6628        }
6629    }
6630
6631    /**
6632     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6633     * instant, returns {@code null}.
6634     */
6635    private String getInstantAppPackageName(int callingUid) {
6636        synchronized (mPackages) {
6637            // If the caller is an isolated app use the owner's uid for the lookup.
6638            if (Process.isIsolated(callingUid)) {
6639                callingUid = mIsolatedOwners.get(callingUid);
6640            }
6641            final int appId = UserHandle.getAppId(callingUid);
6642            final Object obj = mSettings.getUserIdLPr(appId);
6643            if (obj instanceof PackageSetting) {
6644                final PackageSetting ps = (PackageSetting) obj;
6645                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6646                return isInstantApp ? ps.pkg.packageName : null;
6647            }
6648        }
6649        return null;
6650    }
6651
6652    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6653            String resolvedType, int flags, int userId) {
6654        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6655    }
6656
6657    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6658            String resolvedType, int flags, int userId, boolean resolveForStart) {
6659        if (!sUserManager.exists(userId)) return Collections.emptyList();
6660        final int callingUid = Binder.getCallingUid();
6661        final String instantAppPkgName = getInstantAppPackageName(callingUid);
6662        enforceCrossUserPermission(callingUid, userId,
6663                false /* requireFullPermission */, false /* checkShell */,
6664                "query intent activities");
6665        final String pkgName = intent.getPackage();
6666        ComponentName comp = intent.getComponent();
6667        if (comp == null) {
6668            if (intent.getSelector() != null) {
6669                intent = intent.getSelector();
6670                comp = intent.getComponent();
6671            }
6672        }
6673
6674        flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart,
6675                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6676        if (comp != null) {
6677            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6678            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6679            if (ai != null) {
6680                // When specifying an explicit component, we prevent the activity from being
6681                // used when either 1) the calling package is normal and the activity is within
6682                // an ephemeral application or 2) the calling package is ephemeral and the
6683                // activity is not visible to ephemeral applications.
6684                final boolean matchInstantApp =
6685                        (flags & PackageManager.MATCH_INSTANT) != 0;
6686                final boolean matchVisibleToInstantAppOnly =
6687                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6688                final boolean matchExplicitlyVisibleOnly =
6689                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6690                final boolean isCallerInstantApp =
6691                        instantAppPkgName != null;
6692                final boolean isTargetSameInstantApp =
6693                        comp.getPackageName().equals(instantAppPkgName);
6694                final boolean isTargetInstantApp =
6695                        (ai.applicationInfo.privateFlags
6696                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6697                final boolean isTargetVisibleToInstantApp =
6698                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6699                final boolean isTargetExplicitlyVisibleToInstantApp =
6700                        isTargetVisibleToInstantApp
6701                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6702                final boolean isTargetHiddenFromInstantApp =
6703                        !isTargetVisibleToInstantApp
6704                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6705                final boolean blockResolution =
6706                        !isTargetSameInstantApp
6707                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6708                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6709                                        && isTargetHiddenFromInstantApp));
6710                if (!blockResolution) {
6711                    final ResolveInfo ri = new ResolveInfo();
6712                    ri.activityInfo = ai;
6713                    list.add(ri);
6714                }
6715            }
6716            return applyPostResolutionFilter(list, instantAppPkgName);
6717        }
6718
6719        // reader
6720        boolean sortResult = false;
6721        boolean addEphemeral = false;
6722        List<ResolveInfo> result;
6723        final boolean ephemeralDisabled = isEphemeralDisabled();
6724        synchronized (mPackages) {
6725            if (pkgName == null) {
6726                List<CrossProfileIntentFilter> matchingFilters =
6727                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6728                // Check for results that need to skip the current profile.
6729                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6730                        resolvedType, flags, userId);
6731                if (xpResolveInfo != null) {
6732                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6733                    xpResult.add(xpResolveInfo);
6734                    return applyPostResolutionFilter(
6735                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6736                }
6737
6738                // Check for results in the current profile.
6739                result = filterIfNotSystemUser(mActivities.queryIntent(
6740                        intent, resolvedType, flags, userId), userId);
6741                addEphemeral = !ephemeralDisabled
6742                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6743                // Check for cross profile results.
6744                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6745                xpResolveInfo = queryCrossProfileIntents(
6746                        matchingFilters, intent, resolvedType, flags, userId,
6747                        hasNonNegativePriorityResult);
6748                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6749                    boolean isVisibleToUser = filterIfNotSystemUser(
6750                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6751                    if (isVisibleToUser) {
6752                        result.add(xpResolveInfo);
6753                        sortResult = true;
6754                    }
6755                }
6756                if (hasWebURI(intent)) {
6757                    CrossProfileDomainInfo xpDomainInfo = null;
6758                    final UserInfo parent = getProfileParent(userId);
6759                    if (parent != null) {
6760                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6761                                flags, userId, parent.id);
6762                    }
6763                    if (xpDomainInfo != null) {
6764                        if (xpResolveInfo != null) {
6765                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6766                            // in the result.
6767                            result.remove(xpResolveInfo);
6768                        }
6769                        if (result.size() == 0 && !addEphemeral) {
6770                            // No result in current profile, but found candidate in parent user.
6771                            // And we are not going to add emphemeral app, so we can return the
6772                            // result straight away.
6773                            result.add(xpDomainInfo.resolveInfo);
6774                            return applyPostResolutionFilter(result, instantAppPkgName);
6775                        }
6776                    } else if (result.size() <= 1 && !addEphemeral) {
6777                        // No result in parent user and <= 1 result in current profile, and we
6778                        // are not going to add emphemeral app, so we can return the result without
6779                        // further processing.
6780                        return applyPostResolutionFilter(result, instantAppPkgName);
6781                    }
6782                    // We have more than one candidate (combining results from current and parent
6783                    // profile), so we need filtering and sorting.
6784                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6785                            intent, flags, result, xpDomainInfo, userId);
6786                    sortResult = true;
6787                }
6788            } else {
6789                final PackageParser.Package pkg = mPackages.get(pkgName);
6790                result = null;
6791                if (pkg != null) {
6792                    result = filterIfNotSystemUser(
6793                            mActivities.queryIntentForPackage(
6794                                    intent, resolvedType, flags, pkg.activities, userId),
6795                            userId);
6796                }
6797                if (result == null || result.size() == 0) {
6798                    // the caller wants to resolve for a particular package; however, there
6799                    // were no installed results, so, try to find an ephemeral result
6800                    addEphemeral = !ephemeralDisabled
6801                            && isInstantAppAllowed(
6802                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6803                    if (result == null) {
6804                        result = new ArrayList<>();
6805                    }
6806                }
6807            }
6808        }
6809        if (addEphemeral) {
6810            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
6811        }
6812        if (sortResult) {
6813            Collections.sort(result, mResolvePrioritySorter);
6814        }
6815        return applyPostResolutionFilter(result, instantAppPkgName);
6816    }
6817
6818    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6819            String resolvedType, int flags, int userId) {
6820        // first, check to see if we've got an instant app already installed
6821        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6822        ResolveInfo localInstantApp = null;
6823        boolean blockResolution = false;
6824        if (!alreadyResolvedLocally) {
6825            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6826                    flags
6827                        | PackageManager.GET_RESOLVED_FILTER
6828                        | PackageManager.MATCH_INSTANT
6829                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6830                    userId);
6831            for (int i = instantApps.size() - 1; i >= 0; --i) {
6832                final ResolveInfo info = instantApps.get(i);
6833                final String packageName = info.activityInfo.packageName;
6834                final PackageSetting ps = mSettings.mPackages.get(packageName);
6835                if (ps.getInstantApp(userId)) {
6836                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6837                    final int status = (int)(packedStatus >> 32);
6838                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6839                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6840                        // there's a local instant application installed, but, the user has
6841                        // chosen to never use it; skip resolution and don't acknowledge
6842                        // an instant application is even available
6843                        if (DEBUG_EPHEMERAL) {
6844                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6845                        }
6846                        blockResolution = true;
6847                        break;
6848                    } else {
6849                        // we have a locally installed instant application; skip resolution
6850                        // but acknowledge there's an instant application available
6851                        if (DEBUG_EPHEMERAL) {
6852                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6853                        }
6854                        localInstantApp = info;
6855                        break;
6856                    }
6857                }
6858            }
6859        }
6860        // no app installed, let's see if one's available
6861        AuxiliaryResolveInfo auxiliaryResponse = null;
6862        if (!blockResolution) {
6863            if (localInstantApp == null) {
6864                // we don't have an instant app locally, resolve externally
6865                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6866                final InstantAppRequest requestObject = new InstantAppRequest(
6867                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6868                        null /*callingPackage*/, userId, null /*verificationBundle*/);
6869                auxiliaryResponse =
6870                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6871                                mContext, mInstantAppResolverConnection, requestObject);
6872                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6873            } else {
6874                // we have an instant application locally, but, we can't admit that since
6875                // callers shouldn't be able to determine prior browsing. create a dummy
6876                // auxiliary response so the downstream code behaves as if there's an
6877                // instant application available externally. when it comes time to start
6878                // the instant application, we'll do the right thing.
6879                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6880                auxiliaryResponse = new AuxiliaryResolveInfo(
6881                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
6882            }
6883        }
6884        if (auxiliaryResponse != null) {
6885            if (DEBUG_EPHEMERAL) {
6886                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6887            }
6888            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6889            final PackageSetting ps =
6890                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6891            if (ps != null) {
6892                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6893                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6894                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6895                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6896                // make sure this resolver is the default
6897                ephemeralInstaller.isDefault = true;
6898                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6899                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6900                // add a non-generic filter
6901                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6902                ephemeralInstaller.filter.addDataPath(
6903                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6904                ephemeralInstaller.isInstantAppAvailable = true;
6905                result.add(ephemeralInstaller);
6906            }
6907        }
6908        return result;
6909    }
6910
6911    private static class CrossProfileDomainInfo {
6912        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6913        ResolveInfo resolveInfo;
6914        /* Best domain verification status of the activities found in the other profile */
6915        int bestDomainVerificationStatus;
6916    }
6917
6918    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6919            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6920        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6921                sourceUserId)) {
6922            return null;
6923        }
6924        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6925                resolvedType, flags, parentUserId);
6926
6927        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6928            return null;
6929        }
6930        CrossProfileDomainInfo result = null;
6931        int size = resultTargetUser.size();
6932        for (int i = 0; i < size; i++) {
6933            ResolveInfo riTargetUser = resultTargetUser.get(i);
6934            // Intent filter verification is only for filters that specify a host. So don't return
6935            // those that handle all web uris.
6936            if (riTargetUser.handleAllWebDataURI) {
6937                continue;
6938            }
6939            String packageName = riTargetUser.activityInfo.packageName;
6940            PackageSetting ps = mSettings.mPackages.get(packageName);
6941            if (ps == null) {
6942                continue;
6943            }
6944            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6945            int status = (int)(verificationState >> 32);
6946            if (result == null) {
6947                result = new CrossProfileDomainInfo();
6948                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6949                        sourceUserId, parentUserId);
6950                result.bestDomainVerificationStatus = status;
6951            } else {
6952                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6953                        result.bestDomainVerificationStatus);
6954            }
6955        }
6956        // Don't consider matches with status NEVER across profiles.
6957        if (result != null && result.bestDomainVerificationStatus
6958                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6959            return null;
6960        }
6961        return result;
6962    }
6963
6964    /**
6965     * Verification statuses are ordered from the worse to the best, except for
6966     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6967     */
6968    private int bestDomainVerificationStatus(int status1, int status2) {
6969        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6970            return status2;
6971        }
6972        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6973            return status1;
6974        }
6975        return (int) MathUtils.max(status1, status2);
6976    }
6977
6978    private boolean isUserEnabled(int userId) {
6979        long callingId = Binder.clearCallingIdentity();
6980        try {
6981            UserInfo userInfo = sUserManager.getUserInfo(userId);
6982            return userInfo != null && userInfo.isEnabled();
6983        } finally {
6984            Binder.restoreCallingIdentity(callingId);
6985        }
6986    }
6987
6988    /**
6989     * Filter out activities with systemUserOnly flag set, when current user is not System.
6990     *
6991     * @return filtered list
6992     */
6993    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6994        if (userId == UserHandle.USER_SYSTEM) {
6995            return resolveInfos;
6996        }
6997        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6998            ResolveInfo info = resolveInfos.get(i);
6999            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7000                resolveInfos.remove(i);
7001            }
7002        }
7003        return resolveInfos;
7004    }
7005
7006    /**
7007     * Filters out ephemeral activities.
7008     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7009     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7010     *
7011     * @param resolveInfos The pre-filtered list of resolved activities
7012     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7013     *          is performed.
7014     * @return A filtered list of resolved activities.
7015     */
7016    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7017            String ephemeralPkgName) {
7018        // TODO: When adding on-demand split support for non-instant apps, remove this check
7019        // and always apply post filtering
7020        if (ephemeralPkgName == null) {
7021            return resolveInfos;
7022        }
7023        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7024            final ResolveInfo info = resolveInfos.get(i);
7025            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7026            // allow activities that are defined in the provided package
7027            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
7028                if (info.activityInfo.splitName != null
7029                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7030                                info.activityInfo.splitName)) {
7031                    // requested activity is defined in a split that hasn't been installed yet.
7032                    // add the installer to the resolve list
7033                    if (DEBUG_EPHEMERAL) {
7034                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7035                    }
7036                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7037                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7038                            info.activityInfo.packageName, info.activityInfo.splitName,
7039                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7040                    // make sure this resolver is the default
7041                    installerInfo.isDefault = true;
7042                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7043                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7044                    // add a non-generic filter
7045                    installerInfo.filter = new IntentFilter();
7046                    // load resources from the correct package
7047                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7048                    resolveInfos.set(i, installerInfo);
7049                }
7050                continue;
7051            }
7052            // allow activities that have been explicitly exposed to ephemeral apps
7053            if (!isEphemeralApp
7054                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7055                continue;
7056            }
7057            resolveInfos.remove(i);
7058        }
7059        return resolveInfos;
7060    }
7061
7062    /**
7063     * @param resolveInfos list of resolve infos in descending priority order
7064     * @return if the list contains a resolve info with non-negative priority
7065     */
7066    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7067        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7068    }
7069
7070    private static boolean hasWebURI(Intent intent) {
7071        if (intent.getData() == null) {
7072            return false;
7073        }
7074        final String scheme = intent.getScheme();
7075        if (TextUtils.isEmpty(scheme)) {
7076            return false;
7077        }
7078        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7079    }
7080
7081    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7082            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7083            int userId) {
7084        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7085
7086        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7087            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7088                    candidates.size());
7089        }
7090
7091        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7092        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7093        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7094        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7095        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7096        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7097
7098        synchronized (mPackages) {
7099            final int count = candidates.size();
7100            // First, try to use linked apps. Partition the candidates into four lists:
7101            // one for the final results, one for the "do not use ever", one for "undefined status"
7102            // and finally one for "browser app type".
7103            for (int n=0; n<count; n++) {
7104                ResolveInfo info = candidates.get(n);
7105                String packageName = info.activityInfo.packageName;
7106                PackageSetting ps = mSettings.mPackages.get(packageName);
7107                if (ps != null) {
7108                    // Add to the special match all list (Browser use case)
7109                    if (info.handleAllWebDataURI) {
7110                        matchAllList.add(info);
7111                        continue;
7112                    }
7113                    // Try to get the status from User settings first
7114                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7115                    int status = (int)(packedStatus >> 32);
7116                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7117                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7118                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7119                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7120                                    + " : linkgen=" + linkGeneration);
7121                        }
7122                        // Use link-enabled generation as preferredOrder, i.e.
7123                        // prefer newly-enabled over earlier-enabled.
7124                        info.preferredOrder = linkGeneration;
7125                        alwaysList.add(info);
7126                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7127                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7128                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7129                        }
7130                        neverList.add(info);
7131                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7132                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7133                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7134                        }
7135                        alwaysAskList.add(info);
7136                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7137                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7138                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7139                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7140                        }
7141                        undefinedList.add(info);
7142                    }
7143                }
7144            }
7145
7146            // We'll want to include browser possibilities in a few cases
7147            boolean includeBrowser = false;
7148
7149            // First try to add the "always" resolution(s) for the current user, if any
7150            if (alwaysList.size() > 0) {
7151                result.addAll(alwaysList);
7152            } else {
7153                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7154                result.addAll(undefinedList);
7155                // Maybe add one for the other profile.
7156                if (xpDomainInfo != null && (
7157                        xpDomainInfo.bestDomainVerificationStatus
7158                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7159                    result.add(xpDomainInfo.resolveInfo);
7160                }
7161                includeBrowser = true;
7162            }
7163
7164            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7165            // If there were 'always' entries their preferred order has been set, so we also
7166            // back that off to make the alternatives equivalent
7167            if (alwaysAskList.size() > 0) {
7168                for (ResolveInfo i : result) {
7169                    i.preferredOrder = 0;
7170                }
7171                result.addAll(alwaysAskList);
7172                includeBrowser = true;
7173            }
7174
7175            if (includeBrowser) {
7176                // Also add browsers (all of them or only the default one)
7177                if (DEBUG_DOMAIN_VERIFICATION) {
7178                    Slog.v(TAG, "   ...including browsers in candidate set");
7179                }
7180                if ((matchFlags & MATCH_ALL) != 0) {
7181                    result.addAll(matchAllList);
7182                } else {
7183                    // Browser/generic handling case.  If there's a default browser, go straight
7184                    // to that (but only if there is no other higher-priority match).
7185                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7186                    int maxMatchPrio = 0;
7187                    ResolveInfo defaultBrowserMatch = null;
7188                    final int numCandidates = matchAllList.size();
7189                    for (int n = 0; n < numCandidates; n++) {
7190                        ResolveInfo info = matchAllList.get(n);
7191                        // track the highest overall match priority...
7192                        if (info.priority > maxMatchPrio) {
7193                            maxMatchPrio = info.priority;
7194                        }
7195                        // ...and the highest-priority default browser match
7196                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7197                            if (defaultBrowserMatch == null
7198                                    || (defaultBrowserMatch.priority < info.priority)) {
7199                                if (debug) {
7200                                    Slog.v(TAG, "Considering default browser match " + info);
7201                                }
7202                                defaultBrowserMatch = info;
7203                            }
7204                        }
7205                    }
7206                    if (defaultBrowserMatch != null
7207                            && defaultBrowserMatch.priority >= maxMatchPrio
7208                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7209                    {
7210                        if (debug) {
7211                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7212                        }
7213                        result.add(defaultBrowserMatch);
7214                    } else {
7215                        result.addAll(matchAllList);
7216                    }
7217                }
7218
7219                // If there is nothing selected, add all candidates and remove the ones that the user
7220                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7221                if (result.size() == 0) {
7222                    result.addAll(candidates);
7223                    result.removeAll(neverList);
7224                }
7225            }
7226        }
7227        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7228            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7229                    result.size());
7230            for (ResolveInfo info : result) {
7231                Slog.v(TAG, "  + " + info.activityInfo);
7232            }
7233        }
7234        return result;
7235    }
7236
7237    // Returns a packed value as a long:
7238    //
7239    // high 'int'-sized word: link status: undefined/ask/never/always.
7240    // low 'int'-sized word: relative priority among 'always' results.
7241    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7242        long result = ps.getDomainVerificationStatusForUser(userId);
7243        // if none available, get the master status
7244        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7245            if (ps.getIntentFilterVerificationInfo() != null) {
7246                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7247            }
7248        }
7249        return result;
7250    }
7251
7252    private ResolveInfo querySkipCurrentProfileIntents(
7253            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7254            int flags, int sourceUserId) {
7255        if (matchingFilters != null) {
7256            int size = matchingFilters.size();
7257            for (int i = 0; i < size; i ++) {
7258                CrossProfileIntentFilter filter = matchingFilters.get(i);
7259                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7260                    // Checking if there are activities in the target user that can handle the
7261                    // intent.
7262                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7263                            resolvedType, flags, sourceUserId);
7264                    if (resolveInfo != null) {
7265                        return resolveInfo;
7266                    }
7267                }
7268            }
7269        }
7270        return null;
7271    }
7272
7273    // Return matching ResolveInfo in target user if any.
7274    private ResolveInfo queryCrossProfileIntents(
7275            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7276            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7277        if (matchingFilters != null) {
7278            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7279            // match the same intent. For performance reasons, it is better not to
7280            // run queryIntent twice for the same userId
7281            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7282            int size = matchingFilters.size();
7283            for (int i = 0; i < size; i++) {
7284                CrossProfileIntentFilter filter = matchingFilters.get(i);
7285                int targetUserId = filter.getTargetUserId();
7286                boolean skipCurrentProfile =
7287                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7288                boolean skipCurrentProfileIfNoMatchFound =
7289                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7290                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7291                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7292                    // Checking if there are activities in the target user that can handle the
7293                    // intent.
7294                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7295                            resolvedType, flags, sourceUserId);
7296                    if (resolveInfo != null) return resolveInfo;
7297                    alreadyTriedUserIds.put(targetUserId, true);
7298                }
7299            }
7300        }
7301        return null;
7302    }
7303
7304    /**
7305     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7306     * will forward the intent to the filter's target user.
7307     * Otherwise, returns null.
7308     */
7309    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7310            String resolvedType, int flags, int sourceUserId) {
7311        int targetUserId = filter.getTargetUserId();
7312        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7313                resolvedType, flags, targetUserId);
7314        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7315            // If all the matches in the target profile are suspended, return null.
7316            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7317                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7318                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7319                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7320                            targetUserId);
7321                }
7322            }
7323        }
7324        return null;
7325    }
7326
7327    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7328            int sourceUserId, int targetUserId) {
7329        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7330        long ident = Binder.clearCallingIdentity();
7331        boolean targetIsProfile;
7332        try {
7333            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7334        } finally {
7335            Binder.restoreCallingIdentity(ident);
7336        }
7337        String className;
7338        if (targetIsProfile) {
7339            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7340        } else {
7341            className = FORWARD_INTENT_TO_PARENT;
7342        }
7343        ComponentName forwardingActivityComponentName = new ComponentName(
7344                mAndroidApplication.packageName, className);
7345        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7346                sourceUserId);
7347        if (!targetIsProfile) {
7348            forwardingActivityInfo.showUserIcon = targetUserId;
7349            forwardingResolveInfo.noResourceId = true;
7350        }
7351        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7352        forwardingResolveInfo.priority = 0;
7353        forwardingResolveInfo.preferredOrder = 0;
7354        forwardingResolveInfo.match = 0;
7355        forwardingResolveInfo.isDefault = true;
7356        forwardingResolveInfo.filter = filter;
7357        forwardingResolveInfo.targetUserId = targetUserId;
7358        return forwardingResolveInfo;
7359    }
7360
7361    @Override
7362    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7363            Intent[] specifics, String[] specificTypes, Intent intent,
7364            String resolvedType, int flags, int userId) {
7365        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7366                specificTypes, intent, resolvedType, flags, userId));
7367    }
7368
7369    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7370            Intent[] specifics, String[] specificTypes, Intent intent,
7371            String resolvedType, int flags, int userId) {
7372        if (!sUserManager.exists(userId)) return Collections.emptyList();
7373        final int callingUid = Binder.getCallingUid();
7374        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7375                false /*includeInstantApps*/);
7376        enforceCrossUserPermission(callingUid, userId,
7377                false /*requireFullPermission*/, false /*checkShell*/,
7378                "query intent activity options");
7379        final String resultsAction = intent.getAction();
7380
7381        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7382                | PackageManager.GET_RESOLVED_FILTER, userId);
7383
7384        if (DEBUG_INTENT_MATCHING) {
7385            Log.v(TAG, "Query " + intent + ": " + results);
7386        }
7387
7388        int specificsPos = 0;
7389        int N;
7390
7391        // todo: note that the algorithm used here is O(N^2).  This
7392        // isn't a problem in our current environment, but if we start running
7393        // into situations where we have more than 5 or 10 matches then this
7394        // should probably be changed to something smarter...
7395
7396        // First we go through and resolve each of the specific items
7397        // that were supplied, taking care of removing any corresponding
7398        // duplicate items in the generic resolve list.
7399        if (specifics != null) {
7400            for (int i=0; i<specifics.length; i++) {
7401                final Intent sintent = specifics[i];
7402                if (sintent == null) {
7403                    continue;
7404                }
7405
7406                if (DEBUG_INTENT_MATCHING) {
7407                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7408                }
7409
7410                String action = sintent.getAction();
7411                if (resultsAction != null && resultsAction.equals(action)) {
7412                    // If this action was explicitly requested, then don't
7413                    // remove things that have it.
7414                    action = null;
7415                }
7416
7417                ResolveInfo ri = null;
7418                ActivityInfo ai = null;
7419
7420                ComponentName comp = sintent.getComponent();
7421                if (comp == null) {
7422                    ri = resolveIntent(
7423                        sintent,
7424                        specificTypes != null ? specificTypes[i] : null,
7425                            flags, userId);
7426                    if (ri == null) {
7427                        continue;
7428                    }
7429                    if (ri == mResolveInfo) {
7430                        // ACK!  Must do something better with this.
7431                    }
7432                    ai = ri.activityInfo;
7433                    comp = new ComponentName(ai.applicationInfo.packageName,
7434                            ai.name);
7435                } else {
7436                    ai = getActivityInfo(comp, flags, userId);
7437                    if (ai == null) {
7438                        continue;
7439                    }
7440                }
7441
7442                // Look for any generic query activities that are duplicates
7443                // of this specific one, and remove them from the results.
7444                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7445                N = results.size();
7446                int j;
7447                for (j=specificsPos; j<N; j++) {
7448                    ResolveInfo sri = results.get(j);
7449                    if ((sri.activityInfo.name.equals(comp.getClassName())
7450                            && sri.activityInfo.applicationInfo.packageName.equals(
7451                                    comp.getPackageName()))
7452                        || (action != null && sri.filter.matchAction(action))) {
7453                        results.remove(j);
7454                        if (DEBUG_INTENT_MATCHING) Log.v(
7455                            TAG, "Removing duplicate item from " + j
7456                            + " due to specific " + specificsPos);
7457                        if (ri == null) {
7458                            ri = sri;
7459                        }
7460                        j--;
7461                        N--;
7462                    }
7463                }
7464
7465                // Add this specific item to its proper place.
7466                if (ri == null) {
7467                    ri = new ResolveInfo();
7468                    ri.activityInfo = ai;
7469                }
7470                results.add(specificsPos, ri);
7471                ri.specificIndex = i;
7472                specificsPos++;
7473            }
7474        }
7475
7476        // Now we go through the remaining generic results and remove any
7477        // duplicate actions that are found here.
7478        N = results.size();
7479        for (int i=specificsPos; i<N-1; i++) {
7480            final ResolveInfo rii = results.get(i);
7481            if (rii.filter == null) {
7482                continue;
7483            }
7484
7485            // Iterate over all of the actions of this result's intent
7486            // filter...  typically this should be just one.
7487            final Iterator<String> it = rii.filter.actionsIterator();
7488            if (it == null) {
7489                continue;
7490            }
7491            while (it.hasNext()) {
7492                final String action = it.next();
7493                if (resultsAction != null && resultsAction.equals(action)) {
7494                    // If this action was explicitly requested, then don't
7495                    // remove things that have it.
7496                    continue;
7497                }
7498                for (int j=i+1; j<N; j++) {
7499                    final ResolveInfo rij = results.get(j);
7500                    if (rij.filter != null && rij.filter.hasAction(action)) {
7501                        results.remove(j);
7502                        if (DEBUG_INTENT_MATCHING) Log.v(
7503                            TAG, "Removing duplicate item from " + j
7504                            + " due to action " + action + " at " + i);
7505                        j--;
7506                        N--;
7507                    }
7508                }
7509            }
7510
7511            // If the caller didn't request filter information, drop it now
7512            // so we don't have to marshall/unmarshall it.
7513            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7514                rii.filter = null;
7515            }
7516        }
7517
7518        // Filter out the caller activity if so requested.
7519        if (caller != null) {
7520            N = results.size();
7521            for (int i=0; i<N; i++) {
7522                ActivityInfo ainfo = results.get(i).activityInfo;
7523                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7524                        && caller.getClassName().equals(ainfo.name)) {
7525                    results.remove(i);
7526                    break;
7527                }
7528            }
7529        }
7530
7531        // If the caller didn't request filter information,
7532        // drop them now so we don't have to
7533        // marshall/unmarshall it.
7534        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7535            N = results.size();
7536            for (int i=0; i<N; i++) {
7537                results.get(i).filter = null;
7538            }
7539        }
7540
7541        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7542        return results;
7543    }
7544
7545    @Override
7546    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7547            String resolvedType, int flags, int userId) {
7548        return new ParceledListSlice<>(
7549                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7550    }
7551
7552    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7553            String resolvedType, int flags, int userId) {
7554        if (!sUserManager.exists(userId)) return Collections.emptyList();
7555        final int callingUid = Binder.getCallingUid();
7556        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7557                false /*includeInstantApps*/);
7558        ComponentName comp = intent.getComponent();
7559        if (comp == null) {
7560            if (intent.getSelector() != null) {
7561                intent = intent.getSelector();
7562                comp = intent.getComponent();
7563            }
7564        }
7565        if (comp != null) {
7566            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7567            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7568            if (ai != null) {
7569                ResolveInfo ri = new ResolveInfo();
7570                ri.activityInfo = ai;
7571                list.add(ri);
7572            }
7573            return list;
7574        }
7575
7576        // reader
7577        synchronized (mPackages) {
7578            String pkgName = intent.getPackage();
7579            if (pkgName == null) {
7580                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7581            }
7582            final PackageParser.Package pkg = mPackages.get(pkgName);
7583            if (pkg != null) {
7584                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7585                        userId);
7586            }
7587            return Collections.emptyList();
7588        }
7589    }
7590
7591    @Override
7592    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7593        final int callingUid = Binder.getCallingUid();
7594        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7595    }
7596
7597    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7598            int userId, int callingUid) {
7599        if (!sUserManager.exists(userId)) return null;
7600        flags = updateFlagsForResolve(
7601                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7602        List<ResolveInfo> query = queryIntentServicesInternal(
7603                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7604        if (query != null) {
7605            if (query.size() >= 1) {
7606                // If there is more than one service with the same priority,
7607                // just arbitrarily pick the first one.
7608                return query.get(0);
7609            }
7610        }
7611        return null;
7612    }
7613
7614    @Override
7615    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7616            String resolvedType, int flags, int userId) {
7617        final int callingUid = Binder.getCallingUid();
7618        return new ParceledListSlice<>(queryIntentServicesInternal(
7619                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7620    }
7621
7622    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7623            String resolvedType, int flags, int userId, int callingUid,
7624            boolean includeInstantApps) {
7625        if (!sUserManager.exists(userId)) return Collections.emptyList();
7626        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7627        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7628        ComponentName comp = intent.getComponent();
7629        if (comp == null) {
7630            if (intent.getSelector() != null) {
7631                intent = intent.getSelector();
7632                comp = intent.getComponent();
7633            }
7634        }
7635        if (comp != null) {
7636            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7637            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7638            if (si != null) {
7639                // When specifying an explicit component, we prevent the service from being
7640                // used when either 1) the service is in an instant application and the
7641                // caller is not the same instant application or 2) the calling package is
7642                // ephemeral and the activity is not visible to ephemeral applications.
7643                final boolean matchInstantApp =
7644                        (flags & PackageManager.MATCH_INSTANT) != 0;
7645                final boolean matchVisibleToInstantAppOnly =
7646                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7647                final boolean isCallerInstantApp =
7648                        instantAppPkgName != null;
7649                final boolean isTargetSameInstantApp =
7650                        comp.getPackageName().equals(instantAppPkgName);
7651                final boolean isTargetInstantApp =
7652                        (si.applicationInfo.privateFlags
7653                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7654                final boolean isTargetHiddenFromInstantApp =
7655                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7656                final boolean blockResolution =
7657                        !isTargetSameInstantApp
7658                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7659                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7660                                        && isTargetHiddenFromInstantApp));
7661                if (!blockResolution) {
7662                    final ResolveInfo ri = new ResolveInfo();
7663                    ri.serviceInfo = si;
7664                    list.add(ri);
7665                }
7666            }
7667            return list;
7668        }
7669
7670        // reader
7671        synchronized (mPackages) {
7672            String pkgName = intent.getPackage();
7673            if (pkgName == null) {
7674                return applyPostServiceResolutionFilter(
7675                        mServices.queryIntent(intent, resolvedType, flags, userId),
7676                        instantAppPkgName);
7677            }
7678            final PackageParser.Package pkg = mPackages.get(pkgName);
7679            if (pkg != null) {
7680                return applyPostServiceResolutionFilter(
7681                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7682                                userId),
7683                        instantAppPkgName);
7684            }
7685            return Collections.emptyList();
7686        }
7687    }
7688
7689    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7690            String instantAppPkgName) {
7691        // TODO: When adding on-demand split support for non-instant apps, remove this check
7692        // and always apply post filtering
7693        if (instantAppPkgName == null) {
7694            return resolveInfos;
7695        }
7696        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7697            final ResolveInfo info = resolveInfos.get(i);
7698            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7699            // allow services that are defined in the provided package
7700            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7701                if (info.serviceInfo.splitName != null
7702                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7703                                info.serviceInfo.splitName)) {
7704                    // requested service is defined in a split that hasn't been installed yet.
7705                    // add the installer to the resolve list
7706                    if (DEBUG_EPHEMERAL) {
7707                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7708                    }
7709                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7710                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7711                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7712                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7713                    // make sure this resolver is the default
7714                    installerInfo.isDefault = true;
7715                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7716                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7717                    // add a non-generic filter
7718                    installerInfo.filter = new IntentFilter();
7719                    // load resources from the correct package
7720                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7721                    resolveInfos.set(i, installerInfo);
7722                }
7723                continue;
7724            }
7725            // allow services that have been explicitly exposed to ephemeral apps
7726            if (!isEphemeralApp
7727                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7728                continue;
7729            }
7730            resolveInfos.remove(i);
7731        }
7732        return resolveInfos;
7733    }
7734
7735    @Override
7736    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7737            String resolvedType, int flags, int userId) {
7738        return new ParceledListSlice<>(
7739                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7740    }
7741
7742    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7743            Intent intent, String resolvedType, int flags, int userId) {
7744        if (!sUserManager.exists(userId)) return Collections.emptyList();
7745        final int callingUid = Binder.getCallingUid();
7746        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7747        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7748                false /*includeInstantApps*/);
7749        ComponentName comp = intent.getComponent();
7750        if (comp == null) {
7751            if (intent.getSelector() != null) {
7752                intent = intent.getSelector();
7753                comp = intent.getComponent();
7754            }
7755        }
7756        if (comp != null) {
7757            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7758            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7759            if (pi != null) {
7760                // When specifying an explicit component, we prevent the provider from being
7761                // used when either 1) the provider is in an instant application and the
7762                // caller is not the same instant application or 2) the calling package is an
7763                // instant application and the provider is not visible to instant applications.
7764                final boolean matchInstantApp =
7765                        (flags & PackageManager.MATCH_INSTANT) != 0;
7766                final boolean matchVisibleToInstantAppOnly =
7767                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7768                final boolean isCallerInstantApp =
7769                        instantAppPkgName != null;
7770                final boolean isTargetSameInstantApp =
7771                        comp.getPackageName().equals(instantAppPkgName);
7772                final boolean isTargetInstantApp =
7773                        (pi.applicationInfo.privateFlags
7774                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7775                final boolean isTargetHiddenFromInstantApp =
7776                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7777                final boolean blockResolution =
7778                        !isTargetSameInstantApp
7779                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7780                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7781                                        && isTargetHiddenFromInstantApp));
7782                if (!blockResolution) {
7783                    final ResolveInfo ri = new ResolveInfo();
7784                    ri.providerInfo = pi;
7785                    list.add(ri);
7786                }
7787            }
7788            return list;
7789        }
7790
7791        // reader
7792        synchronized (mPackages) {
7793            String pkgName = intent.getPackage();
7794            if (pkgName == null) {
7795                return applyPostContentProviderResolutionFilter(
7796                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7797                        instantAppPkgName);
7798            }
7799            final PackageParser.Package pkg = mPackages.get(pkgName);
7800            if (pkg != null) {
7801                return applyPostContentProviderResolutionFilter(
7802                        mProviders.queryIntentForPackage(
7803                        intent, resolvedType, flags, pkg.providers, userId),
7804                        instantAppPkgName);
7805            }
7806            return Collections.emptyList();
7807        }
7808    }
7809
7810    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7811            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7812        // TODO: When adding on-demand split support for non-instant applications, remove
7813        // this check and always apply post filtering
7814        if (instantAppPkgName == null) {
7815            return resolveInfos;
7816        }
7817        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7818            final ResolveInfo info = resolveInfos.get(i);
7819            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7820            // allow providers that are defined in the provided package
7821            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7822                if (info.providerInfo.splitName != null
7823                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7824                                info.providerInfo.splitName)) {
7825                    // requested provider is defined in a split that hasn't been installed yet.
7826                    // add the installer to the resolve list
7827                    if (DEBUG_EPHEMERAL) {
7828                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7829                    }
7830                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7831                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7832                            info.providerInfo.packageName, info.providerInfo.splitName,
7833                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
7834                    // make sure this resolver is the default
7835                    installerInfo.isDefault = true;
7836                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7837                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7838                    // add a non-generic filter
7839                    installerInfo.filter = new IntentFilter();
7840                    // load resources from the correct package
7841                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7842                    resolveInfos.set(i, installerInfo);
7843                }
7844                continue;
7845            }
7846            // allow providers that have been explicitly exposed to instant applications
7847            if (!isEphemeralApp
7848                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7849                continue;
7850            }
7851            resolveInfos.remove(i);
7852        }
7853        return resolveInfos;
7854    }
7855
7856    @Override
7857    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7858        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7859            return ParceledListSlice.emptyList();
7860        }
7861        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7862        flags = updateFlagsForPackage(flags, userId, null);
7863        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7864        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7865                true /* requireFullPermission */, false /* checkShell */,
7866                "get installed packages");
7867
7868        // writer
7869        synchronized (mPackages) {
7870            ArrayList<PackageInfo> list;
7871            if (listUninstalled) {
7872                list = new ArrayList<>(mSettings.mPackages.size());
7873                for (PackageSetting ps : mSettings.mPackages.values()) {
7874                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7875                        continue;
7876                    }
7877                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7878                    if (pi != null) {
7879                        list.add(pi);
7880                    }
7881                }
7882            } else {
7883                list = new ArrayList<>(mPackages.size());
7884                for (PackageParser.Package p : mPackages.values()) {
7885                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7886                            Binder.getCallingUid(), userId, flags)) {
7887                        continue;
7888                    }
7889                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7890                            p.mExtras, flags, userId);
7891                    if (pi != null) {
7892                        list.add(pi);
7893                    }
7894                }
7895            }
7896
7897            return new ParceledListSlice<>(list);
7898        }
7899    }
7900
7901    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7902            String[] permissions, boolean[] tmp, int flags, int userId) {
7903        int numMatch = 0;
7904        final PermissionsState permissionsState = ps.getPermissionsState();
7905        for (int i=0; i<permissions.length; i++) {
7906            final String permission = permissions[i];
7907            if (permissionsState.hasPermission(permission, userId)) {
7908                tmp[i] = true;
7909                numMatch++;
7910            } else {
7911                tmp[i] = false;
7912            }
7913        }
7914        if (numMatch == 0) {
7915            return;
7916        }
7917        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7918
7919        // The above might return null in cases of uninstalled apps or install-state
7920        // skew across users/profiles.
7921        if (pi != null) {
7922            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7923                if (numMatch == permissions.length) {
7924                    pi.requestedPermissions = permissions;
7925                } else {
7926                    pi.requestedPermissions = new String[numMatch];
7927                    numMatch = 0;
7928                    for (int i=0; i<permissions.length; i++) {
7929                        if (tmp[i]) {
7930                            pi.requestedPermissions[numMatch] = permissions[i];
7931                            numMatch++;
7932                        }
7933                    }
7934                }
7935            }
7936            list.add(pi);
7937        }
7938    }
7939
7940    @Override
7941    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7942            String[] permissions, int flags, int userId) {
7943        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7944        flags = updateFlagsForPackage(flags, userId, permissions);
7945        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7946                true /* requireFullPermission */, false /* checkShell */,
7947                "get packages holding permissions");
7948        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7949
7950        // writer
7951        synchronized (mPackages) {
7952            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7953            boolean[] tmpBools = new boolean[permissions.length];
7954            if (listUninstalled) {
7955                for (PackageSetting ps : mSettings.mPackages.values()) {
7956                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7957                            userId);
7958                }
7959            } else {
7960                for (PackageParser.Package pkg : mPackages.values()) {
7961                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7962                    if (ps != null) {
7963                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7964                                userId);
7965                    }
7966                }
7967            }
7968
7969            return new ParceledListSlice<PackageInfo>(list);
7970        }
7971    }
7972
7973    @Override
7974    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7975        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7976            return ParceledListSlice.emptyList();
7977        }
7978        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7979        flags = updateFlagsForApplication(flags, userId, null);
7980        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7981
7982        // writer
7983        synchronized (mPackages) {
7984            ArrayList<ApplicationInfo> list;
7985            if (listUninstalled) {
7986                list = new ArrayList<>(mSettings.mPackages.size());
7987                for (PackageSetting ps : mSettings.mPackages.values()) {
7988                    ApplicationInfo ai;
7989                    int effectiveFlags = flags;
7990                    if (ps.isSystem()) {
7991                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7992                    }
7993                    if (ps.pkg != null) {
7994                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7995                            continue;
7996                        }
7997                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7998                                ps.readUserState(userId), userId);
7999                        if (ai != null) {
8000                            rebaseEnabledOverlays(ai, userId);
8001                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8002                        }
8003                    } else {
8004                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8005                        // and already converts to externally visible package name
8006                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8007                                Binder.getCallingUid(), effectiveFlags, userId);
8008                    }
8009                    if (ai != null) {
8010                        list.add(ai);
8011                    }
8012                }
8013            } else {
8014                list = new ArrayList<>(mPackages.size());
8015                for (PackageParser.Package p : mPackages.values()) {
8016                    if (p.mExtras != null) {
8017                        PackageSetting ps = (PackageSetting) p.mExtras;
8018                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8019                            continue;
8020                        }
8021                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8022                                ps.readUserState(userId), userId);
8023                        if (ai != null) {
8024                            rebaseEnabledOverlays(ai, userId);
8025                            ai.packageName = resolveExternalPackageNameLPr(p);
8026                            list.add(ai);
8027                        }
8028                    }
8029                }
8030            }
8031
8032            return new ParceledListSlice<>(list);
8033        }
8034    }
8035
8036    @Override
8037    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8038        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8039            return null;
8040        }
8041        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8042                "getEphemeralApplications");
8043        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8044                true /* requireFullPermission */, false /* checkShell */,
8045                "getEphemeralApplications");
8046        synchronized (mPackages) {
8047            List<InstantAppInfo> instantApps = mInstantAppRegistry
8048                    .getInstantAppsLPr(userId);
8049            if (instantApps != null) {
8050                return new ParceledListSlice<>(instantApps);
8051            }
8052        }
8053        return null;
8054    }
8055
8056    @Override
8057    public boolean isInstantApp(String packageName, int userId) {
8058        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8059                true /* requireFullPermission */, false /* checkShell */,
8060                "isInstantApp");
8061        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8062            return false;
8063        }
8064        int callingUid = Binder.getCallingUid();
8065        if (Process.isIsolated(callingUid)) {
8066            callingUid = mIsolatedOwners.get(callingUid);
8067        }
8068
8069        synchronized (mPackages) {
8070            final PackageSetting ps = mSettings.mPackages.get(packageName);
8071            PackageParser.Package pkg = mPackages.get(packageName);
8072            final boolean returnAllowed =
8073                    ps != null
8074                    && (isCallerSameApp(packageName, callingUid)
8075                            || mContext.checkCallingOrSelfPermission(
8076                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
8077                                            == PERMISSION_GRANTED
8078                            || mInstantAppRegistry.isInstantAccessGranted(
8079                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8080            if (returnAllowed) {
8081                return ps.getInstantApp(userId);
8082            }
8083        }
8084        return false;
8085    }
8086
8087    @Override
8088    public byte[] getInstantAppCookie(String packageName, int userId) {
8089        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8090            return null;
8091        }
8092
8093        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8094                true /* requireFullPermission */, false /* checkShell */,
8095                "getInstantAppCookie");
8096        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8097            return null;
8098        }
8099        synchronized (mPackages) {
8100            return mInstantAppRegistry.getInstantAppCookieLPw(
8101                    packageName, userId);
8102        }
8103    }
8104
8105    @Override
8106    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8107        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8108            return true;
8109        }
8110
8111        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8112                true /* requireFullPermission */, true /* checkShell */,
8113                "setInstantAppCookie");
8114        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8115            return false;
8116        }
8117        synchronized (mPackages) {
8118            return mInstantAppRegistry.setInstantAppCookieLPw(
8119                    packageName, cookie, userId);
8120        }
8121    }
8122
8123    @Override
8124    public Bitmap getInstantAppIcon(String packageName, int userId) {
8125        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8126            return null;
8127        }
8128
8129        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8130                "getInstantAppIcon");
8131
8132        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8133                true /* requireFullPermission */, false /* checkShell */,
8134                "getInstantAppIcon");
8135
8136        synchronized (mPackages) {
8137            return mInstantAppRegistry.getInstantAppIconLPw(
8138                    packageName, userId);
8139        }
8140    }
8141
8142    private boolean isCallerSameApp(String packageName, int uid) {
8143        PackageParser.Package pkg = mPackages.get(packageName);
8144        return pkg != null
8145                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8146    }
8147
8148    @Override
8149    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8150        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8151            return ParceledListSlice.emptyList();
8152        }
8153        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8154    }
8155
8156    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8157        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8158
8159        // reader
8160        synchronized (mPackages) {
8161            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8162            final int userId = UserHandle.getCallingUserId();
8163            while (i.hasNext()) {
8164                final PackageParser.Package p = i.next();
8165                if (p.applicationInfo == null) continue;
8166
8167                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8168                        && !p.applicationInfo.isDirectBootAware();
8169                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8170                        && p.applicationInfo.isDirectBootAware();
8171
8172                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8173                        && (!mSafeMode || isSystemApp(p))
8174                        && (matchesUnaware || matchesAware)) {
8175                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8176                    if (ps != null) {
8177                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8178                                ps.readUserState(userId), userId);
8179                        if (ai != null) {
8180                            rebaseEnabledOverlays(ai, userId);
8181                            finalList.add(ai);
8182                        }
8183                    }
8184                }
8185            }
8186        }
8187
8188        return finalList;
8189    }
8190
8191    @Override
8192    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8193        if (!sUserManager.exists(userId)) return null;
8194        flags = updateFlagsForComponent(flags, userId, name);
8195        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8196        // reader
8197        synchronized (mPackages) {
8198            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8199            PackageSetting ps = provider != null
8200                    ? mSettings.mPackages.get(provider.owner.packageName)
8201                    : null;
8202            if (ps != null) {
8203                final boolean isInstantApp = ps.getInstantApp(userId);
8204                // normal application; filter out instant application provider
8205                if (instantAppPkgName == null && isInstantApp) {
8206                    return null;
8207                }
8208                // instant application; filter out other instant applications
8209                if (instantAppPkgName != null
8210                        && isInstantApp
8211                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8212                    return null;
8213                }
8214                // instant application; filter out non-exposed provider
8215                if (instantAppPkgName != null
8216                        && !isInstantApp
8217                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8218                    return null;
8219                }
8220                // provider not enabled
8221                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8222                    return null;
8223                }
8224                return PackageParser.generateProviderInfo(
8225                        provider, flags, ps.readUserState(userId), userId);
8226            }
8227            return null;
8228        }
8229    }
8230
8231    /**
8232     * @deprecated
8233     */
8234    @Deprecated
8235    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8236        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8237            return;
8238        }
8239        // reader
8240        synchronized (mPackages) {
8241            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8242                    .entrySet().iterator();
8243            final int userId = UserHandle.getCallingUserId();
8244            while (i.hasNext()) {
8245                Map.Entry<String, PackageParser.Provider> entry = i.next();
8246                PackageParser.Provider p = entry.getValue();
8247                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8248
8249                if (ps != null && p.syncable
8250                        && (!mSafeMode || (p.info.applicationInfo.flags
8251                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8252                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8253                            ps.readUserState(userId), userId);
8254                    if (info != null) {
8255                        outNames.add(entry.getKey());
8256                        outInfo.add(info);
8257                    }
8258                }
8259            }
8260        }
8261    }
8262
8263    @Override
8264    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8265            int uid, int flags, String metaDataKey) {
8266        final int userId = processName != null ? UserHandle.getUserId(uid)
8267                : UserHandle.getCallingUserId();
8268        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8269        flags = updateFlagsForComponent(flags, userId, processName);
8270
8271        ArrayList<ProviderInfo> finalList = null;
8272        // reader
8273        synchronized (mPackages) {
8274            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8275            while (i.hasNext()) {
8276                final PackageParser.Provider p = i.next();
8277                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8278                if (ps != null && p.info.authority != null
8279                        && (processName == null
8280                                || (p.info.processName.equals(processName)
8281                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8282                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8283
8284                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8285                    // parameter.
8286                    if (metaDataKey != null
8287                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8288                        continue;
8289                    }
8290
8291                    if (finalList == null) {
8292                        finalList = new ArrayList<ProviderInfo>(3);
8293                    }
8294                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8295                            ps.readUserState(userId), userId);
8296                    if (info != null) {
8297                        finalList.add(info);
8298                    }
8299                }
8300            }
8301        }
8302
8303        if (finalList != null) {
8304            Collections.sort(finalList, mProviderInitOrderSorter);
8305            return new ParceledListSlice<ProviderInfo>(finalList);
8306        }
8307
8308        return ParceledListSlice.emptyList();
8309    }
8310
8311    @Override
8312    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
8313        // reader
8314        synchronized (mPackages) {
8315            final PackageParser.Instrumentation i = mInstrumentation.get(name);
8316            return PackageParser.generateInstrumentationInfo(i, flags);
8317        }
8318    }
8319
8320    @Override
8321    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8322            String targetPackage, int flags) {
8323        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8324    }
8325
8326    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8327            int flags) {
8328        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8329
8330        // reader
8331        synchronized (mPackages) {
8332            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8333            while (i.hasNext()) {
8334                final PackageParser.Instrumentation p = i.next();
8335                if (targetPackage == null
8336                        || targetPackage.equals(p.info.targetPackage)) {
8337                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8338                            flags);
8339                    if (ii != null) {
8340                        finalList.add(ii);
8341                    }
8342                }
8343            }
8344        }
8345
8346        return finalList;
8347    }
8348
8349    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8350        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8351        try {
8352            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8353        } finally {
8354            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8355        }
8356    }
8357
8358    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8359        final File[] files = dir.listFiles();
8360        if (ArrayUtils.isEmpty(files)) {
8361            Log.d(TAG, "No files in app dir " + dir);
8362            return;
8363        }
8364
8365        if (DEBUG_PACKAGE_SCANNING) {
8366            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8367                    + " flags=0x" + Integer.toHexString(parseFlags));
8368        }
8369        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8370                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8371                mParallelPackageParserCallback);
8372
8373        // Submit files for parsing in parallel
8374        int fileCount = 0;
8375        for (File file : files) {
8376            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8377                    && !PackageInstallerService.isStageName(file.getName());
8378            if (!isPackage) {
8379                // Ignore entries which are not packages
8380                continue;
8381            }
8382            parallelPackageParser.submit(file, parseFlags);
8383            fileCount++;
8384        }
8385
8386        // Process results one by one
8387        for (; fileCount > 0; fileCount--) {
8388            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8389            Throwable throwable = parseResult.throwable;
8390            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8391
8392            if (throwable == null) {
8393                // Static shared libraries have synthetic package names
8394                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8395                    renameStaticSharedLibraryPackage(parseResult.pkg);
8396                }
8397                try {
8398                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8399                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8400                                currentTime, null);
8401                    }
8402                } catch (PackageManagerException e) {
8403                    errorCode = e.error;
8404                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8405                }
8406            } else if (throwable instanceof PackageParser.PackageParserException) {
8407                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8408                        throwable;
8409                errorCode = e.error;
8410                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8411            } else {
8412                throw new IllegalStateException("Unexpected exception occurred while parsing "
8413                        + parseResult.scanFile, throwable);
8414            }
8415
8416            // Delete invalid userdata apps
8417            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8418                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8419                logCriticalInfo(Log.WARN,
8420                        "Deleting invalid package at " + parseResult.scanFile);
8421                removeCodePathLI(parseResult.scanFile);
8422            }
8423        }
8424        parallelPackageParser.close();
8425    }
8426
8427    private static File getSettingsProblemFile() {
8428        File dataDir = Environment.getDataDirectory();
8429        File systemDir = new File(dataDir, "system");
8430        File fname = new File(systemDir, "uiderrors.txt");
8431        return fname;
8432    }
8433
8434    static void reportSettingsProblem(int priority, String msg) {
8435        logCriticalInfo(priority, msg);
8436    }
8437
8438    public static void logCriticalInfo(int priority, String msg) {
8439        Slog.println(priority, TAG, msg);
8440        EventLogTags.writePmCriticalInfo(msg);
8441        try {
8442            File fname = getSettingsProblemFile();
8443            FileOutputStream out = new FileOutputStream(fname, true);
8444            PrintWriter pw = new FastPrintWriter(out);
8445            SimpleDateFormat formatter = new SimpleDateFormat();
8446            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8447            pw.println(dateString + ": " + msg);
8448            pw.close();
8449            FileUtils.setPermissions(
8450                    fname.toString(),
8451                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8452                    -1, -1);
8453        } catch (java.io.IOException e) {
8454        }
8455    }
8456
8457    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8458        if (srcFile.isDirectory()) {
8459            final File baseFile = new File(pkg.baseCodePath);
8460            long maxModifiedTime = baseFile.lastModified();
8461            if (pkg.splitCodePaths != null) {
8462                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8463                    final File splitFile = new File(pkg.splitCodePaths[i]);
8464                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8465                }
8466            }
8467            return maxModifiedTime;
8468        }
8469        return srcFile.lastModified();
8470    }
8471
8472    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8473            final int policyFlags) throws PackageManagerException {
8474        // When upgrading from pre-N MR1, verify the package time stamp using the package
8475        // directory and not the APK file.
8476        final long lastModifiedTime = mIsPreNMR1Upgrade
8477                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8478        if (ps != null
8479                && ps.codePath.equals(srcFile)
8480                && ps.timeStamp == lastModifiedTime
8481                && !isCompatSignatureUpdateNeeded(pkg)
8482                && !isRecoverSignatureUpdateNeeded(pkg)) {
8483            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8484            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8485            ArraySet<PublicKey> signingKs;
8486            synchronized (mPackages) {
8487                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8488            }
8489            if (ps.signatures.mSignatures != null
8490                    && ps.signatures.mSignatures.length != 0
8491                    && signingKs != null) {
8492                // Optimization: reuse the existing cached certificates
8493                // if the package appears to be unchanged.
8494                pkg.mSignatures = ps.signatures.mSignatures;
8495                pkg.mSigningKeys = signingKs;
8496                return;
8497            }
8498
8499            Slog.w(TAG, "PackageSetting for " + ps.name
8500                    + " is missing signatures.  Collecting certs again to recover them.");
8501        } else {
8502            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8503        }
8504
8505        try {
8506            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8507            PackageParser.collectCertificates(pkg, policyFlags);
8508        } catch (PackageParserException e) {
8509            throw PackageManagerException.from(e);
8510        } finally {
8511            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8512        }
8513    }
8514
8515    /**
8516     *  Traces a package scan.
8517     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8518     */
8519    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8520            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8521        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8522        try {
8523            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8524        } finally {
8525            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8526        }
8527    }
8528
8529    /**
8530     *  Scans a package and returns the newly parsed package.
8531     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8532     */
8533    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8534            long currentTime, UserHandle user) throws PackageManagerException {
8535        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8536        PackageParser pp = new PackageParser();
8537        pp.setSeparateProcesses(mSeparateProcesses);
8538        pp.setOnlyCoreApps(mOnlyCore);
8539        pp.setDisplayMetrics(mMetrics);
8540        pp.setCallback(mPackageParserCallback);
8541
8542        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8543            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8544        }
8545
8546        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8547        final PackageParser.Package pkg;
8548        try {
8549            pkg = pp.parsePackage(scanFile, parseFlags);
8550        } catch (PackageParserException e) {
8551            throw PackageManagerException.from(e);
8552        } finally {
8553            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8554        }
8555
8556        // Static shared libraries have synthetic package names
8557        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8558            renameStaticSharedLibraryPackage(pkg);
8559        }
8560
8561        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8562    }
8563
8564    /**
8565     *  Scans a package and returns the newly parsed package.
8566     *  @throws PackageManagerException on a parse error.
8567     */
8568    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8569            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8570            throws PackageManagerException {
8571        // If the package has children and this is the first dive in the function
8572        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8573        // packages (parent and children) would be successfully scanned before the
8574        // actual scan since scanning mutates internal state and we want to atomically
8575        // install the package and its children.
8576        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8577            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8578                scanFlags |= SCAN_CHECK_ONLY;
8579            }
8580        } else {
8581            scanFlags &= ~SCAN_CHECK_ONLY;
8582        }
8583
8584        // Scan the parent
8585        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8586                scanFlags, currentTime, user);
8587
8588        // Scan the children
8589        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8590        for (int i = 0; i < childCount; i++) {
8591            PackageParser.Package childPackage = pkg.childPackages.get(i);
8592            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8593                    currentTime, user);
8594        }
8595
8596
8597        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8598            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8599        }
8600
8601        return scannedPkg;
8602    }
8603
8604    /**
8605     *  Scans a package and returns the newly parsed package.
8606     *  @throws PackageManagerException on a parse error.
8607     */
8608    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8609            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8610            throws PackageManagerException {
8611        PackageSetting ps = null;
8612        PackageSetting updatedPkg;
8613        // reader
8614        synchronized (mPackages) {
8615            // Look to see if we already know about this package.
8616            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8617            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8618                // This package has been renamed to its original name.  Let's
8619                // use that.
8620                ps = mSettings.getPackageLPr(oldName);
8621            }
8622            // If there was no original package, see one for the real package name.
8623            if (ps == null) {
8624                ps = mSettings.getPackageLPr(pkg.packageName);
8625            }
8626            // Check to see if this package could be hiding/updating a system
8627            // package.  Must look for it either under the original or real
8628            // package name depending on our state.
8629            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8630            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8631
8632            // If this is a package we don't know about on the system partition, we
8633            // may need to remove disabled child packages on the system partition
8634            // or may need to not add child packages if the parent apk is updated
8635            // on the data partition and no longer defines this child package.
8636            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8637                // If this is a parent package for an updated system app and this system
8638                // app got an OTA update which no longer defines some of the child packages
8639                // we have to prune them from the disabled system packages.
8640                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8641                if (disabledPs != null) {
8642                    final int scannedChildCount = (pkg.childPackages != null)
8643                            ? pkg.childPackages.size() : 0;
8644                    final int disabledChildCount = disabledPs.childPackageNames != null
8645                            ? disabledPs.childPackageNames.size() : 0;
8646                    for (int i = 0; i < disabledChildCount; i++) {
8647                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8648                        boolean disabledPackageAvailable = false;
8649                        for (int j = 0; j < scannedChildCount; j++) {
8650                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8651                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8652                                disabledPackageAvailable = true;
8653                                break;
8654                            }
8655                         }
8656                         if (!disabledPackageAvailable) {
8657                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8658                         }
8659                    }
8660                }
8661            }
8662        }
8663
8664        boolean updatedPkgBetter = false;
8665        // First check if this is a system package that may involve an update
8666        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8667            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8668            // it needs to drop FLAG_PRIVILEGED.
8669            if (locationIsPrivileged(scanFile)) {
8670                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8671            } else {
8672                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8673            }
8674
8675            if (ps != null && !ps.codePath.equals(scanFile)) {
8676                // The path has changed from what was last scanned...  check the
8677                // version of the new path against what we have stored to determine
8678                // what to do.
8679                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8680                if (pkg.mVersionCode <= ps.versionCode) {
8681                    // The system package has been updated and the code path does not match
8682                    // Ignore entry. Skip it.
8683                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8684                            + " ignored: updated version " + ps.versionCode
8685                            + " better than this " + pkg.mVersionCode);
8686                    if (!updatedPkg.codePath.equals(scanFile)) {
8687                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8688                                + ps.name + " changing from " + updatedPkg.codePathString
8689                                + " to " + scanFile);
8690                        updatedPkg.codePath = scanFile;
8691                        updatedPkg.codePathString = scanFile.toString();
8692                        updatedPkg.resourcePath = scanFile;
8693                        updatedPkg.resourcePathString = scanFile.toString();
8694                    }
8695                    updatedPkg.pkg = pkg;
8696                    updatedPkg.versionCode = pkg.mVersionCode;
8697
8698                    // Update the disabled system child packages to point to the package too.
8699                    final int childCount = updatedPkg.childPackageNames != null
8700                            ? updatedPkg.childPackageNames.size() : 0;
8701                    for (int i = 0; i < childCount; i++) {
8702                        String childPackageName = updatedPkg.childPackageNames.get(i);
8703                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8704                                childPackageName);
8705                        if (updatedChildPkg != null) {
8706                            updatedChildPkg.pkg = pkg;
8707                            updatedChildPkg.versionCode = pkg.mVersionCode;
8708                        }
8709                    }
8710
8711                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8712                            + scanFile + " ignored: updated version " + ps.versionCode
8713                            + " better than this " + pkg.mVersionCode);
8714                } else {
8715                    // The current app on the system partition is better than
8716                    // what we have updated to on the data partition; switch
8717                    // back to the system partition version.
8718                    // At this point, its safely assumed that package installation for
8719                    // apps in system partition will go through. If not there won't be a working
8720                    // version of the app
8721                    // writer
8722                    synchronized (mPackages) {
8723                        // Just remove the loaded entries from package lists.
8724                        mPackages.remove(ps.name);
8725                    }
8726
8727                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8728                            + " reverting from " + ps.codePathString
8729                            + ": new version " + pkg.mVersionCode
8730                            + " better than installed " + ps.versionCode);
8731
8732                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8733                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8734                    synchronized (mInstallLock) {
8735                        args.cleanUpResourcesLI();
8736                    }
8737                    synchronized (mPackages) {
8738                        mSettings.enableSystemPackageLPw(ps.name);
8739                    }
8740                    updatedPkgBetter = true;
8741                }
8742            }
8743        }
8744
8745        if (updatedPkg != null) {
8746            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8747            // initially
8748            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8749
8750            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8751            // flag set initially
8752            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8753                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8754            }
8755        }
8756
8757        // Verify certificates against what was last scanned
8758        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8759
8760        /*
8761         * A new system app appeared, but we already had a non-system one of the
8762         * same name installed earlier.
8763         */
8764        boolean shouldHideSystemApp = false;
8765        if (updatedPkg == null && ps != null
8766                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8767            /*
8768             * Check to make sure the signatures match first. If they don't,
8769             * wipe the installed application and its data.
8770             */
8771            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8772                    != PackageManager.SIGNATURE_MATCH) {
8773                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8774                        + " signatures don't match existing userdata copy; removing");
8775                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8776                        "scanPackageInternalLI")) {
8777                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8778                }
8779                ps = null;
8780            } else {
8781                /*
8782                 * If the newly-added system app is an older version than the
8783                 * already installed version, hide it. It will be scanned later
8784                 * and re-added like an update.
8785                 */
8786                if (pkg.mVersionCode <= ps.versionCode) {
8787                    shouldHideSystemApp = true;
8788                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8789                            + " but new version " + pkg.mVersionCode + " better than installed "
8790                            + ps.versionCode + "; hiding system");
8791                } else {
8792                    /*
8793                     * The newly found system app is a newer version that the
8794                     * one previously installed. Simply remove the
8795                     * already-installed application and replace it with our own
8796                     * while keeping the application data.
8797                     */
8798                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8799                            + " reverting from " + ps.codePathString + ": new version "
8800                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8801                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8802                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8803                    synchronized (mInstallLock) {
8804                        args.cleanUpResourcesLI();
8805                    }
8806                }
8807            }
8808        }
8809
8810        // The apk is forward locked (not public) if its code and resources
8811        // are kept in different files. (except for app in either system or
8812        // vendor path).
8813        // TODO grab this value from PackageSettings
8814        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8815            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8816                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8817            }
8818        }
8819
8820        // TODO: extend to support forward-locked splits
8821        String resourcePath = null;
8822        String baseResourcePath = null;
8823        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8824            if (ps != null && ps.resourcePathString != null) {
8825                resourcePath = ps.resourcePathString;
8826                baseResourcePath = ps.resourcePathString;
8827            } else {
8828                // Should not happen at all. Just log an error.
8829                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8830            }
8831        } else {
8832            resourcePath = pkg.codePath;
8833            baseResourcePath = pkg.baseCodePath;
8834        }
8835
8836        // Set application objects path explicitly.
8837        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8838        pkg.setApplicationInfoCodePath(pkg.codePath);
8839        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8840        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8841        pkg.setApplicationInfoResourcePath(resourcePath);
8842        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8843        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8844
8845        final int userId = ((user == null) ? 0 : user.getIdentifier());
8846        if (ps != null && ps.getInstantApp(userId)) {
8847            scanFlags |= SCAN_AS_INSTANT_APP;
8848        }
8849
8850        // Note that we invoke the following method only if we are about to unpack an application
8851        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8852                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8853
8854        /*
8855         * If the system app should be overridden by a previously installed
8856         * data, hide the system app now and let the /data/app scan pick it up
8857         * again.
8858         */
8859        if (shouldHideSystemApp) {
8860            synchronized (mPackages) {
8861                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8862            }
8863        }
8864
8865        return scannedPkg;
8866    }
8867
8868    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8869        // Derive the new package synthetic package name
8870        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8871                + pkg.staticSharedLibVersion);
8872    }
8873
8874    private static String fixProcessName(String defProcessName,
8875            String processName) {
8876        if (processName == null) {
8877            return defProcessName;
8878        }
8879        return processName;
8880    }
8881
8882    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8883            throws PackageManagerException {
8884        if (pkgSetting.signatures.mSignatures != null) {
8885            // Already existing package. Make sure signatures match
8886            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8887                    == PackageManager.SIGNATURE_MATCH;
8888            if (!match) {
8889                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8890                        == PackageManager.SIGNATURE_MATCH;
8891            }
8892            if (!match) {
8893                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8894                        == PackageManager.SIGNATURE_MATCH;
8895            }
8896            if (!match) {
8897                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8898                        + pkg.packageName + " signatures do not match the "
8899                        + "previously installed version; ignoring!");
8900            }
8901        }
8902
8903        // Check for shared user signatures
8904        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8905            // Already existing package. Make sure signatures match
8906            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8907                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8908            if (!match) {
8909                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8910                        == PackageManager.SIGNATURE_MATCH;
8911            }
8912            if (!match) {
8913                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8914                        == PackageManager.SIGNATURE_MATCH;
8915            }
8916            if (!match) {
8917                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8918                        "Package " + pkg.packageName
8919                        + " has no signatures that match those in shared user "
8920                        + pkgSetting.sharedUser.name + "; ignoring!");
8921            }
8922        }
8923    }
8924
8925    /**
8926     * Enforces that only the system UID or root's UID can call a method exposed
8927     * via Binder.
8928     *
8929     * @param message used as message if SecurityException is thrown
8930     * @throws SecurityException if the caller is not system or root
8931     */
8932    private static final void enforceSystemOrRoot(String message) {
8933        final int uid = Binder.getCallingUid();
8934        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8935            throw new SecurityException(message);
8936        }
8937    }
8938
8939    @Override
8940    public void performFstrimIfNeeded() {
8941        enforceSystemOrRoot("Only the system can request fstrim");
8942
8943        // Before everything else, see whether we need to fstrim.
8944        try {
8945            IStorageManager sm = PackageHelper.getStorageManager();
8946            if (sm != null) {
8947                boolean doTrim = false;
8948                final long interval = android.provider.Settings.Global.getLong(
8949                        mContext.getContentResolver(),
8950                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8951                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8952                if (interval > 0) {
8953                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8954                    if (timeSinceLast > interval) {
8955                        doTrim = true;
8956                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8957                                + "; running immediately");
8958                    }
8959                }
8960                if (doTrim) {
8961                    final boolean dexOptDialogShown;
8962                    synchronized (mPackages) {
8963                        dexOptDialogShown = mDexOptDialogShown;
8964                    }
8965                    if (!isFirstBoot() && dexOptDialogShown) {
8966                        try {
8967                            ActivityManager.getService().showBootMessage(
8968                                    mContext.getResources().getString(
8969                                            R.string.android_upgrading_fstrim), true);
8970                        } catch (RemoteException e) {
8971                        }
8972                    }
8973                    sm.runMaintenance();
8974                }
8975            } else {
8976                Slog.e(TAG, "storageManager service unavailable!");
8977            }
8978        } catch (RemoteException e) {
8979            // Can't happen; StorageManagerService is local
8980        }
8981    }
8982
8983    @Override
8984    public void updatePackagesIfNeeded() {
8985        enforceSystemOrRoot("Only the system can request package update");
8986
8987        // We need to re-extract after an OTA.
8988        boolean causeUpgrade = isUpgrade();
8989
8990        // First boot or factory reset.
8991        // Note: we also handle devices that are upgrading to N right now as if it is their
8992        //       first boot, as they do not have profile data.
8993        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8994
8995        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8996        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8997
8998        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8999            return;
9000        }
9001
9002        List<PackageParser.Package> pkgs;
9003        synchronized (mPackages) {
9004            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9005        }
9006
9007        final long startTime = System.nanoTime();
9008        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9009                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
9010
9011        final int elapsedTimeSeconds =
9012                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9013
9014        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9015        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9016        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9017        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9018        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9019    }
9020
9021    /**
9022     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9023     * containing statistics about the invocation. The array consists of three elements,
9024     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9025     * and {@code numberOfPackagesFailed}.
9026     */
9027    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9028            String compilerFilter) {
9029
9030        int numberOfPackagesVisited = 0;
9031        int numberOfPackagesOptimized = 0;
9032        int numberOfPackagesSkipped = 0;
9033        int numberOfPackagesFailed = 0;
9034        final int numberOfPackagesToDexopt = pkgs.size();
9035
9036        for (PackageParser.Package pkg : pkgs) {
9037            numberOfPackagesVisited++;
9038
9039            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9040                if (DEBUG_DEXOPT) {
9041                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9042                }
9043                numberOfPackagesSkipped++;
9044                continue;
9045            }
9046
9047            if (DEBUG_DEXOPT) {
9048                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9049                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9050            }
9051
9052            if (showDialog) {
9053                try {
9054                    ActivityManager.getService().showBootMessage(
9055                            mContext.getResources().getString(R.string.android_upgrading_apk,
9056                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9057                } catch (RemoteException e) {
9058                }
9059                synchronized (mPackages) {
9060                    mDexOptDialogShown = true;
9061                }
9062            }
9063
9064            // If the OTA updates a system app which was previously preopted to a non-preopted state
9065            // the app might end up being verified at runtime. That's because by default the apps
9066            // are verify-profile but for preopted apps there's no profile.
9067            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9068            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9069            // filter (by default 'quicken').
9070            // Note that at this stage unused apps are already filtered.
9071            if (isSystemApp(pkg) &&
9072                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9073                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9074                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9075            }
9076
9077            // checkProfiles is false to avoid merging profiles during boot which
9078            // might interfere with background compilation (b/28612421).
9079            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9080            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9081            // trade-off worth doing to save boot time work.
9082            int dexOptStatus = performDexOptTraced(pkg.packageName,
9083                    false /* checkProfiles */,
9084                    compilerFilter,
9085                    false /* force */);
9086            switch (dexOptStatus) {
9087                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9088                    numberOfPackagesOptimized++;
9089                    break;
9090                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9091                    numberOfPackagesSkipped++;
9092                    break;
9093                case PackageDexOptimizer.DEX_OPT_FAILED:
9094                    numberOfPackagesFailed++;
9095                    break;
9096                default:
9097                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9098                    break;
9099            }
9100        }
9101
9102        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9103                numberOfPackagesFailed };
9104    }
9105
9106    @Override
9107    public void notifyPackageUse(String packageName, int reason) {
9108        synchronized (mPackages) {
9109            if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
9110                return;
9111            }
9112            final PackageParser.Package p = mPackages.get(packageName);
9113            if (p == null) {
9114                return;
9115            }
9116            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9117        }
9118    }
9119
9120    @Override
9121    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9122        int userId = UserHandle.getCallingUserId();
9123        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9124        if (ai == null) {
9125            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9126                + loadingPackageName + ", user=" + userId);
9127            return;
9128        }
9129        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9130    }
9131
9132    @Override
9133    public boolean performDexOpt(String packageName,
9134            boolean checkProfiles, int compileReason, boolean force) {
9135        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9136                getCompilerFilterForReason(compileReason), force);
9137        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9138    }
9139
9140    @Override
9141    public boolean performDexOptMode(String packageName,
9142            boolean checkProfiles, String targetCompilerFilter, boolean force) {
9143        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9144            return false;
9145        }
9146        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9147                targetCompilerFilter, force);
9148        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9149    }
9150
9151    private int performDexOptTraced(String packageName,
9152                boolean checkProfiles, String targetCompilerFilter, boolean force) {
9153        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9154        try {
9155            return performDexOptInternal(packageName, checkProfiles,
9156                    targetCompilerFilter, force);
9157        } finally {
9158            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9159        }
9160    }
9161
9162    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9163    // if the package can now be considered up to date for the given filter.
9164    private int performDexOptInternal(String packageName,
9165                boolean checkProfiles, String targetCompilerFilter, boolean force) {
9166        PackageParser.Package p;
9167        synchronized (mPackages) {
9168            p = mPackages.get(packageName);
9169            if (p == null) {
9170                // Package could not be found. Report failure.
9171                return PackageDexOptimizer.DEX_OPT_FAILED;
9172            }
9173            mPackageUsage.maybeWriteAsync(mPackages);
9174            mCompilerStats.maybeWriteAsync();
9175        }
9176        long callingId = Binder.clearCallingIdentity();
9177        try {
9178            synchronized (mInstallLock) {
9179                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9180                        targetCompilerFilter, force);
9181            }
9182        } finally {
9183            Binder.restoreCallingIdentity(callingId);
9184        }
9185    }
9186
9187    public ArraySet<String> getOptimizablePackages() {
9188        ArraySet<String> pkgs = new ArraySet<String>();
9189        synchronized (mPackages) {
9190            for (PackageParser.Package p : mPackages.values()) {
9191                if (PackageDexOptimizer.canOptimizePackage(p)) {
9192                    pkgs.add(p.packageName);
9193                }
9194            }
9195        }
9196        return pkgs;
9197    }
9198
9199    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9200            boolean checkProfiles, String targetCompilerFilter,
9201            boolean force) {
9202        // Select the dex optimizer based on the force parameter.
9203        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9204        //       allocate an object here.
9205        PackageDexOptimizer pdo = force
9206                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9207                : mPackageDexOptimizer;
9208
9209        // Dexopt all dependencies first. Note: we ignore the return value and march on
9210        // on errors.
9211        // Note that we are going to call performDexOpt on those libraries as many times as
9212        // they are referenced in packages. When we do a batch of performDexOpt (for example
9213        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9214        // and the first package that uses the library will dexopt it. The
9215        // others will see that the compiled code for the library is up to date.
9216        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9217        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9218        if (!deps.isEmpty()) {
9219            for (PackageParser.Package depPackage : deps) {
9220                // TODO: Analyze and investigate if we (should) profile libraries.
9221                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9222                        false /* checkProfiles */,
9223                        targetCompilerFilter,
9224                        getOrCreateCompilerPackageStats(depPackage),
9225                        true /* isUsedByOtherApps */);
9226            }
9227        }
9228        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9229                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9230                mDexManager.isUsedByOtherApps(p.packageName));
9231    }
9232
9233    // Performs dexopt on the used secondary dex files belonging to the given package.
9234    // Returns true if all dex files were process successfully (which could mean either dexopt or
9235    // skip). Returns false if any of the files caused errors.
9236    @Override
9237    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9238            boolean force) {
9239        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9240            return false;
9241        }
9242        mDexManager.reconcileSecondaryDexFiles(packageName);
9243        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9244    }
9245
9246    public boolean performDexOptSecondary(String packageName, int compileReason,
9247            boolean force) {
9248        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9249    }
9250
9251    /**
9252     * Reconcile the information we have about the secondary dex files belonging to
9253     * {@code packagName} and the actual dex files. For all dex files that were
9254     * deleted, update the internal records and delete the generated oat files.
9255     */
9256    @Override
9257    public void reconcileSecondaryDexFiles(String packageName) {
9258        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9259            return;
9260        }
9261        mDexManager.reconcileSecondaryDexFiles(packageName);
9262    }
9263
9264    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9265    // a reference there.
9266    /*package*/ DexManager getDexManager() {
9267        return mDexManager;
9268    }
9269
9270    /**
9271     * Execute the background dexopt job immediately.
9272     */
9273    @Override
9274    public boolean runBackgroundDexoptJob() {
9275        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9276            return false;
9277        }
9278        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9279    }
9280
9281    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9282        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9283                || p.usesStaticLibraries != null) {
9284            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9285            Set<String> collectedNames = new HashSet<>();
9286            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9287
9288            retValue.remove(p);
9289
9290            return retValue;
9291        } else {
9292            return Collections.emptyList();
9293        }
9294    }
9295
9296    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9297            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9298        if (!collectedNames.contains(p.packageName)) {
9299            collectedNames.add(p.packageName);
9300            collected.add(p);
9301
9302            if (p.usesLibraries != null) {
9303                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9304                        null, collected, collectedNames);
9305            }
9306            if (p.usesOptionalLibraries != null) {
9307                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9308                        null, collected, collectedNames);
9309            }
9310            if (p.usesStaticLibraries != null) {
9311                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9312                        p.usesStaticLibrariesVersions, collected, collectedNames);
9313            }
9314        }
9315    }
9316
9317    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9318            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9319        final int libNameCount = libs.size();
9320        for (int i = 0; i < libNameCount; i++) {
9321            String libName = libs.get(i);
9322            int version = (versions != null && versions.length == libNameCount)
9323                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9324            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9325            if (libPkg != null) {
9326                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9327            }
9328        }
9329    }
9330
9331    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9332        synchronized (mPackages) {
9333            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9334            if (libEntry != null) {
9335                return mPackages.get(libEntry.apk);
9336            }
9337            return null;
9338        }
9339    }
9340
9341    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9342        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9343        if (versionedLib == null) {
9344            return null;
9345        }
9346        return versionedLib.get(version);
9347    }
9348
9349    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9350        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9351                pkg.staticSharedLibName);
9352        if (versionedLib == null) {
9353            return null;
9354        }
9355        int previousLibVersion = -1;
9356        final int versionCount = versionedLib.size();
9357        for (int i = 0; i < versionCount; i++) {
9358            final int libVersion = versionedLib.keyAt(i);
9359            if (libVersion < pkg.staticSharedLibVersion) {
9360                previousLibVersion = Math.max(previousLibVersion, libVersion);
9361            }
9362        }
9363        if (previousLibVersion >= 0) {
9364            return versionedLib.get(previousLibVersion);
9365        }
9366        return null;
9367    }
9368
9369    public void shutdown() {
9370        mPackageUsage.writeNow(mPackages);
9371        mCompilerStats.writeNow();
9372    }
9373
9374    @Override
9375    public void dumpProfiles(String packageName) {
9376        PackageParser.Package pkg;
9377        synchronized (mPackages) {
9378            pkg = mPackages.get(packageName);
9379            if (pkg == null) {
9380                throw new IllegalArgumentException("Unknown package: " + packageName);
9381            }
9382        }
9383        /* Only the shell, root, or the app user should be able to dump profiles. */
9384        int callingUid = Binder.getCallingUid();
9385        if (callingUid != Process.SHELL_UID &&
9386            callingUid != Process.ROOT_UID &&
9387            callingUid != pkg.applicationInfo.uid) {
9388            throw new SecurityException("dumpProfiles");
9389        }
9390
9391        synchronized (mInstallLock) {
9392            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9393            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9394            try {
9395                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9396                String codePaths = TextUtils.join(";", allCodePaths);
9397                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9398            } catch (InstallerException e) {
9399                Slog.w(TAG, "Failed to dump profiles", e);
9400            }
9401            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9402        }
9403    }
9404
9405    @Override
9406    public void forceDexOpt(String packageName) {
9407        enforceSystemOrRoot("forceDexOpt");
9408
9409        PackageParser.Package pkg;
9410        synchronized (mPackages) {
9411            pkg = mPackages.get(packageName);
9412            if (pkg == null) {
9413                throw new IllegalArgumentException("Unknown package: " + packageName);
9414            }
9415        }
9416
9417        synchronized (mInstallLock) {
9418            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9419
9420            // Whoever is calling forceDexOpt wants a compiled package.
9421            // Don't use profiles since that may cause compilation to be skipped.
9422            final int res = performDexOptInternalWithDependenciesLI(pkg,
9423                    false /* checkProfiles */, getDefaultCompilerFilter(),
9424                    true /* force */);
9425
9426            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9427            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9428                throw new IllegalStateException("Failed to dexopt: " + res);
9429            }
9430        }
9431    }
9432
9433    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9434        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9435            Slog.w(TAG, "Unable to update from " + oldPkg.name
9436                    + " to " + newPkg.packageName
9437                    + ": old package not in system partition");
9438            return false;
9439        } else if (mPackages.get(oldPkg.name) != null) {
9440            Slog.w(TAG, "Unable to update from " + oldPkg.name
9441                    + " to " + newPkg.packageName
9442                    + ": old package still exists");
9443            return false;
9444        }
9445        return true;
9446    }
9447
9448    void removeCodePathLI(File codePath) {
9449        if (codePath.isDirectory()) {
9450            try {
9451                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9452            } catch (InstallerException e) {
9453                Slog.w(TAG, "Failed to remove code path", e);
9454            }
9455        } else {
9456            codePath.delete();
9457        }
9458    }
9459
9460    private int[] resolveUserIds(int userId) {
9461        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9462    }
9463
9464    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9465        if (pkg == null) {
9466            Slog.wtf(TAG, "Package was null!", new Throwable());
9467            return;
9468        }
9469        clearAppDataLeafLIF(pkg, userId, flags);
9470        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9471        for (int i = 0; i < childCount; i++) {
9472            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9473        }
9474    }
9475
9476    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9477        final PackageSetting ps;
9478        synchronized (mPackages) {
9479            ps = mSettings.mPackages.get(pkg.packageName);
9480        }
9481        for (int realUserId : resolveUserIds(userId)) {
9482            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9483            try {
9484                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9485                        ceDataInode);
9486            } catch (InstallerException e) {
9487                Slog.w(TAG, String.valueOf(e));
9488            }
9489        }
9490    }
9491
9492    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9493        if (pkg == null) {
9494            Slog.wtf(TAG, "Package was null!", new Throwable());
9495            return;
9496        }
9497        destroyAppDataLeafLIF(pkg, userId, flags);
9498        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9499        for (int i = 0; i < childCount; i++) {
9500            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9501        }
9502    }
9503
9504    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9505        final PackageSetting ps;
9506        synchronized (mPackages) {
9507            ps = mSettings.mPackages.get(pkg.packageName);
9508        }
9509        for (int realUserId : resolveUserIds(userId)) {
9510            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9511            try {
9512                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9513                        ceDataInode);
9514            } catch (InstallerException e) {
9515                Slog.w(TAG, String.valueOf(e));
9516            }
9517            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9518        }
9519    }
9520
9521    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9522        if (pkg == null) {
9523            Slog.wtf(TAG, "Package was null!", new Throwable());
9524            return;
9525        }
9526        destroyAppProfilesLeafLIF(pkg);
9527        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9528        for (int i = 0; i < childCount; i++) {
9529            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9530        }
9531    }
9532
9533    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9534        try {
9535            mInstaller.destroyAppProfiles(pkg.packageName);
9536        } catch (InstallerException e) {
9537            Slog.w(TAG, String.valueOf(e));
9538        }
9539    }
9540
9541    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9542        if (pkg == null) {
9543            Slog.wtf(TAG, "Package was null!", new Throwable());
9544            return;
9545        }
9546        clearAppProfilesLeafLIF(pkg);
9547        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9548        for (int i = 0; i < childCount; i++) {
9549            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9550        }
9551    }
9552
9553    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9554        try {
9555            mInstaller.clearAppProfiles(pkg.packageName);
9556        } catch (InstallerException e) {
9557            Slog.w(TAG, String.valueOf(e));
9558        }
9559    }
9560
9561    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9562            long lastUpdateTime) {
9563        // Set parent install/update time
9564        PackageSetting ps = (PackageSetting) pkg.mExtras;
9565        if (ps != null) {
9566            ps.firstInstallTime = firstInstallTime;
9567            ps.lastUpdateTime = lastUpdateTime;
9568        }
9569        // Set children install/update time
9570        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9571        for (int i = 0; i < childCount; i++) {
9572            PackageParser.Package childPkg = pkg.childPackages.get(i);
9573            ps = (PackageSetting) childPkg.mExtras;
9574            if (ps != null) {
9575                ps.firstInstallTime = firstInstallTime;
9576                ps.lastUpdateTime = lastUpdateTime;
9577            }
9578        }
9579    }
9580
9581    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9582            PackageParser.Package changingLib) {
9583        if (file.path != null) {
9584            usesLibraryFiles.add(file.path);
9585            return;
9586        }
9587        PackageParser.Package p = mPackages.get(file.apk);
9588        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9589            // If we are doing this while in the middle of updating a library apk,
9590            // then we need to make sure to use that new apk for determining the
9591            // dependencies here.  (We haven't yet finished committing the new apk
9592            // to the package manager state.)
9593            if (p == null || p.packageName.equals(changingLib.packageName)) {
9594                p = changingLib;
9595            }
9596        }
9597        if (p != null) {
9598            usesLibraryFiles.addAll(p.getAllCodePaths());
9599            if (p.usesLibraryFiles != null) {
9600                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9601            }
9602        }
9603    }
9604
9605    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9606            PackageParser.Package changingLib) throws PackageManagerException {
9607        if (pkg == null) {
9608            return;
9609        }
9610        ArraySet<String> usesLibraryFiles = null;
9611        if (pkg.usesLibraries != null) {
9612            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9613                    null, null, pkg.packageName, changingLib, true, null);
9614        }
9615        if (pkg.usesStaticLibraries != null) {
9616            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9617                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9618                    pkg.packageName, changingLib, true, usesLibraryFiles);
9619        }
9620        if (pkg.usesOptionalLibraries != null) {
9621            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9622                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9623        }
9624        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9625            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9626        } else {
9627            pkg.usesLibraryFiles = null;
9628        }
9629    }
9630
9631    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9632            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9633            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9634            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9635            throws PackageManagerException {
9636        final int libCount = requestedLibraries.size();
9637        for (int i = 0; i < libCount; i++) {
9638            final String libName = requestedLibraries.get(i);
9639            final int libVersion = requiredVersions != null ? requiredVersions[i]
9640                    : SharedLibraryInfo.VERSION_UNDEFINED;
9641            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9642            if (libEntry == null) {
9643                if (required) {
9644                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9645                            "Package " + packageName + " requires unavailable shared library "
9646                                    + libName + "; failing!");
9647                } else if (DEBUG_SHARED_LIBRARIES) {
9648                    Slog.i(TAG, "Package " + packageName
9649                            + " desires unavailable shared library "
9650                            + libName + "; ignoring!");
9651                }
9652            } else {
9653                if (requiredVersions != null && requiredCertDigests != null) {
9654                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9655                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9656                            "Package " + packageName + " requires unavailable static shared"
9657                                    + " library " + libName + " version "
9658                                    + libEntry.info.getVersion() + "; failing!");
9659                    }
9660
9661                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9662                    if (libPkg == null) {
9663                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9664                                "Package " + packageName + " requires unavailable static shared"
9665                                        + " library; failing!");
9666                    }
9667
9668                    String expectedCertDigest = requiredCertDigests[i];
9669                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9670                                libPkg.mSignatures[0]);
9671                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9672                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9673                                "Package " + packageName + " requires differently signed" +
9674                                        " static shared library; failing!");
9675                    }
9676                }
9677
9678                if (outUsedLibraries == null) {
9679                    outUsedLibraries = new ArraySet<>();
9680                }
9681                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9682            }
9683        }
9684        return outUsedLibraries;
9685    }
9686
9687    private static boolean hasString(List<String> list, List<String> which) {
9688        if (list == null) {
9689            return false;
9690        }
9691        for (int i=list.size()-1; i>=0; i--) {
9692            for (int j=which.size()-1; j>=0; j--) {
9693                if (which.get(j).equals(list.get(i))) {
9694                    return true;
9695                }
9696            }
9697        }
9698        return false;
9699    }
9700
9701    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9702            PackageParser.Package changingPkg) {
9703        ArrayList<PackageParser.Package> res = null;
9704        for (PackageParser.Package pkg : mPackages.values()) {
9705            if (changingPkg != null
9706                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9707                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9708                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9709                            changingPkg.staticSharedLibName)) {
9710                return null;
9711            }
9712            if (res == null) {
9713                res = new ArrayList<>();
9714            }
9715            res.add(pkg);
9716            try {
9717                updateSharedLibrariesLPr(pkg, changingPkg);
9718            } catch (PackageManagerException e) {
9719                // If a system app update or an app and a required lib missing we
9720                // delete the package and for updated system apps keep the data as
9721                // it is better for the user to reinstall than to be in an limbo
9722                // state. Also libs disappearing under an app should never happen
9723                // - just in case.
9724                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9725                    final int flags = pkg.isUpdatedSystemApp()
9726                            ? PackageManager.DELETE_KEEP_DATA : 0;
9727                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9728                            flags , null, true, null);
9729                }
9730                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9731            }
9732        }
9733        return res;
9734    }
9735
9736    /**
9737     * Derive the value of the {@code cpuAbiOverride} based on the provided
9738     * value and an optional stored value from the package settings.
9739     */
9740    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9741        String cpuAbiOverride = null;
9742
9743        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9744            cpuAbiOverride = null;
9745        } else if (abiOverride != null) {
9746            cpuAbiOverride = abiOverride;
9747        } else if (settings != null) {
9748            cpuAbiOverride = settings.cpuAbiOverrideString;
9749        }
9750
9751        return cpuAbiOverride;
9752    }
9753
9754    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9755            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9756                    throws PackageManagerException {
9757        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9758        // If the package has children and this is the first dive in the function
9759        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9760        // whether all packages (parent and children) would be successfully scanned
9761        // before the actual scan since scanning mutates internal state and we want
9762        // to atomically install the package and its children.
9763        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9764            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9765                scanFlags |= SCAN_CHECK_ONLY;
9766            }
9767        } else {
9768            scanFlags &= ~SCAN_CHECK_ONLY;
9769        }
9770
9771        final PackageParser.Package scannedPkg;
9772        try {
9773            // Scan the parent
9774            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9775            // Scan the children
9776            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9777            for (int i = 0; i < childCount; i++) {
9778                PackageParser.Package childPkg = pkg.childPackages.get(i);
9779                scanPackageLI(childPkg, policyFlags,
9780                        scanFlags, currentTime, user);
9781            }
9782        } finally {
9783            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9784        }
9785
9786        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9787            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9788        }
9789
9790        return scannedPkg;
9791    }
9792
9793    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9794            int scanFlags, long currentTime, @Nullable UserHandle user)
9795                    throws PackageManagerException {
9796        boolean success = false;
9797        try {
9798            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9799                    currentTime, user);
9800            success = true;
9801            return res;
9802        } finally {
9803            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9804                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9805                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9806                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9807                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9808            }
9809        }
9810    }
9811
9812    /**
9813     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9814     */
9815    private static boolean apkHasCode(String fileName) {
9816        StrictJarFile jarFile = null;
9817        try {
9818            jarFile = new StrictJarFile(fileName,
9819                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9820            return jarFile.findEntry("classes.dex") != null;
9821        } catch (IOException ignore) {
9822        } finally {
9823            try {
9824                if (jarFile != null) {
9825                    jarFile.close();
9826                }
9827            } catch (IOException ignore) {}
9828        }
9829        return false;
9830    }
9831
9832    /**
9833     * Enforces code policy for the package. This ensures that if an APK has
9834     * declared hasCode="true" in its manifest that the APK actually contains
9835     * code.
9836     *
9837     * @throws PackageManagerException If bytecode could not be found when it should exist
9838     */
9839    private static void assertCodePolicy(PackageParser.Package pkg)
9840            throws PackageManagerException {
9841        final boolean shouldHaveCode =
9842                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9843        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9844            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9845                    "Package " + pkg.baseCodePath + " code is missing");
9846        }
9847
9848        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9849            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9850                final boolean splitShouldHaveCode =
9851                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9852                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9853                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9854                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9855                }
9856            }
9857        }
9858    }
9859
9860    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9861            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9862                    throws PackageManagerException {
9863        if (DEBUG_PACKAGE_SCANNING) {
9864            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9865                Log.d(TAG, "Scanning package " + pkg.packageName);
9866        }
9867
9868        applyPolicy(pkg, policyFlags);
9869
9870        assertPackageIsValid(pkg, policyFlags, scanFlags);
9871
9872        // Initialize package source and resource directories
9873        final File scanFile = new File(pkg.codePath);
9874        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9875        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9876
9877        SharedUserSetting suid = null;
9878        PackageSetting pkgSetting = null;
9879
9880        // Getting the package setting may have a side-effect, so if we
9881        // are only checking if scan would succeed, stash a copy of the
9882        // old setting to restore at the end.
9883        PackageSetting nonMutatedPs = null;
9884
9885        // We keep references to the derived CPU Abis from settings in oder to reuse
9886        // them in the case where we're not upgrading or booting for the first time.
9887        String primaryCpuAbiFromSettings = null;
9888        String secondaryCpuAbiFromSettings = null;
9889
9890        // writer
9891        synchronized (mPackages) {
9892            if (pkg.mSharedUserId != null) {
9893                // SIDE EFFECTS; may potentially allocate a new shared user
9894                suid = mSettings.getSharedUserLPw(
9895                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9896                if (DEBUG_PACKAGE_SCANNING) {
9897                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9898                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9899                                + "): packages=" + suid.packages);
9900                }
9901            }
9902
9903            // Check if we are renaming from an original package name.
9904            PackageSetting origPackage = null;
9905            String realName = null;
9906            if (pkg.mOriginalPackages != null) {
9907                // This package may need to be renamed to a previously
9908                // installed name.  Let's check on that...
9909                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9910                if (pkg.mOriginalPackages.contains(renamed)) {
9911                    // This package had originally been installed as the
9912                    // original name, and we have already taken care of
9913                    // transitioning to the new one.  Just update the new
9914                    // one to continue using the old name.
9915                    realName = pkg.mRealPackage;
9916                    if (!pkg.packageName.equals(renamed)) {
9917                        // Callers into this function may have already taken
9918                        // care of renaming the package; only do it here if
9919                        // it is not already done.
9920                        pkg.setPackageName(renamed);
9921                    }
9922                } else {
9923                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9924                        if ((origPackage = mSettings.getPackageLPr(
9925                                pkg.mOriginalPackages.get(i))) != null) {
9926                            // We do have the package already installed under its
9927                            // original name...  should we use it?
9928                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9929                                // New package is not compatible with original.
9930                                origPackage = null;
9931                                continue;
9932                            } else if (origPackage.sharedUser != null) {
9933                                // Make sure uid is compatible between packages.
9934                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9935                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9936                                            + " to " + pkg.packageName + ": old uid "
9937                                            + origPackage.sharedUser.name
9938                                            + " differs from " + pkg.mSharedUserId);
9939                                    origPackage = null;
9940                                    continue;
9941                                }
9942                                // TODO: Add case when shared user id is added [b/28144775]
9943                            } else {
9944                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9945                                        + pkg.packageName + " to old name " + origPackage.name);
9946                            }
9947                            break;
9948                        }
9949                    }
9950                }
9951            }
9952
9953            if (mTransferedPackages.contains(pkg.packageName)) {
9954                Slog.w(TAG, "Package " + pkg.packageName
9955                        + " was transferred to another, but its .apk remains");
9956            }
9957
9958            // See comments in nonMutatedPs declaration
9959            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9960                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9961                if (foundPs != null) {
9962                    nonMutatedPs = new PackageSetting(foundPs);
9963                }
9964            }
9965
9966            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9967                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9968                if (foundPs != null) {
9969                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9970                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9971                }
9972            }
9973
9974            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9975            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9976                PackageManagerService.reportSettingsProblem(Log.WARN,
9977                        "Package " + pkg.packageName + " shared user changed from "
9978                                + (pkgSetting.sharedUser != null
9979                                        ? pkgSetting.sharedUser.name : "<nothing>")
9980                                + " to "
9981                                + (suid != null ? suid.name : "<nothing>")
9982                                + "; replacing with new");
9983                pkgSetting = null;
9984            }
9985            final PackageSetting oldPkgSetting =
9986                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9987            final PackageSetting disabledPkgSetting =
9988                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9989
9990            String[] usesStaticLibraries = null;
9991            if (pkg.usesStaticLibraries != null) {
9992                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9993                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9994            }
9995
9996            if (pkgSetting == null) {
9997                final String parentPackageName = (pkg.parentPackage != null)
9998                        ? pkg.parentPackage.packageName : null;
9999                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10000                // REMOVE SharedUserSetting from method; update in a separate call
10001                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10002                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10003                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10004                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10005                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10006                        true /*allowInstall*/, instantApp, parentPackageName,
10007                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10008                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10009                // SIDE EFFECTS; updates system state; move elsewhere
10010                if (origPackage != null) {
10011                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10012                }
10013                mSettings.addUserToSettingLPw(pkgSetting);
10014            } else {
10015                // REMOVE SharedUserSetting from method; update in a separate call.
10016                //
10017                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10018                // secondaryCpuAbi are not known at this point so we always update them
10019                // to null here, only to reset them at a later point.
10020                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10021                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10022                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10023                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10024                        UserManagerService.getInstance(), usesStaticLibraries,
10025                        pkg.usesStaticLibrariesVersions);
10026            }
10027            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10028            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10029
10030            // SIDE EFFECTS; modifies system state; move elsewhere
10031            if (pkgSetting.origPackage != null) {
10032                // If we are first transitioning from an original package,
10033                // fix up the new package's name now.  We need to do this after
10034                // looking up the package under its new name, so getPackageLP
10035                // can take care of fiddling things correctly.
10036                pkg.setPackageName(origPackage.name);
10037
10038                // File a report about this.
10039                String msg = "New package " + pkgSetting.realName
10040                        + " renamed to replace old package " + pkgSetting.name;
10041                reportSettingsProblem(Log.WARN, msg);
10042
10043                // Make a note of it.
10044                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10045                    mTransferedPackages.add(origPackage.name);
10046                }
10047
10048                // No longer need to retain this.
10049                pkgSetting.origPackage = null;
10050            }
10051
10052            // SIDE EFFECTS; modifies system state; move elsewhere
10053            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10054                // Make a note of it.
10055                mTransferedPackages.add(pkg.packageName);
10056            }
10057
10058            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10059                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10060            }
10061
10062            if ((scanFlags & SCAN_BOOTING) == 0
10063                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10064                // Check all shared libraries and map to their actual file path.
10065                // We only do this here for apps not on a system dir, because those
10066                // are the only ones that can fail an install due to this.  We
10067                // will take care of the system apps by updating all of their
10068                // library paths after the scan is done. Also during the initial
10069                // scan don't update any libs as we do this wholesale after all
10070                // apps are scanned to avoid dependency based scanning.
10071                updateSharedLibrariesLPr(pkg, null);
10072            }
10073
10074            if (mFoundPolicyFile) {
10075                SELinuxMMAC.assignSeInfoValue(pkg);
10076            }
10077            pkg.applicationInfo.uid = pkgSetting.appId;
10078            pkg.mExtras = pkgSetting;
10079
10080
10081            // Static shared libs have same package with different versions where
10082            // we internally use a synthetic package name to allow multiple versions
10083            // of the same package, therefore we need to compare signatures against
10084            // the package setting for the latest library version.
10085            PackageSetting signatureCheckPs = pkgSetting;
10086            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10087                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10088                if (libraryEntry != null) {
10089                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10090                }
10091            }
10092
10093            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10094                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10095                    // We just determined the app is signed correctly, so bring
10096                    // over the latest parsed certs.
10097                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10098                } else {
10099                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10100                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10101                                "Package " + pkg.packageName + " upgrade keys do not match the "
10102                                + "previously installed version");
10103                    } else {
10104                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10105                        String msg = "System package " + pkg.packageName
10106                                + " signature changed; retaining data.";
10107                        reportSettingsProblem(Log.WARN, msg);
10108                    }
10109                }
10110            } else {
10111                try {
10112                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10113                    verifySignaturesLP(signatureCheckPs, pkg);
10114                    // We just determined the app is signed correctly, so bring
10115                    // over the latest parsed certs.
10116                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10117                } catch (PackageManagerException e) {
10118                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10119                        throw e;
10120                    }
10121                    // The signature has changed, but this package is in the system
10122                    // image...  let's recover!
10123                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10124                    // However...  if this package is part of a shared user, but it
10125                    // doesn't match the signature of the shared user, let's fail.
10126                    // What this means is that you can't change the signatures
10127                    // associated with an overall shared user, which doesn't seem all
10128                    // that unreasonable.
10129                    if (signatureCheckPs.sharedUser != null) {
10130                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10131                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10132                            throw new PackageManagerException(
10133                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10134                                    "Signature mismatch for shared user: "
10135                                            + pkgSetting.sharedUser);
10136                        }
10137                    }
10138                    // File a report about this.
10139                    String msg = "System package " + pkg.packageName
10140                            + " signature changed; retaining data.";
10141                    reportSettingsProblem(Log.WARN, msg);
10142                }
10143            }
10144
10145            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10146                // This package wants to adopt ownership of permissions from
10147                // another package.
10148                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10149                    final String origName = pkg.mAdoptPermissions.get(i);
10150                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10151                    if (orig != null) {
10152                        if (verifyPackageUpdateLPr(orig, pkg)) {
10153                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10154                                    + pkg.packageName);
10155                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10156                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10157                        }
10158                    }
10159                }
10160            }
10161        }
10162
10163        pkg.applicationInfo.processName = fixProcessName(
10164                pkg.applicationInfo.packageName,
10165                pkg.applicationInfo.processName);
10166
10167        if (pkg != mPlatformPackage) {
10168            // Get all of our default paths setup
10169            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10170        }
10171
10172        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10173
10174        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10175            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10176                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10177                derivePackageAbi(
10178                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
10179                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10180
10181                // Some system apps still use directory structure for native libraries
10182                // in which case we might end up not detecting abi solely based on apk
10183                // structure. Try to detect abi based on directory structure.
10184                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10185                        pkg.applicationInfo.primaryCpuAbi == null) {
10186                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10187                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10188                }
10189            } else {
10190                // This is not a first boot or an upgrade, don't bother deriving the
10191                // ABI during the scan. Instead, trust the value that was stored in the
10192                // package setting.
10193                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10194                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10195
10196                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10197
10198                if (DEBUG_ABI_SELECTION) {
10199                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10200                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10201                        pkg.applicationInfo.secondaryCpuAbi);
10202                }
10203            }
10204        } else {
10205            if ((scanFlags & SCAN_MOVE) != 0) {
10206                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10207                // but we already have this packages package info in the PackageSetting. We just
10208                // use that and derive the native library path based on the new codepath.
10209                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10210                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10211            }
10212
10213            // Set native library paths again. For moves, the path will be updated based on the
10214            // ABIs we've determined above. For non-moves, the path will be updated based on the
10215            // ABIs we determined during compilation, but the path will depend on the final
10216            // package path (after the rename away from the stage path).
10217            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10218        }
10219
10220        // This is a special case for the "system" package, where the ABI is
10221        // dictated by the zygote configuration (and init.rc). We should keep track
10222        // of this ABI so that we can deal with "normal" applications that run under
10223        // the same UID correctly.
10224        if (mPlatformPackage == pkg) {
10225            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10226                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10227        }
10228
10229        // If there's a mismatch between the abi-override in the package setting
10230        // and the abiOverride specified for the install. Warn about this because we
10231        // would've already compiled the app without taking the package setting into
10232        // account.
10233        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10234            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10235                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10236                        " for package " + pkg.packageName);
10237            }
10238        }
10239
10240        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10241        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10242        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10243
10244        // Copy the derived override back to the parsed package, so that we can
10245        // update the package settings accordingly.
10246        pkg.cpuAbiOverride = cpuAbiOverride;
10247
10248        if (DEBUG_ABI_SELECTION) {
10249            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10250                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10251                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10252        }
10253
10254        // Push the derived path down into PackageSettings so we know what to
10255        // clean up at uninstall time.
10256        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10257
10258        if (DEBUG_ABI_SELECTION) {
10259            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10260                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10261                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10262        }
10263
10264        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10265        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10266            // We don't do this here during boot because we can do it all
10267            // at once after scanning all existing packages.
10268            //
10269            // We also do this *before* we perform dexopt on this package, so that
10270            // we can avoid redundant dexopts, and also to make sure we've got the
10271            // code and package path correct.
10272            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10273        }
10274
10275        if (mFactoryTest && pkg.requestedPermissions.contains(
10276                android.Manifest.permission.FACTORY_TEST)) {
10277            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10278        }
10279
10280        if (isSystemApp(pkg)) {
10281            pkgSetting.isOrphaned = true;
10282        }
10283
10284        // Take care of first install / last update times.
10285        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10286        if (currentTime != 0) {
10287            if (pkgSetting.firstInstallTime == 0) {
10288                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10289            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10290                pkgSetting.lastUpdateTime = currentTime;
10291            }
10292        } else if (pkgSetting.firstInstallTime == 0) {
10293            // We need *something*.  Take time time stamp of the file.
10294            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10295        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10296            if (scanFileTime != pkgSetting.timeStamp) {
10297                // A package on the system image has changed; consider this
10298                // to be an update.
10299                pkgSetting.lastUpdateTime = scanFileTime;
10300            }
10301        }
10302        pkgSetting.setTimeStamp(scanFileTime);
10303
10304        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10305            if (nonMutatedPs != null) {
10306                synchronized (mPackages) {
10307                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10308                }
10309            }
10310        } else {
10311            final int userId = user == null ? 0 : user.getIdentifier();
10312            // Modify state for the given package setting
10313            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10314                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10315            if (pkgSetting.getInstantApp(userId)) {
10316                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10317            }
10318        }
10319        return pkg;
10320    }
10321
10322    /**
10323     * Applies policy to the parsed package based upon the given policy flags.
10324     * Ensures the package is in a good state.
10325     * <p>
10326     * Implementation detail: This method must NOT have any side effect. It would
10327     * ideally be static, but, it requires locks to read system state.
10328     */
10329    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10330        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10331            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10332            if (pkg.applicationInfo.isDirectBootAware()) {
10333                // we're direct boot aware; set for all components
10334                for (PackageParser.Service s : pkg.services) {
10335                    s.info.encryptionAware = s.info.directBootAware = true;
10336                }
10337                for (PackageParser.Provider p : pkg.providers) {
10338                    p.info.encryptionAware = p.info.directBootAware = true;
10339                }
10340                for (PackageParser.Activity a : pkg.activities) {
10341                    a.info.encryptionAware = a.info.directBootAware = true;
10342                }
10343                for (PackageParser.Activity r : pkg.receivers) {
10344                    r.info.encryptionAware = r.info.directBootAware = true;
10345                }
10346            }
10347        } else {
10348            // Only allow system apps to be flagged as core apps.
10349            pkg.coreApp = false;
10350            // clear flags not applicable to regular apps
10351            pkg.applicationInfo.privateFlags &=
10352                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10353            pkg.applicationInfo.privateFlags &=
10354                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10355        }
10356        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10357
10358        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10359            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10360        }
10361
10362        if (!isSystemApp(pkg)) {
10363            // Only system apps can use these features.
10364            pkg.mOriginalPackages = null;
10365            pkg.mRealPackage = null;
10366            pkg.mAdoptPermissions = null;
10367        }
10368    }
10369
10370    /**
10371     * Asserts the parsed package is valid according to the given policy. If the
10372     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10373     * <p>
10374     * Implementation detail: This method must NOT have any side effects. It would
10375     * ideally be static, but, it requires locks to read system state.
10376     *
10377     * @throws PackageManagerException If the package fails any of the validation checks
10378     */
10379    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10380            throws PackageManagerException {
10381        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10382            assertCodePolicy(pkg);
10383        }
10384
10385        if (pkg.applicationInfo.getCodePath() == null ||
10386                pkg.applicationInfo.getResourcePath() == null) {
10387            // Bail out. The resource and code paths haven't been set.
10388            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10389                    "Code and resource paths haven't been set correctly");
10390        }
10391
10392        // Make sure we're not adding any bogus keyset info
10393        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10394        ksms.assertScannedPackageValid(pkg);
10395
10396        synchronized (mPackages) {
10397            // The special "android" package can only be defined once
10398            if (pkg.packageName.equals("android")) {
10399                if (mAndroidApplication != null) {
10400                    Slog.w(TAG, "*************************************************");
10401                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10402                    Slog.w(TAG, " codePath=" + pkg.codePath);
10403                    Slog.w(TAG, "*************************************************");
10404                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10405                            "Core android package being redefined.  Skipping.");
10406                }
10407            }
10408
10409            // A package name must be unique; don't allow duplicates
10410            if (mPackages.containsKey(pkg.packageName)) {
10411                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10412                        "Application package " + pkg.packageName
10413                        + " already installed.  Skipping duplicate.");
10414            }
10415
10416            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10417                // Static libs have a synthetic package name containing the version
10418                // but we still want the base name to be unique.
10419                if (mPackages.containsKey(pkg.manifestPackageName)) {
10420                    throw new PackageManagerException(
10421                            "Duplicate static shared lib provider package");
10422                }
10423
10424                // Static shared libraries should have at least O target SDK
10425                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10426                    throw new PackageManagerException(
10427                            "Packages declaring static-shared libs must target O SDK or higher");
10428                }
10429
10430                // Package declaring static a shared lib cannot be instant apps
10431                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10432                    throw new PackageManagerException(
10433                            "Packages declaring static-shared libs cannot be instant apps");
10434                }
10435
10436                // Package declaring static a shared lib cannot be renamed since the package
10437                // name is synthetic and apps can't code around package manager internals.
10438                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10439                    throw new PackageManagerException(
10440                            "Packages declaring static-shared libs cannot be renamed");
10441                }
10442
10443                // Package declaring static a shared lib cannot declare child packages
10444                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10445                    throw new PackageManagerException(
10446                            "Packages declaring static-shared libs cannot have child packages");
10447                }
10448
10449                // Package declaring static a shared lib cannot declare dynamic libs
10450                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10451                    throw new PackageManagerException(
10452                            "Packages declaring static-shared libs cannot declare dynamic libs");
10453                }
10454
10455                // Package declaring static a shared lib cannot declare shared users
10456                if (pkg.mSharedUserId != null) {
10457                    throw new PackageManagerException(
10458                            "Packages declaring static-shared libs cannot declare shared users");
10459                }
10460
10461                // Static shared libs cannot declare activities
10462                if (!pkg.activities.isEmpty()) {
10463                    throw new PackageManagerException(
10464                            "Static shared libs cannot declare activities");
10465                }
10466
10467                // Static shared libs cannot declare services
10468                if (!pkg.services.isEmpty()) {
10469                    throw new PackageManagerException(
10470                            "Static shared libs cannot declare services");
10471                }
10472
10473                // Static shared libs cannot declare providers
10474                if (!pkg.providers.isEmpty()) {
10475                    throw new PackageManagerException(
10476                            "Static shared libs cannot declare content providers");
10477                }
10478
10479                // Static shared libs cannot declare receivers
10480                if (!pkg.receivers.isEmpty()) {
10481                    throw new PackageManagerException(
10482                            "Static shared libs cannot declare broadcast receivers");
10483                }
10484
10485                // Static shared libs cannot declare permission groups
10486                if (!pkg.permissionGroups.isEmpty()) {
10487                    throw new PackageManagerException(
10488                            "Static shared libs cannot declare permission groups");
10489                }
10490
10491                // Static shared libs cannot declare permissions
10492                if (!pkg.permissions.isEmpty()) {
10493                    throw new PackageManagerException(
10494                            "Static shared libs cannot declare permissions");
10495                }
10496
10497                // Static shared libs cannot declare protected broadcasts
10498                if (pkg.protectedBroadcasts != null) {
10499                    throw new PackageManagerException(
10500                            "Static shared libs cannot declare protected broadcasts");
10501                }
10502
10503                // Static shared libs cannot be overlay targets
10504                if (pkg.mOverlayTarget != null) {
10505                    throw new PackageManagerException(
10506                            "Static shared libs cannot be overlay targets");
10507                }
10508
10509                // The version codes must be ordered as lib versions
10510                int minVersionCode = Integer.MIN_VALUE;
10511                int maxVersionCode = Integer.MAX_VALUE;
10512
10513                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10514                        pkg.staticSharedLibName);
10515                if (versionedLib != null) {
10516                    final int versionCount = versionedLib.size();
10517                    for (int i = 0; i < versionCount; i++) {
10518                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10519                        // TODO: We will change version code to long, so in the new API it is long
10520                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
10521                                .getVersionCode();
10522                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10523                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10524                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10525                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10526                        } else {
10527                            minVersionCode = maxVersionCode = libVersionCode;
10528                            break;
10529                        }
10530                    }
10531                }
10532                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10533                    throw new PackageManagerException("Static shared"
10534                            + " lib version codes must be ordered as lib versions");
10535                }
10536            }
10537
10538            // Only privileged apps and updated privileged apps can add child packages.
10539            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10540                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10541                    throw new PackageManagerException("Only privileged apps can add child "
10542                            + "packages. Ignoring package " + pkg.packageName);
10543                }
10544                final int childCount = pkg.childPackages.size();
10545                for (int i = 0; i < childCount; i++) {
10546                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10547                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10548                            childPkg.packageName)) {
10549                        throw new PackageManagerException("Can't override child of "
10550                                + "another disabled app. Ignoring package " + pkg.packageName);
10551                    }
10552                }
10553            }
10554
10555            // If we're only installing presumed-existing packages, require that the
10556            // scanned APK is both already known and at the path previously established
10557            // for it.  Previously unknown packages we pick up normally, but if we have an
10558            // a priori expectation about this package's install presence, enforce it.
10559            // With a singular exception for new system packages. When an OTA contains
10560            // a new system package, we allow the codepath to change from a system location
10561            // to the user-installed location. If we don't allow this change, any newer,
10562            // user-installed version of the application will be ignored.
10563            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10564                if (mExpectingBetter.containsKey(pkg.packageName)) {
10565                    logCriticalInfo(Log.WARN,
10566                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10567                } else {
10568                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10569                    if (known != null) {
10570                        if (DEBUG_PACKAGE_SCANNING) {
10571                            Log.d(TAG, "Examining " + pkg.codePath
10572                                    + " and requiring known paths " + known.codePathString
10573                                    + " & " + known.resourcePathString);
10574                        }
10575                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10576                                || !pkg.applicationInfo.getResourcePath().equals(
10577                                        known.resourcePathString)) {
10578                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10579                                    "Application package " + pkg.packageName
10580                                    + " found at " + pkg.applicationInfo.getCodePath()
10581                                    + " but expected at " + known.codePathString
10582                                    + "; ignoring.");
10583                        }
10584                    }
10585                }
10586            }
10587
10588            // Verify that this new package doesn't have any content providers
10589            // that conflict with existing packages.  Only do this if the
10590            // package isn't already installed, since we don't want to break
10591            // things that are installed.
10592            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10593                final int N = pkg.providers.size();
10594                int i;
10595                for (i=0; i<N; i++) {
10596                    PackageParser.Provider p = pkg.providers.get(i);
10597                    if (p.info.authority != null) {
10598                        String names[] = p.info.authority.split(";");
10599                        for (int j = 0; j < names.length; j++) {
10600                            if (mProvidersByAuthority.containsKey(names[j])) {
10601                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10602                                final String otherPackageName =
10603                                        ((other != null && other.getComponentName() != null) ?
10604                                                other.getComponentName().getPackageName() : "?");
10605                                throw new PackageManagerException(
10606                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10607                                        "Can't install because provider name " + names[j]
10608                                                + " (in package " + pkg.applicationInfo.packageName
10609                                                + ") is already used by " + otherPackageName);
10610                            }
10611                        }
10612                    }
10613                }
10614            }
10615        }
10616    }
10617
10618    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10619            int type, String declaringPackageName, int declaringVersionCode) {
10620        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10621        if (versionedLib == null) {
10622            versionedLib = new SparseArray<>();
10623            mSharedLibraries.put(name, versionedLib);
10624            if (type == SharedLibraryInfo.TYPE_STATIC) {
10625                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10626            }
10627        } else if (versionedLib.indexOfKey(version) >= 0) {
10628            return false;
10629        }
10630        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10631                version, type, declaringPackageName, declaringVersionCode);
10632        versionedLib.put(version, libEntry);
10633        return true;
10634    }
10635
10636    private boolean removeSharedLibraryLPw(String name, int version) {
10637        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10638        if (versionedLib == null) {
10639            return false;
10640        }
10641        final int libIdx = versionedLib.indexOfKey(version);
10642        if (libIdx < 0) {
10643            return false;
10644        }
10645        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10646        versionedLib.remove(version);
10647        if (versionedLib.size() <= 0) {
10648            mSharedLibraries.remove(name);
10649            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10650                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10651                        .getPackageName());
10652            }
10653        }
10654        return true;
10655    }
10656
10657    /**
10658     * Adds a scanned package to the system. When this method is finished, the package will
10659     * be available for query, resolution, etc...
10660     */
10661    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10662            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10663        final String pkgName = pkg.packageName;
10664        if (mCustomResolverComponentName != null &&
10665                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10666            setUpCustomResolverActivity(pkg);
10667        }
10668
10669        if (pkg.packageName.equals("android")) {
10670            synchronized (mPackages) {
10671                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10672                    // Set up information for our fall-back user intent resolution activity.
10673                    mPlatformPackage = pkg;
10674                    pkg.mVersionCode = mSdkVersion;
10675                    mAndroidApplication = pkg.applicationInfo;
10676                    if (!mResolverReplaced) {
10677                        mResolveActivity.applicationInfo = mAndroidApplication;
10678                        mResolveActivity.name = ResolverActivity.class.getName();
10679                        mResolveActivity.packageName = mAndroidApplication.packageName;
10680                        mResolveActivity.processName = "system:ui";
10681                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10682                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10683                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10684                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10685                        mResolveActivity.exported = true;
10686                        mResolveActivity.enabled = true;
10687                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10688                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10689                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10690                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10691                                | ActivityInfo.CONFIG_ORIENTATION
10692                                | ActivityInfo.CONFIG_KEYBOARD
10693                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10694                        mResolveInfo.activityInfo = mResolveActivity;
10695                        mResolveInfo.priority = 0;
10696                        mResolveInfo.preferredOrder = 0;
10697                        mResolveInfo.match = 0;
10698                        mResolveComponentName = new ComponentName(
10699                                mAndroidApplication.packageName, mResolveActivity.name);
10700                    }
10701                }
10702            }
10703        }
10704
10705        ArrayList<PackageParser.Package> clientLibPkgs = null;
10706        // writer
10707        synchronized (mPackages) {
10708            boolean hasStaticSharedLibs = false;
10709
10710            // Any app can add new static shared libraries
10711            if (pkg.staticSharedLibName != null) {
10712                // Static shared libs don't allow renaming as they have synthetic package
10713                // names to allow install of multiple versions, so use name from manifest.
10714                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10715                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10716                        pkg.manifestPackageName, pkg.mVersionCode)) {
10717                    hasStaticSharedLibs = true;
10718                } else {
10719                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10720                                + pkg.staticSharedLibName + " already exists; skipping");
10721                }
10722                // Static shared libs cannot be updated once installed since they
10723                // use synthetic package name which includes the version code, so
10724                // not need to update other packages's shared lib dependencies.
10725            }
10726
10727            if (!hasStaticSharedLibs
10728                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10729                // Only system apps can add new dynamic shared libraries.
10730                if (pkg.libraryNames != null) {
10731                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10732                        String name = pkg.libraryNames.get(i);
10733                        boolean allowed = false;
10734                        if (pkg.isUpdatedSystemApp()) {
10735                            // New library entries can only be added through the
10736                            // system image.  This is important to get rid of a lot
10737                            // of nasty edge cases: for example if we allowed a non-
10738                            // system update of the app to add a library, then uninstalling
10739                            // the update would make the library go away, and assumptions
10740                            // we made such as through app install filtering would now
10741                            // have allowed apps on the device which aren't compatible
10742                            // with it.  Better to just have the restriction here, be
10743                            // conservative, and create many fewer cases that can negatively
10744                            // impact the user experience.
10745                            final PackageSetting sysPs = mSettings
10746                                    .getDisabledSystemPkgLPr(pkg.packageName);
10747                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10748                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10749                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10750                                        allowed = true;
10751                                        break;
10752                                    }
10753                                }
10754                            }
10755                        } else {
10756                            allowed = true;
10757                        }
10758                        if (allowed) {
10759                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10760                                    SharedLibraryInfo.VERSION_UNDEFINED,
10761                                    SharedLibraryInfo.TYPE_DYNAMIC,
10762                                    pkg.packageName, pkg.mVersionCode)) {
10763                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10764                                        + name + " already exists; skipping");
10765                            }
10766                        } else {
10767                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10768                                    + name + " that is not declared on system image; skipping");
10769                        }
10770                    }
10771
10772                    if ((scanFlags & SCAN_BOOTING) == 0) {
10773                        // If we are not booting, we need to update any applications
10774                        // that are clients of our shared library.  If we are booting,
10775                        // this will all be done once the scan is complete.
10776                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10777                    }
10778                }
10779            }
10780        }
10781
10782        if ((scanFlags & SCAN_BOOTING) != 0) {
10783            // No apps can run during boot scan, so they don't need to be frozen
10784        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10785            // Caller asked to not kill app, so it's probably not frozen
10786        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10787            // Caller asked us to ignore frozen check for some reason; they
10788            // probably didn't know the package name
10789        } else {
10790            // We're doing major surgery on this package, so it better be frozen
10791            // right now to keep it from launching
10792            checkPackageFrozen(pkgName);
10793        }
10794
10795        // Also need to kill any apps that are dependent on the library.
10796        if (clientLibPkgs != null) {
10797            for (int i=0; i<clientLibPkgs.size(); i++) {
10798                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10799                killApplication(clientPkg.applicationInfo.packageName,
10800                        clientPkg.applicationInfo.uid, "update lib");
10801            }
10802        }
10803
10804        // writer
10805        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10806
10807        synchronized (mPackages) {
10808            // We don't expect installation to fail beyond this point
10809
10810            // Add the new setting to mSettings
10811            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10812            // Add the new setting to mPackages
10813            mPackages.put(pkg.applicationInfo.packageName, pkg);
10814            // Make sure we don't accidentally delete its data.
10815            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10816            while (iter.hasNext()) {
10817                PackageCleanItem item = iter.next();
10818                if (pkgName.equals(item.packageName)) {
10819                    iter.remove();
10820                }
10821            }
10822
10823            // Add the package's KeySets to the global KeySetManagerService
10824            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10825            ksms.addScannedPackageLPw(pkg);
10826
10827            int N = pkg.providers.size();
10828            StringBuilder r = null;
10829            int i;
10830            for (i=0; i<N; i++) {
10831                PackageParser.Provider p = pkg.providers.get(i);
10832                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10833                        p.info.processName);
10834                mProviders.addProvider(p);
10835                p.syncable = p.info.isSyncable;
10836                if (p.info.authority != null) {
10837                    String names[] = p.info.authority.split(";");
10838                    p.info.authority = null;
10839                    for (int j = 0; j < names.length; j++) {
10840                        if (j == 1 && p.syncable) {
10841                            // We only want the first authority for a provider to possibly be
10842                            // syncable, so if we already added this provider using a different
10843                            // authority clear the syncable flag. We copy the provider before
10844                            // changing it because the mProviders object contains a reference
10845                            // to a provider that we don't want to change.
10846                            // Only do this for the second authority since the resulting provider
10847                            // object can be the same for all future authorities for this provider.
10848                            p = new PackageParser.Provider(p);
10849                            p.syncable = false;
10850                        }
10851                        if (!mProvidersByAuthority.containsKey(names[j])) {
10852                            mProvidersByAuthority.put(names[j], p);
10853                            if (p.info.authority == null) {
10854                                p.info.authority = names[j];
10855                            } else {
10856                                p.info.authority = p.info.authority + ";" + names[j];
10857                            }
10858                            if (DEBUG_PACKAGE_SCANNING) {
10859                                if (chatty)
10860                                    Log.d(TAG, "Registered content provider: " + names[j]
10861                                            + ", className = " + p.info.name + ", isSyncable = "
10862                                            + p.info.isSyncable);
10863                            }
10864                        } else {
10865                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10866                            Slog.w(TAG, "Skipping provider name " + names[j] +
10867                                    " (in package " + pkg.applicationInfo.packageName +
10868                                    "): name already used by "
10869                                    + ((other != null && other.getComponentName() != null)
10870                                            ? other.getComponentName().getPackageName() : "?"));
10871                        }
10872                    }
10873                }
10874                if (chatty) {
10875                    if (r == null) {
10876                        r = new StringBuilder(256);
10877                    } else {
10878                        r.append(' ');
10879                    }
10880                    r.append(p.info.name);
10881                }
10882            }
10883            if (r != null) {
10884                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10885            }
10886
10887            N = pkg.services.size();
10888            r = null;
10889            for (i=0; i<N; i++) {
10890                PackageParser.Service s = pkg.services.get(i);
10891                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10892                        s.info.processName);
10893                mServices.addService(s);
10894                if (chatty) {
10895                    if (r == null) {
10896                        r = new StringBuilder(256);
10897                    } else {
10898                        r.append(' ');
10899                    }
10900                    r.append(s.info.name);
10901                }
10902            }
10903            if (r != null) {
10904                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10905            }
10906
10907            N = pkg.receivers.size();
10908            r = null;
10909            for (i=0; i<N; i++) {
10910                PackageParser.Activity a = pkg.receivers.get(i);
10911                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10912                        a.info.processName);
10913                mReceivers.addActivity(a, "receiver");
10914                if (chatty) {
10915                    if (r == null) {
10916                        r = new StringBuilder(256);
10917                    } else {
10918                        r.append(' ');
10919                    }
10920                    r.append(a.info.name);
10921                }
10922            }
10923            if (r != null) {
10924                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10925            }
10926
10927            N = pkg.activities.size();
10928            r = null;
10929            for (i=0; i<N; i++) {
10930                PackageParser.Activity a = pkg.activities.get(i);
10931                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10932                        a.info.processName);
10933                mActivities.addActivity(a, "activity");
10934                if (chatty) {
10935                    if (r == null) {
10936                        r = new StringBuilder(256);
10937                    } else {
10938                        r.append(' ');
10939                    }
10940                    r.append(a.info.name);
10941                }
10942            }
10943            if (r != null) {
10944                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10945            }
10946
10947            N = pkg.permissionGroups.size();
10948            r = null;
10949            for (i=0; i<N; i++) {
10950                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10951                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10952                final String curPackageName = cur == null ? null : cur.info.packageName;
10953                // Dont allow ephemeral apps to define new permission groups.
10954                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10955                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10956                            + pg.info.packageName
10957                            + " ignored: instant apps cannot define new permission groups.");
10958                    continue;
10959                }
10960                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10961                if (cur == null || isPackageUpdate) {
10962                    mPermissionGroups.put(pg.info.name, pg);
10963                    if (chatty) {
10964                        if (r == null) {
10965                            r = new StringBuilder(256);
10966                        } else {
10967                            r.append(' ');
10968                        }
10969                        if (isPackageUpdate) {
10970                            r.append("UPD:");
10971                        }
10972                        r.append(pg.info.name);
10973                    }
10974                } else {
10975                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10976                            + pg.info.packageName + " ignored: original from "
10977                            + cur.info.packageName);
10978                    if (chatty) {
10979                        if (r == null) {
10980                            r = new StringBuilder(256);
10981                        } else {
10982                            r.append(' ');
10983                        }
10984                        r.append("DUP:");
10985                        r.append(pg.info.name);
10986                    }
10987                }
10988            }
10989            if (r != null) {
10990                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10991            }
10992
10993            N = pkg.permissions.size();
10994            r = null;
10995            for (i=0; i<N; i++) {
10996                PackageParser.Permission p = pkg.permissions.get(i);
10997
10998                // Dont allow ephemeral apps to define new permissions.
10999                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11000                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11001                            + p.info.packageName
11002                            + " ignored: instant apps cannot define new permissions.");
11003                    continue;
11004                }
11005
11006                // Assume by default that we did not install this permission into the system.
11007                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11008
11009                // Now that permission groups have a special meaning, we ignore permission
11010                // groups for legacy apps to prevent unexpected behavior. In particular,
11011                // permissions for one app being granted to someone just because they happen
11012                // to be in a group defined by another app (before this had no implications).
11013                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11014                    p.group = mPermissionGroups.get(p.info.group);
11015                    // Warn for a permission in an unknown group.
11016                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11017                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11018                                + p.info.packageName + " in an unknown group " + p.info.group);
11019                    }
11020                }
11021
11022                ArrayMap<String, BasePermission> permissionMap =
11023                        p.tree ? mSettings.mPermissionTrees
11024                                : mSettings.mPermissions;
11025                BasePermission bp = permissionMap.get(p.info.name);
11026
11027                // Allow system apps to redefine non-system permissions
11028                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11029                    final boolean currentOwnerIsSystem = (bp.perm != null
11030                            && isSystemApp(bp.perm.owner));
11031                    if (isSystemApp(p.owner)) {
11032                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11033                            // It's a built-in permission and no owner, take ownership now
11034                            bp.packageSetting = pkgSetting;
11035                            bp.perm = p;
11036                            bp.uid = pkg.applicationInfo.uid;
11037                            bp.sourcePackage = p.info.packageName;
11038                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11039                        } else if (!currentOwnerIsSystem) {
11040                            String msg = "New decl " + p.owner + " of permission  "
11041                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11042                            reportSettingsProblem(Log.WARN, msg);
11043                            bp = null;
11044                        }
11045                    }
11046                }
11047
11048                if (bp == null) {
11049                    bp = new BasePermission(p.info.name, p.info.packageName,
11050                            BasePermission.TYPE_NORMAL);
11051                    permissionMap.put(p.info.name, bp);
11052                }
11053
11054                if (bp.perm == null) {
11055                    if (bp.sourcePackage == null
11056                            || bp.sourcePackage.equals(p.info.packageName)) {
11057                        BasePermission tree = findPermissionTreeLP(p.info.name);
11058                        if (tree == null
11059                                || tree.sourcePackage.equals(p.info.packageName)) {
11060                            bp.packageSetting = pkgSetting;
11061                            bp.perm = p;
11062                            bp.uid = pkg.applicationInfo.uid;
11063                            bp.sourcePackage = p.info.packageName;
11064                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11065                            if (chatty) {
11066                                if (r == null) {
11067                                    r = new StringBuilder(256);
11068                                } else {
11069                                    r.append(' ');
11070                                }
11071                                r.append(p.info.name);
11072                            }
11073                        } else {
11074                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11075                                    + p.info.packageName + " ignored: base tree "
11076                                    + tree.name + " is from package "
11077                                    + tree.sourcePackage);
11078                        }
11079                    } else {
11080                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11081                                + p.info.packageName + " ignored: original from "
11082                                + bp.sourcePackage);
11083                    }
11084                } else if (chatty) {
11085                    if (r == null) {
11086                        r = new StringBuilder(256);
11087                    } else {
11088                        r.append(' ');
11089                    }
11090                    r.append("DUP:");
11091                    r.append(p.info.name);
11092                }
11093                if (bp.perm == p) {
11094                    bp.protectionLevel = p.info.protectionLevel;
11095                }
11096            }
11097
11098            if (r != null) {
11099                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11100            }
11101
11102            N = pkg.instrumentation.size();
11103            r = null;
11104            for (i=0; i<N; i++) {
11105                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11106                a.info.packageName = pkg.applicationInfo.packageName;
11107                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11108                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11109                a.info.splitNames = pkg.splitNames;
11110                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11111                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11112                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11113                a.info.dataDir = pkg.applicationInfo.dataDir;
11114                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11115                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11116                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11117                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11118                mInstrumentation.put(a.getComponentName(), a);
11119                if (chatty) {
11120                    if (r == null) {
11121                        r = new StringBuilder(256);
11122                    } else {
11123                        r.append(' ');
11124                    }
11125                    r.append(a.info.name);
11126                }
11127            }
11128            if (r != null) {
11129                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11130            }
11131
11132            if (pkg.protectedBroadcasts != null) {
11133                N = pkg.protectedBroadcasts.size();
11134                for (i=0; i<N; i++) {
11135                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11136                }
11137            }
11138        }
11139
11140        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11141    }
11142
11143    /**
11144     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11145     * is derived purely on the basis of the contents of {@code scanFile} and
11146     * {@code cpuAbiOverride}.
11147     *
11148     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11149     */
11150    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11151                                 String cpuAbiOverride, boolean extractLibs,
11152                                 File appLib32InstallDir)
11153            throws PackageManagerException {
11154        // Give ourselves some initial paths; we'll come back for another
11155        // pass once we've determined ABI below.
11156        setNativeLibraryPaths(pkg, appLib32InstallDir);
11157
11158        // We would never need to extract libs for forward-locked and external packages,
11159        // since the container service will do it for us. We shouldn't attempt to
11160        // extract libs from system app when it was not updated.
11161        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11162                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11163            extractLibs = false;
11164        }
11165
11166        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11167        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11168
11169        NativeLibraryHelper.Handle handle = null;
11170        try {
11171            handle = NativeLibraryHelper.Handle.create(pkg);
11172            // TODO(multiArch): This can be null for apps that didn't go through the
11173            // usual installation process. We can calculate it again, like we
11174            // do during install time.
11175            //
11176            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11177            // unnecessary.
11178            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11179
11180            // Null out the abis so that they can be recalculated.
11181            pkg.applicationInfo.primaryCpuAbi = null;
11182            pkg.applicationInfo.secondaryCpuAbi = null;
11183            if (isMultiArch(pkg.applicationInfo)) {
11184                // Warn if we've set an abiOverride for multi-lib packages..
11185                // By definition, we need to copy both 32 and 64 bit libraries for
11186                // such packages.
11187                if (pkg.cpuAbiOverride != null
11188                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11189                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11190                }
11191
11192                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11193                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11194                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11195                    if (extractLibs) {
11196                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11197                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11198                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11199                                useIsaSpecificSubdirs);
11200                    } else {
11201                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11202                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11203                    }
11204                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11205                }
11206
11207                maybeThrowExceptionForMultiArchCopy(
11208                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11209
11210                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11211                    if (extractLibs) {
11212                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11213                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11214                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11215                                useIsaSpecificSubdirs);
11216                    } else {
11217                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11218                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11219                    }
11220                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11221                }
11222
11223                maybeThrowExceptionForMultiArchCopy(
11224                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11225
11226                if (abi64 >= 0) {
11227                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11228                }
11229
11230                if (abi32 >= 0) {
11231                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11232                    if (abi64 >= 0) {
11233                        if (pkg.use32bitAbi) {
11234                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11235                            pkg.applicationInfo.primaryCpuAbi = abi;
11236                        } else {
11237                            pkg.applicationInfo.secondaryCpuAbi = abi;
11238                        }
11239                    } else {
11240                        pkg.applicationInfo.primaryCpuAbi = abi;
11241                    }
11242                }
11243
11244            } else {
11245                String[] abiList = (cpuAbiOverride != null) ?
11246                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11247
11248                // Enable gross and lame hacks for apps that are built with old
11249                // SDK tools. We must scan their APKs for renderscript bitcode and
11250                // not launch them if it's present. Don't bother checking on devices
11251                // that don't have 64 bit support.
11252                boolean needsRenderScriptOverride = false;
11253                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11254                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11255                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11256                    needsRenderScriptOverride = true;
11257                }
11258
11259                final int copyRet;
11260                if (extractLibs) {
11261                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11262                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11263                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11264                } else {
11265                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11266                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11267                }
11268                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11269
11270                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11271                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11272                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11273                }
11274
11275                if (copyRet >= 0) {
11276                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11277                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11278                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11279                } else if (needsRenderScriptOverride) {
11280                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11281                }
11282            }
11283        } catch (IOException ioe) {
11284            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11285        } finally {
11286            IoUtils.closeQuietly(handle);
11287        }
11288
11289        // Now that we've calculated the ABIs and determined if it's an internal app,
11290        // we will go ahead and populate the nativeLibraryPath.
11291        setNativeLibraryPaths(pkg, appLib32InstallDir);
11292    }
11293
11294    /**
11295     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11296     * i.e, so that all packages can be run inside a single process if required.
11297     *
11298     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11299     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11300     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11301     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11302     * updating a package that belongs to a shared user.
11303     *
11304     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11305     * adds unnecessary complexity.
11306     */
11307    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11308            PackageParser.Package scannedPackage) {
11309        String requiredInstructionSet = null;
11310        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11311            requiredInstructionSet = VMRuntime.getInstructionSet(
11312                     scannedPackage.applicationInfo.primaryCpuAbi);
11313        }
11314
11315        PackageSetting requirer = null;
11316        for (PackageSetting ps : packagesForUser) {
11317            // If packagesForUser contains scannedPackage, we skip it. This will happen
11318            // when scannedPackage is an update of an existing package. Without this check,
11319            // we will never be able to change the ABI of any package belonging to a shared
11320            // user, even if it's compatible with other packages.
11321            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11322                if (ps.primaryCpuAbiString == null) {
11323                    continue;
11324                }
11325
11326                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11327                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11328                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11329                    // this but there's not much we can do.
11330                    String errorMessage = "Instruction set mismatch, "
11331                            + ((requirer == null) ? "[caller]" : requirer)
11332                            + " requires " + requiredInstructionSet + " whereas " + ps
11333                            + " requires " + instructionSet;
11334                    Slog.w(TAG, errorMessage);
11335                }
11336
11337                if (requiredInstructionSet == null) {
11338                    requiredInstructionSet = instructionSet;
11339                    requirer = ps;
11340                }
11341            }
11342        }
11343
11344        if (requiredInstructionSet != null) {
11345            String adjustedAbi;
11346            if (requirer != null) {
11347                // requirer != null implies that either scannedPackage was null or that scannedPackage
11348                // did not require an ABI, in which case we have to adjust scannedPackage to match
11349                // the ABI of the set (which is the same as requirer's ABI)
11350                adjustedAbi = requirer.primaryCpuAbiString;
11351                if (scannedPackage != null) {
11352                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11353                }
11354            } else {
11355                // requirer == null implies that we're updating all ABIs in the set to
11356                // match scannedPackage.
11357                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11358            }
11359
11360            for (PackageSetting ps : packagesForUser) {
11361                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11362                    if (ps.primaryCpuAbiString != null) {
11363                        continue;
11364                    }
11365
11366                    ps.primaryCpuAbiString = adjustedAbi;
11367                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11368                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11369                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11370                        if (DEBUG_ABI_SELECTION) {
11371                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11372                                    + " (requirer="
11373                                    + (requirer != null ? requirer.pkg : "null")
11374                                    + ", scannedPackage="
11375                                    + (scannedPackage != null ? scannedPackage : "null")
11376                                    + ")");
11377                        }
11378                        try {
11379                            mInstaller.rmdex(ps.codePathString,
11380                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11381                        } catch (InstallerException ignored) {
11382                        }
11383                    }
11384                }
11385            }
11386        }
11387    }
11388
11389    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11390        synchronized (mPackages) {
11391            mResolverReplaced = true;
11392            // Set up information for custom user intent resolution activity.
11393            mResolveActivity.applicationInfo = pkg.applicationInfo;
11394            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11395            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11396            mResolveActivity.processName = pkg.applicationInfo.packageName;
11397            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11398            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11399                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11400            mResolveActivity.theme = 0;
11401            mResolveActivity.exported = true;
11402            mResolveActivity.enabled = true;
11403            mResolveInfo.activityInfo = mResolveActivity;
11404            mResolveInfo.priority = 0;
11405            mResolveInfo.preferredOrder = 0;
11406            mResolveInfo.match = 0;
11407            mResolveComponentName = mCustomResolverComponentName;
11408            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11409                    mResolveComponentName);
11410        }
11411    }
11412
11413    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11414        if (installerActivity == null) {
11415            if (DEBUG_EPHEMERAL) {
11416                Slog.d(TAG, "Clear ephemeral installer activity");
11417            }
11418            mInstantAppInstallerActivity = null;
11419            return;
11420        }
11421
11422        if (DEBUG_EPHEMERAL) {
11423            Slog.d(TAG, "Set ephemeral installer activity: "
11424                    + installerActivity.getComponentName());
11425        }
11426        // Set up information for ephemeral installer activity
11427        mInstantAppInstallerActivity = installerActivity;
11428        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11429                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11430        mInstantAppInstallerActivity.exported = true;
11431        mInstantAppInstallerActivity.enabled = true;
11432        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11433        mInstantAppInstallerInfo.priority = 0;
11434        mInstantAppInstallerInfo.preferredOrder = 1;
11435        mInstantAppInstallerInfo.isDefault = true;
11436        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11437                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11438    }
11439
11440    private static String calculateBundledApkRoot(final String codePathString) {
11441        final File codePath = new File(codePathString);
11442        final File codeRoot;
11443        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11444            codeRoot = Environment.getRootDirectory();
11445        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11446            codeRoot = Environment.getOemDirectory();
11447        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11448            codeRoot = Environment.getVendorDirectory();
11449        } else {
11450            // Unrecognized code path; take its top real segment as the apk root:
11451            // e.g. /something/app/blah.apk => /something
11452            try {
11453                File f = codePath.getCanonicalFile();
11454                File parent = f.getParentFile();    // non-null because codePath is a file
11455                File tmp;
11456                while ((tmp = parent.getParentFile()) != null) {
11457                    f = parent;
11458                    parent = tmp;
11459                }
11460                codeRoot = f;
11461                Slog.w(TAG, "Unrecognized code path "
11462                        + codePath + " - using " + codeRoot);
11463            } catch (IOException e) {
11464                // Can't canonicalize the code path -- shenanigans?
11465                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11466                return Environment.getRootDirectory().getPath();
11467            }
11468        }
11469        return codeRoot.getPath();
11470    }
11471
11472    /**
11473     * Derive and set the location of native libraries for the given package,
11474     * which varies depending on where and how the package was installed.
11475     */
11476    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11477        final ApplicationInfo info = pkg.applicationInfo;
11478        final String codePath = pkg.codePath;
11479        final File codeFile = new File(codePath);
11480        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11481        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11482
11483        info.nativeLibraryRootDir = null;
11484        info.nativeLibraryRootRequiresIsa = false;
11485        info.nativeLibraryDir = null;
11486        info.secondaryNativeLibraryDir = null;
11487
11488        if (isApkFile(codeFile)) {
11489            // Monolithic install
11490            if (bundledApp) {
11491                // If "/system/lib64/apkname" exists, assume that is the per-package
11492                // native library directory to use; otherwise use "/system/lib/apkname".
11493                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11494                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11495                        getPrimaryInstructionSet(info));
11496
11497                // This is a bundled system app so choose the path based on the ABI.
11498                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11499                // is just the default path.
11500                final String apkName = deriveCodePathName(codePath);
11501                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11502                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11503                        apkName).getAbsolutePath();
11504
11505                if (info.secondaryCpuAbi != null) {
11506                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11507                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11508                            secondaryLibDir, apkName).getAbsolutePath();
11509                }
11510            } else if (asecApp) {
11511                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11512                        .getAbsolutePath();
11513            } else {
11514                final String apkName = deriveCodePathName(codePath);
11515                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11516                        .getAbsolutePath();
11517            }
11518
11519            info.nativeLibraryRootRequiresIsa = false;
11520            info.nativeLibraryDir = info.nativeLibraryRootDir;
11521        } else {
11522            // Cluster install
11523            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11524            info.nativeLibraryRootRequiresIsa = true;
11525
11526            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11527                    getPrimaryInstructionSet(info)).getAbsolutePath();
11528
11529            if (info.secondaryCpuAbi != null) {
11530                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11531                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11532            }
11533        }
11534    }
11535
11536    /**
11537     * Calculate the abis and roots for a bundled app. These can uniquely
11538     * be determined from the contents of the system partition, i.e whether
11539     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11540     * of this information, and instead assume that the system was built
11541     * sensibly.
11542     */
11543    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11544                                           PackageSetting pkgSetting) {
11545        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11546
11547        // If "/system/lib64/apkname" exists, assume that is the per-package
11548        // native library directory to use; otherwise use "/system/lib/apkname".
11549        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11550        setBundledAppAbi(pkg, apkRoot, apkName);
11551        // pkgSetting might be null during rescan following uninstall of updates
11552        // to a bundled app, so accommodate that possibility.  The settings in
11553        // that case will be established later from the parsed package.
11554        //
11555        // If the settings aren't null, sync them up with what we've just derived.
11556        // note that apkRoot isn't stored in the package settings.
11557        if (pkgSetting != null) {
11558            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11559            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11560        }
11561    }
11562
11563    /**
11564     * Deduces the ABI of a bundled app and sets the relevant fields on the
11565     * parsed pkg object.
11566     *
11567     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11568     *        under which system libraries are installed.
11569     * @param apkName the name of the installed package.
11570     */
11571    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11572        final File codeFile = new File(pkg.codePath);
11573
11574        final boolean has64BitLibs;
11575        final boolean has32BitLibs;
11576        if (isApkFile(codeFile)) {
11577            // Monolithic install
11578            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11579            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11580        } else {
11581            // Cluster install
11582            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11583            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11584                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11585                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11586                has64BitLibs = (new File(rootDir, isa)).exists();
11587            } else {
11588                has64BitLibs = false;
11589            }
11590            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11591                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11592                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11593                has32BitLibs = (new File(rootDir, isa)).exists();
11594            } else {
11595                has32BitLibs = false;
11596            }
11597        }
11598
11599        if (has64BitLibs && !has32BitLibs) {
11600            // The package has 64 bit libs, but not 32 bit libs. Its primary
11601            // ABI should be 64 bit. We can safely assume here that the bundled
11602            // native libraries correspond to the most preferred ABI in the list.
11603
11604            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11605            pkg.applicationInfo.secondaryCpuAbi = null;
11606        } else if (has32BitLibs && !has64BitLibs) {
11607            // The package has 32 bit libs but not 64 bit libs. Its primary
11608            // ABI should be 32 bit.
11609
11610            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11611            pkg.applicationInfo.secondaryCpuAbi = null;
11612        } else if (has32BitLibs && has64BitLibs) {
11613            // The application has both 64 and 32 bit bundled libraries. We check
11614            // here that the app declares multiArch support, and warn if it doesn't.
11615            //
11616            // We will be lenient here and record both ABIs. The primary will be the
11617            // ABI that's higher on the list, i.e, a device that's configured to prefer
11618            // 64 bit apps will see a 64 bit primary ABI,
11619
11620            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11621                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11622            }
11623
11624            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11625                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11626                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11627            } else {
11628                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11629                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11630            }
11631        } else {
11632            pkg.applicationInfo.primaryCpuAbi = null;
11633            pkg.applicationInfo.secondaryCpuAbi = null;
11634        }
11635    }
11636
11637    private void killApplication(String pkgName, int appId, String reason) {
11638        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11639    }
11640
11641    private void killApplication(String pkgName, int appId, int userId, String reason) {
11642        // Request the ActivityManager to kill the process(only for existing packages)
11643        // so that we do not end up in a confused state while the user is still using the older
11644        // version of the application while the new one gets installed.
11645        final long token = Binder.clearCallingIdentity();
11646        try {
11647            IActivityManager am = ActivityManager.getService();
11648            if (am != null) {
11649                try {
11650                    am.killApplication(pkgName, appId, userId, reason);
11651                } catch (RemoteException e) {
11652                }
11653            }
11654        } finally {
11655            Binder.restoreCallingIdentity(token);
11656        }
11657    }
11658
11659    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11660        // Remove the parent package setting
11661        PackageSetting ps = (PackageSetting) pkg.mExtras;
11662        if (ps != null) {
11663            removePackageLI(ps, chatty);
11664        }
11665        // Remove the child package setting
11666        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11667        for (int i = 0; i < childCount; i++) {
11668            PackageParser.Package childPkg = pkg.childPackages.get(i);
11669            ps = (PackageSetting) childPkg.mExtras;
11670            if (ps != null) {
11671                removePackageLI(ps, chatty);
11672            }
11673        }
11674    }
11675
11676    void removePackageLI(PackageSetting ps, boolean chatty) {
11677        if (DEBUG_INSTALL) {
11678            if (chatty)
11679                Log.d(TAG, "Removing package " + ps.name);
11680        }
11681
11682        // writer
11683        synchronized (mPackages) {
11684            mPackages.remove(ps.name);
11685            final PackageParser.Package pkg = ps.pkg;
11686            if (pkg != null) {
11687                cleanPackageDataStructuresLILPw(pkg, chatty);
11688            }
11689        }
11690    }
11691
11692    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11693        if (DEBUG_INSTALL) {
11694            if (chatty)
11695                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11696        }
11697
11698        // writer
11699        synchronized (mPackages) {
11700            // Remove the parent package
11701            mPackages.remove(pkg.applicationInfo.packageName);
11702            cleanPackageDataStructuresLILPw(pkg, chatty);
11703
11704            // Remove the child packages
11705            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11706            for (int i = 0; i < childCount; i++) {
11707                PackageParser.Package childPkg = pkg.childPackages.get(i);
11708                mPackages.remove(childPkg.applicationInfo.packageName);
11709                cleanPackageDataStructuresLILPw(childPkg, chatty);
11710            }
11711        }
11712    }
11713
11714    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11715        int N = pkg.providers.size();
11716        StringBuilder r = null;
11717        int i;
11718        for (i=0; i<N; i++) {
11719            PackageParser.Provider p = pkg.providers.get(i);
11720            mProviders.removeProvider(p);
11721            if (p.info.authority == null) {
11722
11723                /* There was another ContentProvider with this authority when
11724                 * this app was installed so this authority is null,
11725                 * Ignore it as we don't have to unregister the provider.
11726                 */
11727                continue;
11728            }
11729            String names[] = p.info.authority.split(";");
11730            for (int j = 0; j < names.length; j++) {
11731                if (mProvidersByAuthority.get(names[j]) == p) {
11732                    mProvidersByAuthority.remove(names[j]);
11733                    if (DEBUG_REMOVE) {
11734                        if (chatty)
11735                            Log.d(TAG, "Unregistered content provider: " + names[j]
11736                                    + ", className = " + p.info.name + ", isSyncable = "
11737                                    + p.info.isSyncable);
11738                    }
11739                }
11740            }
11741            if (DEBUG_REMOVE && chatty) {
11742                if (r == null) {
11743                    r = new StringBuilder(256);
11744                } else {
11745                    r.append(' ');
11746                }
11747                r.append(p.info.name);
11748            }
11749        }
11750        if (r != null) {
11751            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11752        }
11753
11754        N = pkg.services.size();
11755        r = null;
11756        for (i=0; i<N; i++) {
11757            PackageParser.Service s = pkg.services.get(i);
11758            mServices.removeService(s);
11759            if (chatty) {
11760                if (r == null) {
11761                    r = new StringBuilder(256);
11762                } else {
11763                    r.append(' ');
11764                }
11765                r.append(s.info.name);
11766            }
11767        }
11768        if (r != null) {
11769            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11770        }
11771
11772        N = pkg.receivers.size();
11773        r = null;
11774        for (i=0; i<N; i++) {
11775            PackageParser.Activity a = pkg.receivers.get(i);
11776            mReceivers.removeActivity(a, "receiver");
11777            if (DEBUG_REMOVE && chatty) {
11778                if (r == null) {
11779                    r = new StringBuilder(256);
11780                } else {
11781                    r.append(' ');
11782                }
11783                r.append(a.info.name);
11784            }
11785        }
11786        if (r != null) {
11787            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11788        }
11789
11790        N = pkg.activities.size();
11791        r = null;
11792        for (i=0; i<N; i++) {
11793            PackageParser.Activity a = pkg.activities.get(i);
11794            mActivities.removeActivity(a, "activity");
11795            if (DEBUG_REMOVE && chatty) {
11796                if (r == null) {
11797                    r = new StringBuilder(256);
11798                } else {
11799                    r.append(' ');
11800                }
11801                r.append(a.info.name);
11802            }
11803        }
11804        if (r != null) {
11805            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11806        }
11807
11808        N = pkg.permissions.size();
11809        r = null;
11810        for (i=0; i<N; i++) {
11811            PackageParser.Permission p = pkg.permissions.get(i);
11812            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11813            if (bp == null) {
11814                bp = mSettings.mPermissionTrees.get(p.info.name);
11815            }
11816            if (bp != null && bp.perm == p) {
11817                bp.perm = null;
11818                if (DEBUG_REMOVE && chatty) {
11819                    if (r == null) {
11820                        r = new StringBuilder(256);
11821                    } else {
11822                        r.append(' ');
11823                    }
11824                    r.append(p.info.name);
11825                }
11826            }
11827            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11828                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11829                if (appOpPkgs != null) {
11830                    appOpPkgs.remove(pkg.packageName);
11831                }
11832            }
11833        }
11834        if (r != null) {
11835            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11836        }
11837
11838        N = pkg.requestedPermissions.size();
11839        r = null;
11840        for (i=0; i<N; i++) {
11841            String perm = pkg.requestedPermissions.get(i);
11842            BasePermission bp = mSettings.mPermissions.get(perm);
11843            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11844                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11845                if (appOpPkgs != null) {
11846                    appOpPkgs.remove(pkg.packageName);
11847                    if (appOpPkgs.isEmpty()) {
11848                        mAppOpPermissionPackages.remove(perm);
11849                    }
11850                }
11851            }
11852        }
11853        if (r != null) {
11854            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11855        }
11856
11857        N = pkg.instrumentation.size();
11858        r = null;
11859        for (i=0; i<N; i++) {
11860            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11861            mInstrumentation.remove(a.getComponentName());
11862            if (DEBUG_REMOVE && chatty) {
11863                if (r == null) {
11864                    r = new StringBuilder(256);
11865                } else {
11866                    r.append(' ');
11867                }
11868                r.append(a.info.name);
11869            }
11870        }
11871        if (r != null) {
11872            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11873        }
11874
11875        r = null;
11876        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11877            // Only system apps can hold shared libraries.
11878            if (pkg.libraryNames != null) {
11879                for (i = 0; i < pkg.libraryNames.size(); i++) {
11880                    String name = pkg.libraryNames.get(i);
11881                    if (removeSharedLibraryLPw(name, 0)) {
11882                        if (DEBUG_REMOVE && chatty) {
11883                            if (r == null) {
11884                                r = new StringBuilder(256);
11885                            } else {
11886                                r.append(' ');
11887                            }
11888                            r.append(name);
11889                        }
11890                    }
11891                }
11892            }
11893        }
11894
11895        r = null;
11896
11897        // Any package can hold static shared libraries.
11898        if (pkg.staticSharedLibName != null) {
11899            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11900                if (DEBUG_REMOVE && chatty) {
11901                    if (r == null) {
11902                        r = new StringBuilder(256);
11903                    } else {
11904                        r.append(' ');
11905                    }
11906                    r.append(pkg.staticSharedLibName);
11907                }
11908            }
11909        }
11910
11911        if (r != null) {
11912            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11913        }
11914    }
11915
11916    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11917        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11918            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11919                return true;
11920            }
11921        }
11922        return false;
11923    }
11924
11925    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11926    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11927    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11928
11929    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11930        // Update the parent permissions
11931        updatePermissionsLPw(pkg.packageName, pkg, flags);
11932        // Update the child permissions
11933        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11934        for (int i = 0; i < childCount; i++) {
11935            PackageParser.Package childPkg = pkg.childPackages.get(i);
11936            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11937        }
11938    }
11939
11940    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11941            int flags) {
11942        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11943        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11944    }
11945
11946    private void updatePermissionsLPw(String changingPkg,
11947            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11948        // Make sure there are no dangling permission trees.
11949        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11950        while (it.hasNext()) {
11951            final BasePermission bp = it.next();
11952            if (bp.packageSetting == null) {
11953                // We may not yet have parsed the package, so just see if
11954                // we still know about its settings.
11955                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11956            }
11957            if (bp.packageSetting == null) {
11958                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11959                        + " from package " + bp.sourcePackage);
11960                it.remove();
11961            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11962                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11963                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11964                            + " from package " + bp.sourcePackage);
11965                    flags |= UPDATE_PERMISSIONS_ALL;
11966                    it.remove();
11967                }
11968            }
11969        }
11970
11971        // Make sure all dynamic permissions have been assigned to a package,
11972        // and make sure there are no dangling permissions.
11973        it = mSettings.mPermissions.values().iterator();
11974        while (it.hasNext()) {
11975            final BasePermission bp = it.next();
11976            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11977                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11978                        + bp.name + " pkg=" + bp.sourcePackage
11979                        + " info=" + bp.pendingInfo);
11980                if (bp.packageSetting == null && bp.pendingInfo != null) {
11981                    final BasePermission tree = findPermissionTreeLP(bp.name);
11982                    if (tree != null && tree.perm != null) {
11983                        bp.packageSetting = tree.packageSetting;
11984                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11985                                new PermissionInfo(bp.pendingInfo));
11986                        bp.perm.info.packageName = tree.perm.info.packageName;
11987                        bp.perm.info.name = bp.name;
11988                        bp.uid = tree.uid;
11989                    }
11990                }
11991            }
11992            if (bp.packageSetting == null) {
11993                // We may not yet have parsed the package, so just see if
11994                // we still know about its settings.
11995                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11996            }
11997            if (bp.packageSetting == null) {
11998                Slog.w(TAG, "Removing dangling permission: " + bp.name
11999                        + " from package " + bp.sourcePackage);
12000                it.remove();
12001            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12002                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12003                    Slog.i(TAG, "Removing old permission: " + bp.name
12004                            + " from package " + bp.sourcePackage);
12005                    flags |= UPDATE_PERMISSIONS_ALL;
12006                    it.remove();
12007                }
12008            }
12009        }
12010
12011        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12012        // Now update the permissions for all packages, in particular
12013        // replace the granted permissions of the system packages.
12014        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12015            for (PackageParser.Package pkg : mPackages.values()) {
12016                if (pkg != pkgInfo) {
12017                    // Only replace for packages on requested volume
12018                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12019                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12020                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12021                    grantPermissionsLPw(pkg, replace, changingPkg);
12022                }
12023            }
12024        }
12025
12026        if (pkgInfo != null) {
12027            // Only replace for packages on requested volume
12028            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12029            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12030                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12031            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12032        }
12033        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12034    }
12035
12036    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12037            String packageOfInterest) {
12038        // IMPORTANT: There are two types of permissions: install and runtime.
12039        // Install time permissions are granted when the app is installed to
12040        // all device users and users added in the future. Runtime permissions
12041        // are granted at runtime explicitly to specific users. Normal and signature
12042        // protected permissions are install time permissions. Dangerous permissions
12043        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12044        // otherwise they are runtime permissions. This function does not manage
12045        // runtime permissions except for the case an app targeting Lollipop MR1
12046        // being upgraded to target a newer SDK, in which case dangerous permissions
12047        // are transformed from install time to runtime ones.
12048
12049        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12050        if (ps == null) {
12051            return;
12052        }
12053
12054        PermissionsState permissionsState = ps.getPermissionsState();
12055        PermissionsState origPermissions = permissionsState;
12056
12057        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12058
12059        boolean runtimePermissionsRevoked = false;
12060        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12061
12062        boolean changedInstallPermission = false;
12063
12064        if (replace) {
12065            ps.installPermissionsFixed = false;
12066            if (!ps.isSharedUser()) {
12067                origPermissions = new PermissionsState(permissionsState);
12068                permissionsState.reset();
12069            } else {
12070                // We need to know only about runtime permission changes since the
12071                // calling code always writes the install permissions state but
12072                // the runtime ones are written only if changed. The only cases of
12073                // changed runtime permissions here are promotion of an install to
12074                // runtime and revocation of a runtime from a shared user.
12075                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12076                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12077                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12078                    runtimePermissionsRevoked = true;
12079                }
12080            }
12081        }
12082
12083        permissionsState.setGlobalGids(mGlobalGids);
12084
12085        final int N = pkg.requestedPermissions.size();
12086        for (int i=0; i<N; i++) {
12087            final String name = pkg.requestedPermissions.get(i);
12088            final BasePermission bp = mSettings.mPermissions.get(name);
12089            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12090                    >= Build.VERSION_CODES.M;
12091
12092            if (DEBUG_INSTALL) {
12093                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12094            }
12095
12096            if (bp == null || bp.packageSetting == null) {
12097                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12098                    if (DEBUG_PERMISSIONS) {
12099                        Slog.i(TAG, "Unknown permission " + name
12100                                + " in package " + pkg.packageName);
12101                    }
12102                }
12103                continue;
12104            }
12105
12106
12107            // Limit ephemeral apps to ephemeral allowed permissions.
12108            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12109                if (DEBUG_PERMISSIONS) {
12110                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12111                            + pkg.packageName);
12112                }
12113                continue;
12114            }
12115
12116            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12117                if (DEBUG_PERMISSIONS) {
12118                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12119                            + pkg.packageName);
12120                }
12121                continue;
12122            }
12123
12124            final String perm = bp.name;
12125            boolean allowedSig = false;
12126            int grant = GRANT_DENIED;
12127
12128            // Keep track of app op permissions.
12129            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12130                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12131                if (pkgs == null) {
12132                    pkgs = new ArraySet<>();
12133                    mAppOpPermissionPackages.put(bp.name, pkgs);
12134                }
12135                pkgs.add(pkg.packageName);
12136            }
12137
12138            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12139            switch (level) {
12140                case PermissionInfo.PROTECTION_NORMAL: {
12141                    // For all apps normal permissions are install time ones.
12142                    grant = GRANT_INSTALL;
12143                } break;
12144
12145                case PermissionInfo.PROTECTION_DANGEROUS: {
12146                    // If a permission review is required for legacy apps we represent
12147                    // their permissions as always granted runtime ones since we need
12148                    // to keep the review required permission flag per user while an
12149                    // install permission's state is shared across all users.
12150                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12151                        // For legacy apps dangerous permissions are install time ones.
12152                        grant = GRANT_INSTALL;
12153                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12154                        // For legacy apps that became modern, install becomes runtime.
12155                        grant = GRANT_UPGRADE;
12156                    } else if (mPromoteSystemApps
12157                            && isSystemApp(ps)
12158                            && mExistingSystemPackages.contains(ps.name)) {
12159                        // For legacy system apps, install becomes runtime.
12160                        // We cannot check hasInstallPermission() for system apps since those
12161                        // permissions were granted implicitly and not persisted pre-M.
12162                        grant = GRANT_UPGRADE;
12163                    } else {
12164                        // For modern apps keep runtime permissions unchanged.
12165                        grant = GRANT_RUNTIME;
12166                    }
12167                } break;
12168
12169                case PermissionInfo.PROTECTION_SIGNATURE: {
12170                    // For all apps signature permissions are install time ones.
12171                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12172                    if (allowedSig) {
12173                        grant = GRANT_INSTALL;
12174                    }
12175                } break;
12176            }
12177
12178            if (DEBUG_PERMISSIONS) {
12179                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12180            }
12181
12182            if (grant != GRANT_DENIED) {
12183                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12184                    // If this is an existing, non-system package, then
12185                    // we can't add any new permissions to it.
12186                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12187                        // Except...  if this is a permission that was added
12188                        // to the platform (note: need to only do this when
12189                        // updating the platform).
12190                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12191                            grant = GRANT_DENIED;
12192                        }
12193                    }
12194                }
12195
12196                switch (grant) {
12197                    case GRANT_INSTALL: {
12198                        // Revoke this as runtime permission to handle the case of
12199                        // a runtime permission being downgraded to an install one.
12200                        // Also in permission review mode we keep dangerous permissions
12201                        // for legacy apps
12202                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12203                            if (origPermissions.getRuntimePermissionState(
12204                                    bp.name, userId) != null) {
12205                                // Revoke the runtime permission and clear the flags.
12206                                origPermissions.revokeRuntimePermission(bp, userId);
12207                                origPermissions.updatePermissionFlags(bp, userId,
12208                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12209                                // If we revoked a permission permission, we have to write.
12210                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12211                                        changedRuntimePermissionUserIds, userId);
12212                            }
12213                        }
12214                        // Grant an install permission.
12215                        if (permissionsState.grantInstallPermission(bp) !=
12216                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12217                            changedInstallPermission = true;
12218                        }
12219                    } break;
12220
12221                    case GRANT_RUNTIME: {
12222                        // Grant previously granted runtime permissions.
12223                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12224                            PermissionState permissionState = origPermissions
12225                                    .getRuntimePermissionState(bp.name, userId);
12226                            int flags = permissionState != null
12227                                    ? permissionState.getFlags() : 0;
12228                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12229                                // Don't propagate the permission in a permission review mode if
12230                                // the former was revoked, i.e. marked to not propagate on upgrade.
12231                                // Note that in a permission review mode install permissions are
12232                                // represented as constantly granted runtime ones since we need to
12233                                // keep a per user state associated with the permission. Also the
12234                                // revoke on upgrade flag is no longer applicable and is reset.
12235                                final boolean revokeOnUpgrade = (flags & PackageManager
12236                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12237                                if (revokeOnUpgrade) {
12238                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12239                                    // Since we changed the flags, we have to write.
12240                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12241                                            changedRuntimePermissionUserIds, userId);
12242                                }
12243                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12244                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12245                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12246                                        // If we cannot put the permission as it was,
12247                                        // we have to write.
12248                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12249                                                changedRuntimePermissionUserIds, userId);
12250                                    }
12251                                }
12252
12253                                // If the app supports runtime permissions no need for a review.
12254                                if (mPermissionReviewRequired
12255                                        && appSupportsRuntimePermissions
12256                                        && (flags & PackageManager
12257                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12258                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12259                                    // Since we changed the flags, we have to write.
12260                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12261                                            changedRuntimePermissionUserIds, userId);
12262                                }
12263                            } else if (mPermissionReviewRequired
12264                                    && !appSupportsRuntimePermissions) {
12265                                // For legacy apps that need a permission review, every new
12266                                // runtime permission is granted but it is pending a review.
12267                                // We also need to review only platform defined runtime
12268                                // permissions as these are the only ones the platform knows
12269                                // how to disable the API to simulate revocation as legacy
12270                                // apps don't expect to run with revoked permissions.
12271                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12272                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12273                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12274                                        // We changed the flags, hence have to write.
12275                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12276                                                changedRuntimePermissionUserIds, userId);
12277                                    }
12278                                }
12279                                if (permissionsState.grantRuntimePermission(bp, userId)
12280                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12281                                    // We changed the permission, hence have to write.
12282                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12283                                            changedRuntimePermissionUserIds, userId);
12284                                }
12285                            }
12286                            // Propagate the permission flags.
12287                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12288                        }
12289                    } break;
12290
12291                    case GRANT_UPGRADE: {
12292                        // Grant runtime permissions for a previously held install permission.
12293                        PermissionState permissionState = origPermissions
12294                                .getInstallPermissionState(bp.name);
12295                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12296
12297                        if (origPermissions.revokeInstallPermission(bp)
12298                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12299                            // We will be transferring the permission flags, so clear them.
12300                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12301                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12302                            changedInstallPermission = true;
12303                        }
12304
12305                        // If the permission is not to be promoted to runtime we ignore it and
12306                        // also its other flags as they are not applicable to install permissions.
12307                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12308                            for (int userId : currentUserIds) {
12309                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12310                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12311                                    // Transfer the permission flags.
12312                                    permissionsState.updatePermissionFlags(bp, userId,
12313                                            flags, flags);
12314                                    // If we granted the permission, we have to write.
12315                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12316                                            changedRuntimePermissionUserIds, userId);
12317                                }
12318                            }
12319                        }
12320                    } break;
12321
12322                    default: {
12323                        if (packageOfInterest == null
12324                                || packageOfInterest.equals(pkg.packageName)) {
12325                            if (DEBUG_PERMISSIONS) {
12326                                Slog.i(TAG, "Not granting permission " + perm
12327                                        + " to package " + pkg.packageName
12328                                        + " because it was previously installed without");
12329                            }
12330                        }
12331                    } break;
12332                }
12333            } else {
12334                if (permissionsState.revokeInstallPermission(bp) !=
12335                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12336                    // Also drop the permission flags.
12337                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12338                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12339                    changedInstallPermission = true;
12340                    Slog.i(TAG, "Un-granting permission " + perm
12341                            + " from package " + pkg.packageName
12342                            + " (protectionLevel=" + bp.protectionLevel
12343                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12344                            + ")");
12345                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12346                    // Don't print warning for app op permissions, since it is fine for them
12347                    // not to be granted, there is a UI for the user to decide.
12348                    if (DEBUG_PERMISSIONS
12349                            && (packageOfInterest == null
12350                                    || packageOfInterest.equals(pkg.packageName))) {
12351                        Slog.i(TAG, "Not granting permission " + perm
12352                                + " to package " + pkg.packageName
12353                                + " (protectionLevel=" + bp.protectionLevel
12354                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12355                                + ")");
12356                    }
12357                }
12358            }
12359        }
12360
12361        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12362                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12363            // This is the first that we have heard about this package, so the
12364            // permissions we have now selected are fixed until explicitly
12365            // changed.
12366            ps.installPermissionsFixed = true;
12367        }
12368
12369        // Persist the runtime permissions state for users with changes. If permissions
12370        // were revoked because no app in the shared user declares them we have to
12371        // write synchronously to avoid losing runtime permissions state.
12372        for (int userId : changedRuntimePermissionUserIds) {
12373            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12374        }
12375    }
12376
12377    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12378        boolean allowed = false;
12379        final int NP = PackageParser.NEW_PERMISSIONS.length;
12380        for (int ip=0; ip<NP; ip++) {
12381            final PackageParser.NewPermissionInfo npi
12382                    = PackageParser.NEW_PERMISSIONS[ip];
12383            if (npi.name.equals(perm)
12384                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12385                allowed = true;
12386                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12387                        + pkg.packageName);
12388                break;
12389            }
12390        }
12391        return allowed;
12392    }
12393
12394    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12395            BasePermission bp, PermissionsState origPermissions) {
12396        boolean privilegedPermission = (bp.protectionLevel
12397                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12398        boolean privappPermissionsDisable =
12399                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12400        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12401        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12402        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12403                && !platformPackage && platformPermission) {
12404            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12405                    .getPrivAppPermissions(pkg.packageName);
12406            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12407            if (!whitelisted) {
12408                Slog.w(TAG, "Privileged permission " + perm + " for package "
12409                        + pkg.packageName + " - not in privapp-permissions whitelist");
12410                // Only report violations for apps on system image
12411                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12412                    if (mPrivappPermissionsViolations == null) {
12413                        mPrivappPermissionsViolations = new ArraySet<>();
12414                    }
12415                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12416                }
12417                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12418                    return false;
12419                }
12420            }
12421        }
12422        boolean allowed = (compareSignatures(
12423                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12424                        == PackageManager.SIGNATURE_MATCH)
12425                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12426                        == PackageManager.SIGNATURE_MATCH);
12427        if (!allowed && privilegedPermission) {
12428            if (isSystemApp(pkg)) {
12429                // For updated system applications, a system permission
12430                // is granted only if it had been defined by the original application.
12431                if (pkg.isUpdatedSystemApp()) {
12432                    final PackageSetting sysPs = mSettings
12433                            .getDisabledSystemPkgLPr(pkg.packageName);
12434                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12435                        // If the original was granted this permission, we take
12436                        // that grant decision as read and propagate it to the
12437                        // update.
12438                        if (sysPs.isPrivileged()) {
12439                            allowed = true;
12440                        }
12441                    } else {
12442                        // The system apk may have been updated with an older
12443                        // version of the one on the data partition, but which
12444                        // granted a new system permission that it didn't have
12445                        // before.  In this case we do want to allow the app to
12446                        // now get the new permission if the ancestral apk is
12447                        // privileged to get it.
12448                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12449                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12450                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12451                                    allowed = true;
12452                                    break;
12453                                }
12454                            }
12455                        }
12456                        // Also if a privileged parent package on the system image or any of
12457                        // its children requested a privileged permission, the updated child
12458                        // packages can also get the permission.
12459                        if (pkg.parentPackage != null) {
12460                            final PackageSetting disabledSysParentPs = mSettings
12461                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12462                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12463                                    && disabledSysParentPs.isPrivileged()) {
12464                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12465                                    allowed = true;
12466                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12467                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12468                                    for (int i = 0; i < count; i++) {
12469                                        PackageParser.Package disabledSysChildPkg =
12470                                                disabledSysParentPs.pkg.childPackages.get(i);
12471                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12472                                                perm)) {
12473                                            allowed = true;
12474                                            break;
12475                                        }
12476                                    }
12477                                }
12478                            }
12479                        }
12480                    }
12481                } else {
12482                    allowed = isPrivilegedApp(pkg);
12483                }
12484            }
12485        }
12486        if (!allowed) {
12487            if (!allowed && (bp.protectionLevel
12488                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12489                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12490                // If this was a previously normal/dangerous permission that got moved
12491                // to a system permission as part of the runtime permission redesign, then
12492                // we still want to blindly grant it to old apps.
12493                allowed = true;
12494            }
12495            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12496                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12497                // If this permission is to be granted to the system installer and
12498                // this app is an installer, then it gets the permission.
12499                allowed = true;
12500            }
12501            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12502                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12503                // If this permission is to be granted to the system verifier and
12504                // this app is a verifier, then it gets the permission.
12505                allowed = true;
12506            }
12507            if (!allowed && (bp.protectionLevel
12508                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12509                    && isSystemApp(pkg)) {
12510                // Any pre-installed system app is allowed to get this permission.
12511                allowed = true;
12512            }
12513            if (!allowed && (bp.protectionLevel
12514                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12515                // For development permissions, a development permission
12516                // is granted only if it was already granted.
12517                allowed = origPermissions.hasInstallPermission(perm);
12518            }
12519            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12520                    && pkg.packageName.equals(mSetupWizardPackage)) {
12521                // If this permission is to be granted to the system setup wizard and
12522                // this app is a setup wizard, then it gets the permission.
12523                allowed = true;
12524            }
12525        }
12526        return allowed;
12527    }
12528
12529    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12530        final int permCount = pkg.requestedPermissions.size();
12531        for (int j = 0; j < permCount; j++) {
12532            String requestedPermission = pkg.requestedPermissions.get(j);
12533            if (permission.equals(requestedPermission)) {
12534                return true;
12535            }
12536        }
12537        return false;
12538    }
12539
12540    final class ActivityIntentResolver
12541            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12542        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12543                boolean defaultOnly, int userId) {
12544            if (!sUserManager.exists(userId)) return null;
12545            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12546            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12547        }
12548
12549        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12550                int userId) {
12551            if (!sUserManager.exists(userId)) return null;
12552            mFlags = flags;
12553            return super.queryIntent(intent, resolvedType,
12554                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12555                    userId);
12556        }
12557
12558        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12559                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12560            if (!sUserManager.exists(userId)) return null;
12561            if (packageActivities == null) {
12562                return null;
12563            }
12564            mFlags = flags;
12565            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12566            final int N = packageActivities.size();
12567            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12568                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12569
12570            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12571            for (int i = 0; i < N; ++i) {
12572                intentFilters = packageActivities.get(i).intents;
12573                if (intentFilters != null && intentFilters.size() > 0) {
12574                    PackageParser.ActivityIntentInfo[] array =
12575                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12576                    intentFilters.toArray(array);
12577                    listCut.add(array);
12578                }
12579            }
12580            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12581        }
12582
12583        /**
12584         * Finds a privileged activity that matches the specified activity names.
12585         */
12586        private PackageParser.Activity findMatchingActivity(
12587                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12588            for (PackageParser.Activity sysActivity : activityList) {
12589                if (sysActivity.info.name.equals(activityInfo.name)) {
12590                    return sysActivity;
12591                }
12592                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12593                    return sysActivity;
12594                }
12595                if (sysActivity.info.targetActivity != null) {
12596                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12597                        return sysActivity;
12598                    }
12599                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12600                        return sysActivity;
12601                    }
12602                }
12603            }
12604            return null;
12605        }
12606
12607        public class IterGenerator<E> {
12608            public Iterator<E> generate(ActivityIntentInfo info) {
12609                return null;
12610            }
12611        }
12612
12613        public class ActionIterGenerator extends IterGenerator<String> {
12614            @Override
12615            public Iterator<String> generate(ActivityIntentInfo info) {
12616                return info.actionsIterator();
12617            }
12618        }
12619
12620        public class CategoriesIterGenerator extends IterGenerator<String> {
12621            @Override
12622            public Iterator<String> generate(ActivityIntentInfo info) {
12623                return info.categoriesIterator();
12624            }
12625        }
12626
12627        public class SchemesIterGenerator extends IterGenerator<String> {
12628            @Override
12629            public Iterator<String> generate(ActivityIntentInfo info) {
12630                return info.schemesIterator();
12631            }
12632        }
12633
12634        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12635            @Override
12636            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12637                return info.authoritiesIterator();
12638            }
12639        }
12640
12641        /**
12642         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12643         * MODIFIED. Do not pass in a list that should not be changed.
12644         */
12645        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12646                IterGenerator<T> generator, Iterator<T> searchIterator) {
12647            // loop through the set of actions; every one must be found in the intent filter
12648            while (searchIterator.hasNext()) {
12649                // we must have at least one filter in the list to consider a match
12650                if (intentList.size() == 0) {
12651                    break;
12652                }
12653
12654                final T searchAction = searchIterator.next();
12655
12656                // loop through the set of intent filters
12657                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12658                while (intentIter.hasNext()) {
12659                    final ActivityIntentInfo intentInfo = intentIter.next();
12660                    boolean selectionFound = false;
12661
12662                    // loop through the intent filter's selection criteria; at least one
12663                    // of them must match the searched criteria
12664                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12665                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12666                        final T intentSelection = intentSelectionIter.next();
12667                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12668                            selectionFound = true;
12669                            break;
12670                        }
12671                    }
12672
12673                    // the selection criteria wasn't found in this filter's set; this filter
12674                    // is not a potential match
12675                    if (!selectionFound) {
12676                        intentIter.remove();
12677                    }
12678                }
12679            }
12680        }
12681
12682        private boolean isProtectedAction(ActivityIntentInfo filter) {
12683            final Iterator<String> actionsIter = filter.actionsIterator();
12684            while (actionsIter != null && actionsIter.hasNext()) {
12685                final String filterAction = actionsIter.next();
12686                if (PROTECTED_ACTIONS.contains(filterAction)) {
12687                    return true;
12688                }
12689            }
12690            return false;
12691        }
12692
12693        /**
12694         * Adjusts the priority of the given intent filter according to policy.
12695         * <p>
12696         * <ul>
12697         * <li>The priority for non privileged applications is capped to '0'</li>
12698         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12699         * <li>The priority for unbundled updates to privileged applications is capped to the
12700         *      priority defined on the system partition</li>
12701         * </ul>
12702         * <p>
12703         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12704         * allowed to obtain any priority on any action.
12705         */
12706        private void adjustPriority(
12707                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12708            // nothing to do; priority is fine as-is
12709            if (intent.getPriority() <= 0) {
12710                return;
12711            }
12712
12713            final ActivityInfo activityInfo = intent.activity.info;
12714            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12715
12716            final boolean privilegedApp =
12717                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12718            if (!privilegedApp) {
12719                // non-privileged applications can never define a priority >0
12720                if (DEBUG_FILTERS) {
12721                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12722                            + " package: " + applicationInfo.packageName
12723                            + " activity: " + intent.activity.className
12724                            + " origPrio: " + intent.getPriority());
12725                }
12726                intent.setPriority(0);
12727                return;
12728            }
12729
12730            if (systemActivities == null) {
12731                // the system package is not disabled; we're parsing the system partition
12732                if (isProtectedAction(intent)) {
12733                    if (mDeferProtectedFilters) {
12734                        // We can't deal with these just yet. No component should ever obtain a
12735                        // >0 priority for a protected actions, with ONE exception -- the setup
12736                        // wizard. The setup wizard, however, cannot be known until we're able to
12737                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12738                        // until all intent filters have been processed. Chicken, meet egg.
12739                        // Let the filter temporarily have a high priority and rectify the
12740                        // priorities after all system packages have been scanned.
12741                        mProtectedFilters.add(intent);
12742                        if (DEBUG_FILTERS) {
12743                            Slog.i(TAG, "Protected action; save for later;"
12744                                    + " package: " + applicationInfo.packageName
12745                                    + " activity: " + intent.activity.className
12746                                    + " origPrio: " + intent.getPriority());
12747                        }
12748                        return;
12749                    } else {
12750                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12751                            Slog.i(TAG, "No setup wizard;"
12752                                + " All protected intents capped to priority 0");
12753                        }
12754                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12755                            if (DEBUG_FILTERS) {
12756                                Slog.i(TAG, "Found setup wizard;"
12757                                    + " allow priority " + intent.getPriority() + ";"
12758                                    + " package: " + intent.activity.info.packageName
12759                                    + " activity: " + intent.activity.className
12760                                    + " priority: " + intent.getPriority());
12761                            }
12762                            // setup wizard gets whatever it wants
12763                            return;
12764                        }
12765                        if (DEBUG_FILTERS) {
12766                            Slog.i(TAG, "Protected action; cap priority to 0;"
12767                                    + " package: " + intent.activity.info.packageName
12768                                    + " activity: " + intent.activity.className
12769                                    + " origPrio: " + intent.getPriority());
12770                        }
12771                        intent.setPriority(0);
12772                        return;
12773                    }
12774                }
12775                // privileged apps on the system image get whatever priority they request
12776                return;
12777            }
12778
12779            // privileged app unbundled update ... try to find the same activity
12780            final PackageParser.Activity foundActivity =
12781                    findMatchingActivity(systemActivities, activityInfo);
12782            if (foundActivity == null) {
12783                // this is a new activity; it cannot obtain >0 priority
12784                if (DEBUG_FILTERS) {
12785                    Slog.i(TAG, "New activity; cap priority to 0;"
12786                            + " package: " + applicationInfo.packageName
12787                            + " activity: " + intent.activity.className
12788                            + " origPrio: " + intent.getPriority());
12789                }
12790                intent.setPriority(0);
12791                return;
12792            }
12793
12794            // found activity, now check for filter equivalence
12795
12796            // a shallow copy is enough; we modify the list, not its contents
12797            final List<ActivityIntentInfo> intentListCopy =
12798                    new ArrayList<>(foundActivity.intents);
12799            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12800
12801            // find matching action subsets
12802            final Iterator<String> actionsIterator = intent.actionsIterator();
12803            if (actionsIterator != null) {
12804                getIntentListSubset(
12805                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12806                if (intentListCopy.size() == 0) {
12807                    // no more intents to match; we're not equivalent
12808                    if (DEBUG_FILTERS) {
12809                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12810                                + " package: " + applicationInfo.packageName
12811                                + " activity: " + intent.activity.className
12812                                + " origPrio: " + intent.getPriority());
12813                    }
12814                    intent.setPriority(0);
12815                    return;
12816                }
12817            }
12818
12819            // find matching category subsets
12820            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12821            if (categoriesIterator != null) {
12822                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12823                        categoriesIterator);
12824                if (intentListCopy.size() == 0) {
12825                    // no more intents to match; we're not equivalent
12826                    if (DEBUG_FILTERS) {
12827                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12828                                + " package: " + applicationInfo.packageName
12829                                + " activity: " + intent.activity.className
12830                                + " origPrio: " + intent.getPriority());
12831                    }
12832                    intent.setPriority(0);
12833                    return;
12834                }
12835            }
12836
12837            // find matching schemes subsets
12838            final Iterator<String> schemesIterator = intent.schemesIterator();
12839            if (schemesIterator != null) {
12840                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12841                        schemesIterator);
12842                if (intentListCopy.size() == 0) {
12843                    // no more intents to match; we're not equivalent
12844                    if (DEBUG_FILTERS) {
12845                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12846                                + " package: " + applicationInfo.packageName
12847                                + " activity: " + intent.activity.className
12848                                + " origPrio: " + intent.getPriority());
12849                    }
12850                    intent.setPriority(0);
12851                    return;
12852                }
12853            }
12854
12855            // find matching authorities subsets
12856            final Iterator<IntentFilter.AuthorityEntry>
12857                    authoritiesIterator = intent.authoritiesIterator();
12858            if (authoritiesIterator != null) {
12859                getIntentListSubset(intentListCopy,
12860                        new AuthoritiesIterGenerator(),
12861                        authoritiesIterator);
12862                if (intentListCopy.size() == 0) {
12863                    // no more intents to match; we're not equivalent
12864                    if (DEBUG_FILTERS) {
12865                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12866                                + " package: " + applicationInfo.packageName
12867                                + " activity: " + intent.activity.className
12868                                + " origPrio: " + intent.getPriority());
12869                    }
12870                    intent.setPriority(0);
12871                    return;
12872                }
12873            }
12874
12875            // we found matching filter(s); app gets the max priority of all intents
12876            int cappedPriority = 0;
12877            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12878                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12879            }
12880            if (intent.getPriority() > cappedPriority) {
12881                if (DEBUG_FILTERS) {
12882                    Slog.i(TAG, "Found matching filter(s);"
12883                            + " cap priority to " + cappedPriority + ";"
12884                            + " package: " + applicationInfo.packageName
12885                            + " activity: " + intent.activity.className
12886                            + " origPrio: " + intent.getPriority());
12887                }
12888                intent.setPriority(cappedPriority);
12889                return;
12890            }
12891            // all this for nothing; the requested priority was <= what was on the system
12892        }
12893
12894        public final void addActivity(PackageParser.Activity a, String type) {
12895            mActivities.put(a.getComponentName(), a);
12896            if (DEBUG_SHOW_INFO)
12897                Log.v(
12898                TAG, "  " + type + " " +
12899                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12900            if (DEBUG_SHOW_INFO)
12901                Log.v(TAG, "    Class=" + a.info.name);
12902            final int NI = a.intents.size();
12903            for (int j=0; j<NI; j++) {
12904                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12905                if ("activity".equals(type)) {
12906                    final PackageSetting ps =
12907                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12908                    final List<PackageParser.Activity> systemActivities =
12909                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12910                    adjustPriority(systemActivities, intent);
12911                }
12912                if (DEBUG_SHOW_INFO) {
12913                    Log.v(TAG, "    IntentFilter:");
12914                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12915                }
12916                if (!intent.debugCheck()) {
12917                    Log.w(TAG, "==> For Activity " + a.info.name);
12918                }
12919                addFilter(intent);
12920            }
12921        }
12922
12923        public final void removeActivity(PackageParser.Activity a, String type) {
12924            mActivities.remove(a.getComponentName());
12925            if (DEBUG_SHOW_INFO) {
12926                Log.v(TAG, "  " + type + " "
12927                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12928                                : a.info.name) + ":");
12929                Log.v(TAG, "    Class=" + a.info.name);
12930            }
12931            final int NI = a.intents.size();
12932            for (int j=0; j<NI; j++) {
12933                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12934                if (DEBUG_SHOW_INFO) {
12935                    Log.v(TAG, "    IntentFilter:");
12936                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12937                }
12938                removeFilter(intent);
12939            }
12940        }
12941
12942        @Override
12943        protected boolean allowFilterResult(
12944                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12945            ActivityInfo filterAi = filter.activity.info;
12946            for (int i=dest.size()-1; i>=0; i--) {
12947                ActivityInfo destAi = dest.get(i).activityInfo;
12948                if (destAi.name == filterAi.name
12949                        && destAi.packageName == filterAi.packageName) {
12950                    return false;
12951                }
12952            }
12953            return true;
12954        }
12955
12956        @Override
12957        protected ActivityIntentInfo[] newArray(int size) {
12958            return new ActivityIntentInfo[size];
12959        }
12960
12961        @Override
12962        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12963            if (!sUserManager.exists(userId)) return true;
12964            PackageParser.Package p = filter.activity.owner;
12965            if (p != null) {
12966                PackageSetting ps = (PackageSetting)p.mExtras;
12967                if (ps != null) {
12968                    // System apps are never considered stopped for purposes of
12969                    // filtering, because there may be no way for the user to
12970                    // actually re-launch them.
12971                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12972                            && ps.getStopped(userId);
12973                }
12974            }
12975            return false;
12976        }
12977
12978        @Override
12979        protected boolean isPackageForFilter(String packageName,
12980                PackageParser.ActivityIntentInfo info) {
12981            return packageName.equals(info.activity.owner.packageName);
12982        }
12983
12984        @Override
12985        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12986                int match, int userId) {
12987            if (!sUserManager.exists(userId)) return null;
12988            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12989                return null;
12990            }
12991            final PackageParser.Activity activity = info.activity;
12992            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12993            if (ps == null) {
12994                return null;
12995            }
12996            final PackageUserState userState = ps.readUserState(userId);
12997            ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId);
12998            if (ai == null) {
12999                return null;
13000            }
13001            final boolean matchExplicitlyVisibleOnly =
13002                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13003            final boolean matchVisibleToInstantApp =
13004                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13005            final boolean componentVisible =
13006                    matchVisibleToInstantApp
13007                    && info.isVisibleToInstantApp()
13008                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13009            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13010            // throw out filters that aren't visible to ephemeral apps
13011            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13012                return null;
13013            }
13014            // throw out instant app filters if we're not explicitly requesting them
13015            if (!matchInstantApp && userState.instantApp) {
13016                return null;
13017            }
13018            // throw out instant app filters if updates are available; will trigger
13019            // instant app resolution
13020            if (userState.instantApp && ps.isUpdateAvailable()) {
13021                return null;
13022            }
13023            final ResolveInfo res = new ResolveInfo();
13024            res.activityInfo = ai;
13025            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13026                res.filter = info;
13027            }
13028            if (info != null) {
13029                res.handleAllWebDataURI = info.handleAllWebDataURI();
13030            }
13031            res.priority = info.getPriority();
13032            res.preferredOrder = activity.owner.mPreferredOrder;
13033            //System.out.println("Result: " + res.activityInfo.className +
13034            //                   " = " + res.priority);
13035            res.match = match;
13036            res.isDefault = info.hasDefault;
13037            res.labelRes = info.labelRes;
13038            res.nonLocalizedLabel = info.nonLocalizedLabel;
13039            if (userNeedsBadging(userId)) {
13040                res.noResourceId = true;
13041            } else {
13042                res.icon = info.icon;
13043            }
13044            res.iconResourceId = info.icon;
13045            res.system = res.activityInfo.applicationInfo.isSystemApp();
13046            res.isInstantAppAvailable = userState.instantApp;
13047            return res;
13048        }
13049
13050        @Override
13051        protected void sortResults(List<ResolveInfo> results) {
13052            Collections.sort(results, mResolvePrioritySorter);
13053        }
13054
13055        @Override
13056        protected void dumpFilter(PrintWriter out, String prefix,
13057                PackageParser.ActivityIntentInfo filter) {
13058            out.print(prefix); out.print(
13059                    Integer.toHexString(System.identityHashCode(filter.activity)));
13060                    out.print(' ');
13061                    filter.activity.printComponentShortName(out);
13062                    out.print(" filter ");
13063                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13064        }
13065
13066        @Override
13067        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13068            return filter.activity;
13069        }
13070
13071        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13072            PackageParser.Activity activity = (PackageParser.Activity)label;
13073            out.print(prefix); out.print(
13074                    Integer.toHexString(System.identityHashCode(activity)));
13075                    out.print(' ');
13076                    activity.printComponentShortName(out);
13077            if (count > 1) {
13078                out.print(" ("); out.print(count); out.print(" filters)");
13079            }
13080            out.println();
13081        }
13082
13083        // Keys are String (activity class name), values are Activity.
13084        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13085                = new ArrayMap<ComponentName, PackageParser.Activity>();
13086        private int mFlags;
13087    }
13088
13089    private final class ServiceIntentResolver
13090            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13091        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13092                boolean defaultOnly, int userId) {
13093            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13094            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13095        }
13096
13097        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13098                int userId) {
13099            if (!sUserManager.exists(userId)) return null;
13100            mFlags = flags;
13101            return super.queryIntent(intent, resolvedType,
13102                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13103                    userId);
13104        }
13105
13106        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13107                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13108            if (!sUserManager.exists(userId)) return null;
13109            if (packageServices == null) {
13110                return null;
13111            }
13112            mFlags = flags;
13113            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13114            final int N = packageServices.size();
13115            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13116                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13117
13118            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13119            for (int i = 0; i < N; ++i) {
13120                intentFilters = packageServices.get(i).intents;
13121                if (intentFilters != null && intentFilters.size() > 0) {
13122                    PackageParser.ServiceIntentInfo[] array =
13123                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13124                    intentFilters.toArray(array);
13125                    listCut.add(array);
13126                }
13127            }
13128            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13129        }
13130
13131        public final void addService(PackageParser.Service s) {
13132            mServices.put(s.getComponentName(), s);
13133            if (DEBUG_SHOW_INFO) {
13134                Log.v(TAG, "  "
13135                        + (s.info.nonLocalizedLabel != null
13136                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13137                Log.v(TAG, "    Class=" + s.info.name);
13138            }
13139            final int NI = s.intents.size();
13140            int j;
13141            for (j=0; j<NI; j++) {
13142                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13143                if (DEBUG_SHOW_INFO) {
13144                    Log.v(TAG, "    IntentFilter:");
13145                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13146                }
13147                if (!intent.debugCheck()) {
13148                    Log.w(TAG, "==> For Service " + s.info.name);
13149                }
13150                addFilter(intent);
13151            }
13152        }
13153
13154        public final void removeService(PackageParser.Service s) {
13155            mServices.remove(s.getComponentName());
13156            if (DEBUG_SHOW_INFO) {
13157                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13158                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13159                Log.v(TAG, "    Class=" + s.info.name);
13160            }
13161            final int NI = s.intents.size();
13162            int j;
13163            for (j=0; j<NI; j++) {
13164                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13165                if (DEBUG_SHOW_INFO) {
13166                    Log.v(TAG, "    IntentFilter:");
13167                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13168                }
13169                removeFilter(intent);
13170            }
13171        }
13172
13173        @Override
13174        protected boolean allowFilterResult(
13175                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13176            ServiceInfo filterSi = filter.service.info;
13177            for (int i=dest.size()-1; i>=0; i--) {
13178                ServiceInfo destAi = dest.get(i).serviceInfo;
13179                if (destAi.name == filterSi.name
13180                        && destAi.packageName == filterSi.packageName) {
13181                    return false;
13182                }
13183            }
13184            return true;
13185        }
13186
13187        @Override
13188        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13189            return new PackageParser.ServiceIntentInfo[size];
13190        }
13191
13192        @Override
13193        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13194            if (!sUserManager.exists(userId)) return true;
13195            PackageParser.Package p = filter.service.owner;
13196            if (p != null) {
13197                PackageSetting ps = (PackageSetting)p.mExtras;
13198                if (ps != null) {
13199                    // System apps are never considered stopped for purposes of
13200                    // filtering, because there may be no way for the user to
13201                    // actually re-launch them.
13202                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13203                            && ps.getStopped(userId);
13204                }
13205            }
13206            return false;
13207        }
13208
13209        @Override
13210        protected boolean isPackageForFilter(String packageName,
13211                PackageParser.ServiceIntentInfo info) {
13212            return packageName.equals(info.service.owner.packageName);
13213        }
13214
13215        @Override
13216        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13217                int match, int userId) {
13218            if (!sUserManager.exists(userId)) return null;
13219            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13220            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13221                return null;
13222            }
13223            final PackageParser.Service service = info.service;
13224            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13225            if (ps == null) {
13226                return null;
13227            }
13228            final PackageUserState userState = ps.readUserState(userId);
13229            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13230                    userState, userId);
13231            if (si == null) {
13232                return null;
13233            }
13234            final boolean matchVisibleToInstantApp =
13235                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13236            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13237            // throw out filters that aren't visible to ephemeral apps
13238            if (matchVisibleToInstantApp
13239                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13240                return null;
13241            }
13242            // throw out ephemeral filters if we're not explicitly requesting them
13243            if (!isInstantApp && userState.instantApp) {
13244                return null;
13245            }
13246            // throw out instant app filters if updates are available; will trigger
13247            // instant app resolution
13248            if (userState.instantApp && ps.isUpdateAvailable()) {
13249                return null;
13250            }
13251            final ResolveInfo res = new ResolveInfo();
13252            res.serviceInfo = si;
13253            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13254                res.filter = filter;
13255            }
13256            res.priority = info.getPriority();
13257            res.preferredOrder = service.owner.mPreferredOrder;
13258            res.match = match;
13259            res.isDefault = info.hasDefault;
13260            res.labelRes = info.labelRes;
13261            res.nonLocalizedLabel = info.nonLocalizedLabel;
13262            res.icon = info.icon;
13263            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13264            return res;
13265        }
13266
13267        @Override
13268        protected void sortResults(List<ResolveInfo> results) {
13269            Collections.sort(results, mResolvePrioritySorter);
13270        }
13271
13272        @Override
13273        protected void dumpFilter(PrintWriter out, String prefix,
13274                PackageParser.ServiceIntentInfo filter) {
13275            out.print(prefix); out.print(
13276                    Integer.toHexString(System.identityHashCode(filter.service)));
13277                    out.print(' ');
13278                    filter.service.printComponentShortName(out);
13279                    out.print(" filter ");
13280                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13281        }
13282
13283        @Override
13284        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13285            return filter.service;
13286        }
13287
13288        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13289            PackageParser.Service service = (PackageParser.Service)label;
13290            out.print(prefix); out.print(
13291                    Integer.toHexString(System.identityHashCode(service)));
13292                    out.print(' ');
13293                    service.printComponentShortName(out);
13294            if (count > 1) {
13295                out.print(" ("); out.print(count); out.print(" filters)");
13296            }
13297            out.println();
13298        }
13299
13300//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13301//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13302//            final List<ResolveInfo> retList = Lists.newArrayList();
13303//            while (i.hasNext()) {
13304//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13305//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13306//                    retList.add(resolveInfo);
13307//                }
13308//            }
13309//            return retList;
13310//        }
13311
13312        // Keys are String (activity class name), values are Activity.
13313        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13314                = new ArrayMap<ComponentName, PackageParser.Service>();
13315        private int mFlags;
13316    }
13317
13318    private final class ProviderIntentResolver
13319            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13320        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13321                boolean defaultOnly, int userId) {
13322            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13323            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13324        }
13325
13326        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13327                int userId) {
13328            if (!sUserManager.exists(userId))
13329                return null;
13330            mFlags = flags;
13331            return super.queryIntent(intent, resolvedType,
13332                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13333                    userId);
13334        }
13335
13336        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13337                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13338            if (!sUserManager.exists(userId))
13339                return null;
13340            if (packageProviders == null) {
13341                return null;
13342            }
13343            mFlags = flags;
13344            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13345            final int N = packageProviders.size();
13346            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13347                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13348
13349            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13350            for (int i = 0; i < N; ++i) {
13351                intentFilters = packageProviders.get(i).intents;
13352                if (intentFilters != null && intentFilters.size() > 0) {
13353                    PackageParser.ProviderIntentInfo[] array =
13354                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13355                    intentFilters.toArray(array);
13356                    listCut.add(array);
13357                }
13358            }
13359            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13360        }
13361
13362        public final void addProvider(PackageParser.Provider p) {
13363            if (mProviders.containsKey(p.getComponentName())) {
13364                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13365                return;
13366            }
13367
13368            mProviders.put(p.getComponentName(), p);
13369            if (DEBUG_SHOW_INFO) {
13370                Log.v(TAG, "  "
13371                        + (p.info.nonLocalizedLabel != null
13372                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13373                Log.v(TAG, "    Class=" + p.info.name);
13374            }
13375            final int NI = p.intents.size();
13376            int j;
13377            for (j = 0; j < NI; j++) {
13378                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13379                if (DEBUG_SHOW_INFO) {
13380                    Log.v(TAG, "    IntentFilter:");
13381                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13382                }
13383                if (!intent.debugCheck()) {
13384                    Log.w(TAG, "==> For Provider " + p.info.name);
13385                }
13386                addFilter(intent);
13387            }
13388        }
13389
13390        public final void removeProvider(PackageParser.Provider p) {
13391            mProviders.remove(p.getComponentName());
13392            if (DEBUG_SHOW_INFO) {
13393                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13394                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13395                Log.v(TAG, "    Class=" + p.info.name);
13396            }
13397            final int NI = p.intents.size();
13398            int j;
13399            for (j = 0; j < NI; j++) {
13400                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13401                if (DEBUG_SHOW_INFO) {
13402                    Log.v(TAG, "    IntentFilter:");
13403                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13404                }
13405                removeFilter(intent);
13406            }
13407        }
13408
13409        @Override
13410        protected boolean allowFilterResult(
13411                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13412            ProviderInfo filterPi = filter.provider.info;
13413            for (int i = dest.size() - 1; i >= 0; i--) {
13414                ProviderInfo destPi = dest.get(i).providerInfo;
13415                if (destPi.name == filterPi.name
13416                        && destPi.packageName == filterPi.packageName) {
13417                    return false;
13418                }
13419            }
13420            return true;
13421        }
13422
13423        @Override
13424        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13425            return new PackageParser.ProviderIntentInfo[size];
13426        }
13427
13428        @Override
13429        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13430            if (!sUserManager.exists(userId))
13431                return true;
13432            PackageParser.Package p = filter.provider.owner;
13433            if (p != null) {
13434                PackageSetting ps = (PackageSetting) p.mExtras;
13435                if (ps != null) {
13436                    // System apps are never considered stopped for purposes of
13437                    // filtering, because there may be no way for the user to
13438                    // actually re-launch them.
13439                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13440                            && ps.getStopped(userId);
13441                }
13442            }
13443            return false;
13444        }
13445
13446        @Override
13447        protected boolean isPackageForFilter(String packageName,
13448                PackageParser.ProviderIntentInfo info) {
13449            return packageName.equals(info.provider.owner.packageName);
13450        }
13451
13452        @Override
13453        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13454                int match, int userId) {
13455            if (!sUserManager.exists(userId))
13456                return null;
13457            final PackageParser.ProviderIntentInfo info = filter;
13458            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13459                return null;
13460            }
13461            final PackageParser.Provider provider = info.provider;
13462            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13463            if (ps == null) {
13464                return null;
13465            }
13466            final PackageUserState userState = ps.readUserState(userId);
13467            final boolean matchVisibleToInstantApp =
13468                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13469            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13470            // throw out filters that aren't visible to instant applications
13471            if (matchVisibleToInstantApp
13472                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13473                return null;
13474            }
13475            // throw out instant application filters if we're not explicitly requesting them
13476            if (!isInstantApp && userState.instantApp) {
13477                return null;
13478            }
13479            // throw out instant application filters if updates are available; will trigger
13480            // instant application resolution
13481            if (userState.instantApp && ps.isUpdateAvailable()) {
13482                return null;
13483            }
13484            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13485                    userState, userId);
13486            if (pi == null) {
13487                return null;
13488            }
13489            final ResolveInfo res = new ResolveInfo();
13490            res.providerInfo = pi;
13491            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13492                res.filter = filter;
13493            }
13494            res.priority = info.getPriority();
13495            res.preferredOrder = provider.owner.mPreferredOrder;
13496            res.match = match;
13497            res.isDefault = info.hasDefault;
13498            res.labelRes = info.labelRes;
13499            res.nonLocalizedLabel = info.nonLocalizedLabel;
13500            res.icon = info.icon;
13501            res.system = res.providerInfo.applicationInfo.isSystemApp();
13502            return res;
13503        }
13504
13505        @Override
13506        protected void sortResults(List<ResolveInfo> results) {
13507            Collections.sort(results, mResolvePrioritySorter);
13508        }
13509
13510        @Override
13511        protected void dumpFilter(PrintWriter out, String prefix,
13512                PackageParser.ProviderIntentInfo filter) {
13513            out.print(prefix);
13514            out.print(
13515                    Integer.toHexString(System.identityHashCode(filter.provider)));
13516            out.print(' ');
13517            filter.provider.printComponentShortName(out);
13518            out.print(" filter ");
13519            out.println(Integer.toHexString(System.identityHashCode(filter)));
13520        }
13521
13522        @Override
13523        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13524            return filter.provider;
13525        }
13526
13527        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13528            PackageParser.Provider provider = (PackageParser.Provider)label;
13529            out.print(prefix); out.print(
13530                    Integer.toHexString(System.identityHashCode(provider)));
13531                    out.print(' ');
13532                    provider.printComponentShortName(out);
13533            if (count > 1) {
13534                out.print(" ("); out.print(count); out.print(" filters)");
13535            }
13536            out.println();
13537        }
13538
13539        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13540                = new ArrayMap<ComponentName, PackageParser.Provider>();
13541        private int mFlags;
13542    }
13543
13544    static final class EphemeralIntentResolver
13545            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13546        /**
13547         * The result that has the highest defined order. Ordering applies on a
13548         * per-package basis. Mapping is from package name to Pair of order and
13549         * EphemeralResolveInfo.
13550         * <p>
13551         * NOTE: This is implemented as a field variable for convenience and efficiency.
13552         * By having a field variable, we're able to track filter ordering as soon as
13553         * a non-zero order is defined. Otherwise, multiple loops across the result set
13554         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13555         * this needs to be contained entirely within {@link #filterResults}.
13556         */
13557        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13558
13559        @Override
13560        protected AuxiliaryResolveInfo[] newArray(int size) {
13561            return new AuxiliaryResolveInfo[size];
13562        }
13563
13564        @Override
13565        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13566            return true;
13567        }
13568
13569        @Override
13570        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13571                int userId) {
13572            if (!sUserManager.exists(userId)) {
13573                return null;
13574            }
13575            final String packageName = responseObj.resolveInfo.getPackageName();
13576            final Integer order = responseObj.getOrder();
13577            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13578                    mOrderResult.get(packageName);
13579            // ordering is enabled and this item's order isn't high enough
13580            if (lastOrderResult != null && lastOrderResult.first >= order) {
13581                return null;
13582            }
13583            final InstantAppResolveInfo res = responseObj.resolveInfo;
13584            if (order > 0) {
13585                // non-zero order, enable ordering
13586                mOrderResult.put(packageName, new Pair<>(order, res));
13587            }
13588            return responseObj;
13589        }
13590
13591        @Override
13592        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13593            // only do work if ordering is enabled [most of the time it won't be]
13594            if (mOrderResult.size() == 0) {
13595                return;
13596            }
13597            int resultSize = results.size();
13598            for (int i = 0; i < resultSize; i++) {
13599                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13600                final String packageName = info.getPackageName();
13601                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13602                if (savedInfo == null) {
13603                    // package doesn't having ordering
13604                    continue;
13605                }
13606                if (savedInfo.second == info) {
13607                    // circled back to the highest ordered item; remove from order list
13608                    mOrderResult.remove(savedInfo);
13609                    if (mOrderResult.size() == 0) {
13610                        // no more ordered items
13611                        break;
13612                    }
13613                    continue;
13614                }
13615                // item has a worse order, remove it from the result list
13616                results.remove(i);
13617                resultSize--;
13618                i--;
13619            }
13620        }
13621    }
13622
13623    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13624            new Comparator<ResolveInfo>() {
13625        public int compare(ResolveInfo r1, ResolveInfo r2) {
13626            int v1 = r1.priority;
13627            int v2 = r2.priority;
13628            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13629            if (v1 != v2) {
13630                return (v1 > v2) ? -1 : 1;
13631            }
13632            v1 = r1.preferredOrder;
13633            v2 = r2.preferredOrder;
13634            if (v1 != v2) {
13635                return (v1 > v2) ? -1 : 1;
13636            }
13637            if (r1.isDefault != r2.isDefault) {
13638                return r1.isDefault ? -1 : 1;
13639            }
13640            v1 = r1.match;
13641            v2 = r2.match;
13642            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13643            if (v1 != v2) {
13644                return (v1 > v2) ? -1 : 1;
13645            }
13646            if (r1.system != r2.system) {
13647                return r1.system ? -1 : 1;
13648            }
13649            if (r1.activityInfo != null) {
13650                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13651            }
13652            if (r1.serviceInfo != null) {
13653                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13654            }
13655            if (r1.providerInfo != null) {
13656                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13657            }
13658            return 0;
13659        }
13660    };
13661
13662    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13663            new Comparator<ProviderInfo>() {
13664        public int compare(ProviderInfo p1, ProviderInfo p2) {
13665            final int v1 = p1.initOrder;
13666            final int v2 = p2.initOrder;
13667            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13668        }
13669    };
13670
13671    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13672            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13673            final int[] userIds) {
13674        mHandler.post(new Runnable() {
13675            @Override
13676            public void run() {
13677                try {
13678                    final IActivityManager am = ActivityManager.getService();
13679                    if (am == null) return;
13680                    final int[] resolvedUserIds;
13681                    if (userIds == null) {
13682                        resolvedUserIds = am.getRunningUserIds();
13683                    } else {
13684                        resolvedUserIds = userIds;
13685                    }
13686                    for (int id : resolvedUserIds) {
13687                        final Intent intent = new Intent(action,
13688                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13689                        if (extras != null) {
13690                            intent.putExtras(extras);
13691                        }
13692                        if (targetPkg != null) {
13693                            intent.setPackage(targetPkg);
13694                        }
13695                        // Modify the UID when posting to other users
13696                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13697                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13698                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13699                            intent.putExtra(Intent.EXTRA_UID, uid);
13700                        }
13701                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13702                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13703                        if (DEBUG_BROADCASTS) {
13704                            RuntimeException here = new RuntimeException("here");
13705                            here.fillInStackTrace();
13706                            Slog.d(TAG, "Sending to user " + id + ": "
13707                                    + intent.toShortString(false, true, false, false)
13708                                    + " " + intent.getExtras(), here);
13709                        }
13710                        am.broadcastIntent(null, intent, null, finishedReceiver,
13711                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13712                                null, finishedReceiver != null, false, id);
13713                    }
13714                } catch (RemoteException ex) {
13715                }
13716            }
13717        });
13718    }
13719
13720    /**
13721     * Check if the external storage media is available. This is true if there
13722     * is a mounted external storage medium or if the external storage is
13723     * emulated.
13724     */
13725    private boolean isExternalMediaAvailable() {
13726        return mMediaMounted || Environment.isExternalStorageEmulated();
13727    }
13728
13729    @Override
13730    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13731        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13732            return null;
13733        }
13734        // writer
13735        synchronized (mPackages) {
13736            if (!isExternalMediaAvailable()) {
13737                // If the external storage is no longer mounted at this point,
13738                // the caller may not have been able to delete all of this
13739                // packages files and can not delete any more.  Bail.
13740                return null;
13741            }
13742            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13743            if (lastPackage != null) {
13744                pkgs.remove(lastPackage);
13745            }
13746            if (pkgs.size() > 0) {
13747                return pkgs.get(0);
13748            }
13749        }
13750        return null;
13751    }
13752
13753    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13754        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13755                userId, andCode ? 1 : 0, packageName);
13756        if (mSystemReady) {
13757            msg.sendToTarget();
13758        } else {
13759            if (mPostSystemReadyMessages == null) {
13760                mPostSystemReadyMessages = new ArrayList<>();
13761            }
13762            mPostSystemReadyMessages.add(msg);
13763        }
13764    }
13765
13766    void startCleaningPackages() {
13767        // reader
13768        if (!isExternalMediaAvailable()) {
13769            return;
13770        }
13771        synchronized (mPackages) {
13772            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13773                return;
13774            }
13775        }
13776        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13777        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13778        IActivityManager am = ActivityManager.getService();
13779        if (am != null) {
13780            int dcsUid = -1;
13781            synchronized (mPackages) {
13782                if (!mDefaultContainerWhitelisted) {
13783                    mDefaultContainerWhitelisted = true;
13784                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13785                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13786                }
13787            }
13788            try {
13789                if (dcsUid > 0) {
13790                    am.backgroundWhitelistUid(dcsUid);
13791                }
13792                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13793                        UserHandle.USER_SYSTEM);
13794            } catch (RemoteException e) {
13795            }
13796        }
13797    }
13798
13799    @Override
13800    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13801            int installFlags, String installerPackageName, int userId) {
13802        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13803
13804        final int callingUid = Binder.getCallingUid();
13805        enforceCrossUserPermission(callingUid, userId,
13806                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13807
13808        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13809            try {
13810                if (observer != null) {
13811                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13812                }
13813            } catch (RemoteException re) {
13814            }
13815            return;
13816        }
13817
13818        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13819            installFlags |= PackageManager.INSTALL_FROM_ADB;
13820
13821        } else {
13822            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13823            // about installerPackageName.
13824
13825            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13826            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13827        }
13828
13829        UserHandle user;
13830        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13831            user = UserHandle.ALL;
13832        } else {
13833            user = new UserHandle(userId);
13834        }
13835
13836        // Only system components can circumvent runtime permissions when installing.
13837        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13838                && mContext.checkCallingOrSelfPermission(Manifest.permission
13839                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13840            throw new SecurityException("You need the "
13841                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13842                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13843        }
13844
13845        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13846                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13847            throw new IllegalArgumentException(
13848                    "New installs into ASEC containers no longer supported");
13849        }
13850
13851        final File originFile = new File(originPath);
13852        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13853
13854        final Message msg = mHandler.obtainMessage(INIT_COPY);
13855        final VerificationInfo verificationInfo = new VerificationInfo(
13856                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13857        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13858                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13859                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13860                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13861        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13862        msg.obj = params;
13863
13864        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13865                System.identityHashCode(msg.obj));
13866        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13867                System.identityHashCode(msg.obj));
13868
13869        mHandler.sendMessage(msg);
13870    }
13871
13872
13873    /**
13874     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13875     * it is acting on behalf on an enterprise or the user).
13876     *
13877     * Note that the ordering of the conditionals in this method is important. The checks we perform
13878     * are as follows, in this order:
13879     *
13880     * 1) If the install is being performed by a system app, we can trust the app to have set the
13881     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13882     *    what it is.
13883     * 2) If the install is being performed by a device or profile owner app, the install reason
13884     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13885     *    set the install reason correctly. If the app targets an older SDK version where install
13886     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13887     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13888     * 3) In all other cases, the install is being performed by a regular app that is neither part
13889     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13890     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13891     *    set to enterprise policy and if so, change it to unknown instead.
13892     */
13893    private int fixUpInstallReason(String installerPackageName, int installerUid,
13894            int installReason) {
13895        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13896                == PERMISSION_GRANTED) {
13897            // If the install is being performed by a system app, we trust that app to have set the
13898            // install reason correctly.
13899            return installReason;
13900        }
13901
13902        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13903            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13904        if (dpm != null) {
13905            ComponentName owner = null;
13906            try {
13907                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13908                if (owner == null) {
13909                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13910                }
13911            } catch (RemoteException e) {
13912            }
13913            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13914                // If the install is being performed by a device or profile owner, the install
13915                // reason should be enterprise policy.
13916                return PackageManager.INSTALL_REASON_POLICY;
13917            }
13918        }
13919
13920        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13921            // If the install is being performed by a regular app (i.e. neither system app nor
13922            // device or profile owner), we have no reason to believe that the app is acting on
13923            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13924            // change it to unknown instead.
13925            return PackageManager.INSTALL_REASON_UNKNOWN;
13926        }
13927
13928        // If the install is being performed by a regular app and the install reason was set to any
13929        // value but enterprise policy, leave the install reason unchanged.
13930        return installReason;
13931    }
13932
13933    void installStage(String packageName, File stagedDir, String stagedCid,
13934            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13935            String installerPackageName, int installerUid, UserHandle user,
13936            Certificate[][] certificates) {
13937        if (DEBUG_EPHEMERAL) {
13938            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13939                Slog.d(TAG, "Ephemeral install of " + packageName);
13940            }
13941        }
13942        final VerificationInfo verificationInfo = new VerificationInfo(
13943                sessionParams.originatingUri, sessionParams.referrerUri,
13944                sessionParams.originatingUid, installerUid);
13945
13946        final OriginInfo origin;
13947        if (stagedDir != null) {
13948            origin = OriginInfo.fromStagedFile(stagedDir);
13949        } else {
13950            origin = OriginInfo.fromStagedContainer(stagedCid);
13951        }
13952
13953        final Message msg = mHandler.obtainMessage(INIT_COPY);
13954        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13955                sessionParams.installReason);
13956        final InstallParams params = new InstallParams(origin, null, observer,
13957                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13958                verificationInfo, user, sessionParams.abiOverride,
13959                sessionParams.grantedRuntimePermissions, certificates, installReason);
13960        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13961        msg.obj = params;
13962
13963        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13964                System.identityHashCode(msg.obj));
13965        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13966                System.identityHashCode(msg.obj));
13967
13968        mHandler.sendMessage(msg);
13969    }
13970
13971    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13972            int userId) {
13973        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13974        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13975
13976        // Send a session commit broadcast
13977        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13978        info.installReason = pkgSetting.getInstallReason(userId);
13979        info.appPackageName = packageName;
13980        sendSessionCommitBroadcast(info, userId);
13981    }
13982
13983    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
13984        if (ArrayUtils.isEmpty(userIds)) {
13985            return;
13986        }
13987        Bundle extras = new Bundle(1);
13988        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13989        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13990
13991        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13992                packageName, extras, 0, null, null, userIds);
13993        if (isSystem) {
13994            mHandler.post(() -> {
13995                        for (int userId : userIds) {
13996                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13997                        }
13998                    }
13999            );
14000        }
14001    }
14002
14003    /**
14004     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14005     * automatically without needing an explicit launch.
14006     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14007     */
14008    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14009        // If user is not running, the app didn't miss any broadcast
14010        if (!mUserManagerInternal.isUserRunning(userId)) {
14011            return;
14012        }
14013        final IActivityManager am = ActivityManager.getService();
14014        try {
14015            // Deliver LOCKED_BOOT_COMPLETED first
14016            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14017                    .setPackage(packageName);
14018            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14019            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14020                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14021
14022            // Deliver BOOT_COMPLETED only if user is unlocked
14023            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14024                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14025                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14026                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14027            }
14028        } catch (RemoteException e) {
14029            throw e.rethrowFromSystemServer();
14030        }
14031    }
14032
14033    @Override
14034    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14035            int userId) {
14036        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14037        PackageSetting pkgSetting;
14038        final int uid = Binder.getCallingUid();
14039        enforceCrossUserPermission(uid, userId,
14040                true /* requireFullPermission */, true /* checkShell */,
14041                "setApplicationHiddenSetting for user " + userId);
14042
14043        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14044            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14045            return false;
14046        }
14047
14048        long callingId = Binder.clearCallingIdentity();
14049        try {
14050            boolean sendAdded = false;
14051            boolean sendRemoved = false;
14052            // writer
14053            synchronized (mPackages) {
14054                pkgSetting = mSettings.mPackages.get(packageName);
14055                if (pkgSetting == null) {
14056                    return false;
14057                }
14058                // Do not allow "android" is being disabled
14059                if ("android".equals(packageName)) {
14060                    Slog.w(TAG, "Cannot hide package: android");
14061                    return false;
14062                }
14063                // Cannot hide static shared libs as they are considered
14064                // a part of the using app (emulating static linking). Also
14065                // static libs are installed always on internal storage.
14066                PackageParser.Package pkg = mPackages.get(packageName);
14067                if (pkg != null && pkg.staticSharedLibName != null) {
14068                    Slog.w(TAG, "Cannot hide package: " + packageName
14069                            + " providing static shared library: "
14070                            + pkg.staticSharedLibName);
14071                    return false;
14072                }
14073                // Only allow protected packages to hide themselves.
14074                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
14075                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14076                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14077                    return false;
14078                }
14079
14080                if (pkgSetting.getHidden(userId) != hidden) {
14081                    pkgSetting.setHidden(hidden, userId);
14082                    mSettings.writePackageRestrictionsLPr(userId);
14083                    if (hidden) {
14084                        sendRemoved = true;
14085                    } else {
14086                        sendAdded = true;
14087                    }
14088                }
14089            }
14090            if (sendAdded) {
14091                sendPackageAddedForUser(packageName, pkgSetting, userId);
14092                return true;
14093            }
14094            if (sendRemoved) {
14095                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14096                        "hiding pkg");
14097                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14098                return true;
14099            }
14100        } finally {
14101            Binder.restoreCallingIdentity(callingId);
14102        }
14103        return false;
14104    }
14105
14106    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14107            int userId) {
14108        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14109        info.removedPackage = packageName;
14110        info.installerPackageName = pkgSetting.installerPackageName;
14111        info.removedUsers = new int[] {userId};
14112        info.broadcastUsers = new int[] {userId};
14113        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14114        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14115    }
14116
14117    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14118        if (pkgList.length > 0) {
14119            Bundle extras = new Bundle(1);
14120            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14121
14122            sendPackageBroadcast(
14123                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14124                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14125                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14126                    new int[] {userId});
14127        }
14128    }
14129
14130    /**
14131     * Returns true if application is not found or there was an error. Otherwise it returns
14132     * the hidden state of the package for the given user.
14133     */
14134    @Override
14135    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14136        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14137        enforceCrossUserPermission(Binder.getCallingUid(), userId,
14138                true /* requireFullPermission */, false /* checkShell */,
14139                "getApplicationHidden for user " + userId);
14140        PackageSetting pkgSetting;
14141        long callingId = Binder.clearCallingIdentity();
14142        try {
14143            // writer
14144            synchronized (mPackages) {
14145                pkgSetting = mSettings.mPackages.get(packageName);
14146                if (pkgSetting == null) {
14147                    return true;
14148                }
14149                return pkgSetting.getHidden(userId);
14150            }
14151        } finally {
14152            Binder.restoreCallingIdentity(callingId);
14153        }
14154    }
14155
14156    /**
14157     * @hide
14158     */
14159    @Override
14160    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14161            int installReason) {
14162        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14163                null);
14164        PackageSetting pkgSetting;
14165        final int uid = Binder.getCallingUid();
14166        enforceCrossUserPermission(uid, userId,
14167                true /* requireFullPermission */, true /* checkShell */,
14168                "installExistingPackage for user " + userId);
14169        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14170            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14171        }
14172
14173        long callingId = Binder.clearCallingIdentity();
14174        try {
14175            boolean installed = false;
14176            final boolean instantApp =
14177                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14178            final boolean fullApp =
14179                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14180
14181            // writer
14182            synchronized (mPackages) {
14183                pkgSetting = mSettings.mPackages.get(packageName);
14184                if (pkgSetting == null) {
14185                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14186                }
14187                if (!pkgSetting.getInstalled(userId)) {
14188                    pkgSetting.setInstalled(true, userId);
14189                    pkgSetting.setHidden(false, userId);
14190                    pkgSetting.setInstallReason(installReason, userId);
14191                    mSettings.writePackageRestrictionsLPr(userId);
14192                    mSettings.writeKernelMappingLPr(pkgSetting);
14193                    installed = true;
14194                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14195                    // upgrade app from instant to full; we don't allow app downgrade
14196                    installed = true;
14197                }
14198                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14199            }
14200
14201            if (installed) {
14202                if (pkgSetting.pkg != null) {
14203                    synchronized (mInstallLock) {
14204                        // We don't need to freeze for a brand new install
14205                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14206                    }
14207                }
14208                sendPackageAddedForUser(packageName, pkgSetting, userId);
14209                synchronized (mPackages) {
14210                    updateSequenceNumberLP(packageName, new int[]{ userId });
14211                }
14212            }
14213        } finally {
14214            Binder.restoreCallingIdentity(callingId);
14215        }
14216
14217        return PackageManager.INSTALL_SUCCEEDED;
14218    }
14219
14220    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14221            boolean instantApp, boolean fullApp) {
14222        // no state specified; do nothing
14223        if (!instantApp && !fullApp) {
14224            return;
14225        }
14226        if (userId != UserHandle.USER_ALL) {
14227            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14228                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14229            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14230                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14231            }
14232        } else {
14233            for (int currentUserId : sUserManager.getUserIds()) {
14234                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14235                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14236                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14237                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14238                }
14239            }
14240        }
14241    }
14242
14243    boolean isUserRestricted(int userId, String restrictionKey) {
14244        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14245        if (restrictions.getBoolean(restrictionKey, false)) {
14246            Log.w(TAG, "User is restricted: " + restrictionKey);
14247            return true;
14248        }
14249        return false;
14250    }
14251
14252    @Override
14253    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14254            int userId) {
14255        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14256        enforceCrossUserPermission(Binder.getCallingUid(), userId,
14257                true /* requireFullPermission */, true /* checkShell */,
14258                "setPackagesSuspended for user " + userId);
14259
14260        if (ArrayUtils.isEmpty(packageNames)) {
14261            return packageNames;
14262        }
14263
14264        // List of package names for whom the suspended state has changed.
14265        List<String> changedPackages = new ArrayList<>(packageNames.length);
14266        // List of package names for whom the suspended state is not set as requested in this
14267        // method.
14268        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14269        long callingId = Binder.clearCallingIdentity();
14270        try {
14271            for (int i = 0; i < packageNames.length; i++) {
14272                String packageName = packageNames[i];
14273                boolean changed = false;
14274                final int appId;
14275                synchronized (mPackages) {
14276                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14277                    if (pkgSetting == null) {
14278                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14279                                + "\". Skipping suspending/un-suspending.");
14280                        unactionedPackages.add(packageName);
14281                        continue;
14282                    }
14283                    appId = pkgSetting.appId;
14284                    if (pkgSetting.getSuspended(userId) != suspended) {
14285                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14286                            unactionedPackages.add(packageName);
14287                            continue;
14288                        }
14289                        pkgSetting.setSuspended(suspended, userId);
14290                        mSettings.writePackageRestrictionsLPr(userId);
14291                        changed = true;
14292                        changedPackages.add(packageName);
14293                    }
14294                }
14295
14296                if (changed && suspended) {
14297                    killApplication(packageName, UserHandle.getUid(userId, appId),
14298                            "suspending package");
14299                }
14300            }
14301        } finally {
14302            Binder.restoreCallingIdentity(callingId);
14303        }
14304
14305        if (!changedPackages.isEmpty()) {
14306            sendPackagesSuspendedForUser(changedPackages.toArray(
14307                    new String[changedPackages.size()]), userId, suspended);
14308        }
14309
14310        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14311    }
14312
14313    @Override
14314    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14315        final int callingUid = Binder.getCallingUid();
14316        enforceCrossUserPermission(callingUid, userId,
14317                true /* requireFullPermission */, false /* checkShell */,
14318                "isPackageSuspendedForUser for user " + userId);
14319        synchronized (mPackages) {
14320            final PackageSetting ps = mSettings.mPackages.get(packageName);
14321            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14322                throw new IllegalArgumentException("Unknown target package: " + packageName);
14323            }
14324            return ps.getSuspended(userId);
14325        }
14326    }
14327
14328    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14329        if (isPackageDeviceAdmin(packageName, userId)) {
14330            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14331                    + "\": has an active device admin");
14332            return false;
14333        }
14334
14335        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14336        if (packageName.equals(activeLauncherPackageName)) {
14337            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14338                    + "\": contains the active launcher");
14339            return false;
14340        }
14341
14342        if (packageName.equals(mRequiredInstallerPackage)) {
14343            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14344                    + "\": required for package installation");
14345            return false;
14346        }
14347
14348        if (packageName.equals(mRequiredUninstallerPackage)) {
14349            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14350                    + "\": required for package uninstallation");
14351            return false;
14352        }
14353
14354        if (packageName.equals(mRequiredVerifierPackage)) {
14355            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14356                    + "\": required for package verification");
14357            return false;
14358        }
14359
14360        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14361            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14362                    + "\": is the default dialer");
14363            return false;
14364        }
14365
14366        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14367            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14368                    + "\": protected package");
14369            return false;
14370        }
14371
14372        // Cannot suspend static shared libs as they are considered
14373        // a part of the using app (emulating static linking). Also
14374        // static libs are installed always on internal storage.
14375        PackageParser.Package pkg = mPackages.get(packageName);
14376        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14377            Slog.w(TAG, "Cannot suspend package: " + packageName
14378                    + " providing static shared library: "
14379                    + pkg.staticSharedLibName);
14380            return false;
14381        }
14382
14383        return true;
14384    }
14385
14386    private String getActiveLauncherPackageName(int userId) {
14387        Intent intent = new Intent(Intent.ACTION_MAIN);
14388        intent.addCategory(Intent.CATEGORY_HOME);
14389        ResolveInfo resolveInfo = resolveIntent(
14390                intent,
14391                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14392                PackageManager.MATCH_DEFAULT_ONLY,
14393                userId);
14394
14395        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14396    }
14397
14398    private String getDefaultDialerPackageName(int userId) {
14399        synchronized (mPackages) {
14400            return mSettings.getDefaultDialerPackageNameLPw(userId);
14401        }
14402    }
14403
14404    @Override
14405    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14406        mContext.enforceCallingOrSelfPermission(
14407                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14408                "Only package verification agents can verify applications");
14409
14410        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14411        final PackageVerificationResponse response = new PackageVerificationResponse(
14412                verificationCode, Binder.getCallingUid());
14413        msg.arg1 = id;
14414        msg.obj = response;
14415        mHandler.sendMessage(msg);
14416    }
14417
14418    @Override
14419    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14420            long millisecondsToDelay) {
14421        mContext.enforceCallingOrSelfPermission(
14422                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14423                "Only package verification agents can extend verification timeouts");
14424
14425        final PackageVerificationState state = mPendingVerification.get(id);
14426        final PackageVerificationResponse response = new PackageVerificationResponse(
14427                verificationCodeAtTimeout, Binder.getCallingUid());
14428
14429        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14430            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14431        }
14432        if (millisecondsToDelay < 0) {
14433            millisecondsToDelay = 0;
14434        }
14435        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14436                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14437            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14438        }
14439
14440        if ((state != null) && !state.timeoutExtended()) {
14441            state.extendTimeout();
14442
14443            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14444            msg.arg1 = id;
14445            msg.obj = response;
14446            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14447        }
14448    }
14449
14450    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14451            int verificationCode, UserHandle user) {
14452        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14453        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14454        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14455        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14456        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14457
14458        mContext.sendBroadcastAsUser(intent, user,
14459                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14460    }
14461
14462    private ComponentName matchComponentForVerifier(String packageName,
14463            List<ResolveInfo> receivers) {
14464        ActivityInfo targetReceiver = null;
14465
14466        final int NR = receivers.size();
14467        for (int i = 0; i < NR; i++) {
14468            final ResolveInfo info = receivers.get(i);
14469            if (info.activityInfo == null) {
14470                continue;
14471            }
14472
14473            if (packageName.equals(info.activityInfo.packageName)) {
14474                targetReceiver = info.activityInfo;
14475                break;
14476            }
14477        }
14478
14479        if (targetReceiver == null) {
14480            return null;
14481        }
14482
14483        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14484    }
14485
14486    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14487            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14488        if (pkgInfo.verifiers.length == 0) {
14489            return null;
14490        }
14491
14492        final int N = pkgInfo.verifiers.length;
14493        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14494        for (int i = 0; i < N; i++) {
14495            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14496
14497            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14498                    receivers);
14499            if (comp == null) {
14500                continue;
14501            }
14502
14503            final int verifierUid = getUidForVerifier(verifierInfo);
14504            if (verifierUid == -1) {
14505                continue;
14506            }
14507
14508            if (DEBUG_VERIFY) {
14509                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14510                        + " with the correct signature");
14511            }
14512            sufficientVerifiers.add(comp);
14513            verificationState.addSufficientVerifier(verifierUid);
14514        }
14515
14516        return sufficientVerifiers;
14517    }
14518
14519    private int getUidForVerifier(VerifierInfo verifierInfo) {
14520        synchronized (mPackages) {
14521            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14522            if (pkg == null) {
14523                return -1;
14524            } else if (pkg.mSignatures.length != 1) {
14525                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14526                        + " has more than one signature; ignoring");
14527                return -1;
14528            }
14529
14530            /*
14531             * If the public key of the package's signature does not match
14532             * our expected public key, then this is a different package and
14533             * we should skip.
14534             */
14535
14536            final byte[] expectedPublicKey;
14537            try {
14538                final Signature verifierSig = pkg.mSignatures[0];
14539                final PublicKey publicKey = verifierSig.getPublicKey();
14540                expectedPublicKey = publicKey.getEncoded();
14541            } catch (CertificateException e) {
14542                return -1;
14543            }
14544
14545            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14546
14547            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14548                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14549                        + " does not have the expected public key; ignoring");
14550                return -1;
14551            }
14552
14553            return pkg.applicationInfo.uid;
14554        }
14555    }
14556
14557    @Override
14558    public void finishPackageInstall(int token, boolean didLaunch) {
14559        enforceSystemOrRoot("Only the system is allowed to finish installs");
14560
14561        if (DEBUG_INSTALL) {
14562            Slog.v(TAG, "BM finishing package install for " + token);
14563        }
14564        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14565
14566        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14567        mHandler.sendMessage(msg);
14568    }
14569
14570    /**
14571     * Get the verification agent timeout.  Used for both the APK verifier and the
14572     * intent filter verifier.
14573     *
14574     * @return verification timeout in milliseconds
14575     */
14576    private long getVerificationTimeout() {
14577        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14578                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14579                DEFAULT_VERIFICATION_TIMEOUT);
14580    }
14581
14582    /**
14583     * Get the default verification agent response code.
14584     *
14585     * @return default verification response code
14586     */
14587    private int getDefaultVerificationResponse(UserHandle user) {
14588        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14589            return PackageManager.VERIFICATION_REJECT;
14590        }
14591        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14592                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14593                DEFAULT_VERIFICATION_RESPONSE);
14594    }
14595
14596    /**
14597     * Check whether or not package verification has been enabled.
14598     *
14599     * @return true if verification should be performed
14600     */
14601    private boolean isVerificationEnabled(int userId, int installFlags) {
14602        if (!DEFAULT_VERIFY_ENABLE) {
14603            return false;
14604        }
14605
14606        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14607
14608        // Check if installing from ADB
14609        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14610            // Do not run verification in a test harness environment
14611            if (ActivityManager.isRunningInTestHarness()) {
14612                return false;
14613            }
14614            if (ensureVerifyAppsEnabled) {
14615                return true;
14616            }
14617            // Check if the developer does not want package verification for ADB installs
14618            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14619                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14620                return false;
14621            }
14622        }
14623
14624        if (ensureVerifyAppsEnabled) {
14625            return true;
14626        }
14627
14628        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14629                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14630    }
14631
14632    @Override
14633    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14634            throws RemoteException {
14635        mContext.enforceCallingOrSelfPermission(
14636                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14637                "Only intentfilter verification agents can verify applications");
14638
14639        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14640        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14641                Binder.getCallingUid(), verificationCode, failedDomains);
14642        msg.arg1 = id;
14643        msg.obj = response;
14644        mHandler.sendMessage(msg);
14645    }
14646
14647    @Override
14648    public int getIntentVerificationStatus(String packageName, int userId) {
14649        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14650            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14651        }
14652        synchronized (mPackages) {
14653            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14654        }
14655    }
14656
14657    @Override
14658    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14659        mContext.enforceCallingOrSelfPermission(
14660                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14661
14662        boolean result = false;
14663        synchronized (mPackages) {
14664            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14665        }
14666        if (result) {
14667            scheduleWritePackageRestrictionsLocked(userId);
14668        }
14669        return result;
14670    }
14671
14672    @Override
14673    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14674            String packageName) {
14675        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14676            return ParceledListSlice.emptyList();
14677        }
14678        synchronized (mPackages) {
14679            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14680        }
14681    }
14682
14683    @Override
14684    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14685        if (TextUtils.isEmpty(packageName)) {
14686            return ParceledListSlice.emptyList();
14687        }
14688        final int callingUid = Binder.getCallingUid();
14689        final int callingUserId = UserHandle.getUserId(callingUid);
14690        synchronized (mPackages) {
14691            PackageParser.Package pkg = mPackages.get(packageName);
14692            if (pkg == null || pkg.activities == null) {
14693                return ParceledListSlice.emptyList();
14694            }
14695            if (pkg.mExtras == null) {
14696                return ParceledListSlice.emptyList();
14697            }
14698            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14699            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14700                return ParceledListSlice.emptyList();
14701            }
14702            final int count = pkg.activities.size();
14703            ArrayList<IntentFilter> result = new ArrayList<>();
14704            for (int n=0; n<count; n++) {
14705                PackageParser.Activity activity = pkg.activities.get(n);
14706                if (activity.intents != null && activity.intents.size() > 0) {
14707                    result.addAll(activity.intents);
14708                }
14709            }
14710            return new ParceledListSlice<>(result);
14711        }
14712    }
14713
14714    @Override
14715    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14716        mContext.enforceCallingOrSelfPermission(
14717                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14718
14719        synchronized (mPackages) {
14720            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14721            if (packageName != null) {
14722                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
14723                        packageName, userId);
14724            }
14725            return result;
14726        }
14727    }
14728
14729    @Override
14730    public String getDefaultBrowserPackageName(int userId) {
14731        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14732            return null;
14733        }
14734        synchronized (mPackages) {
14735            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14736        }
14737    }
14738
14739    /**
14740     * Get the "allow unknown sources" setting.
14741     *
14742     * @return the current "allow unknown sources" setting
14743     */
14744    private int getUnknownSourcesSettings() {
14745        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14746                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14747                -1);
14748    }
14749
14750    @Override
14751    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14752        final int callingUid = Binder.getCallingUid();
14753        if (getInstantAppPackageName(callingUid) != null) {
14754            return;
14755        }
14756        // writer
14757        synchronized (mPackages) {
14758            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14759            if (targetPackageSetting == null) {
14760                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14761            }
14762
14763            PackageSetting installerPackageSetting;
14764            if (installerPackageName != null) {
14765                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14766                if (installerPackageSetting == null) {
14767                    throw new IllegalArgumentException("Unknown installer package: "
14768                            + installerPackageName);
14769                }
14770            } else {
14771                installerPackageSetting = null;
14772            }
14773
14774            Signature[] callerSignature;
14775            Object obj = mSettings.getUserIdLPr(callingUid);
14776            if (obj != null) {
14777                if (obj instanceof SharedUserSetting) {
14778                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14779                } else if (obj instanceof PackageSetting) {
14780                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14781                } else {
14782                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14783                }
14784            } else {
14785                throw new SecurityException("Unknown calling UID: " + callingUid);
14786            }
14787
14788            // Verify: can't set installerPackageName to a package that is
14789            // not signed with the same cert as the caller.
14790            if (installerPackageSetting != null) {
14791                if (compareSignatures(callerSignature,
14792                        installerPackageSetting.signatures.mSignatures)
14793                        != PackageManager.SIGNATURE_MATCH) {
14794                    throw new SecurityException(
14795                            "Caller does not have same cert as new installer package "
14796                            + installerPackageName);
14797                }
14798            }
14799
14800            // Verify: if target already has an installer package, it must
14801            // be signed with the same cert as the caller.
14802            if (targetPackageSetting.installerPackageName != null) {
14803                PackageSetting setting = mSettings.mPackages.get(
14804                        targetPackageSetting.installerPackageName);
14805                // If the currently set package isn't valid, then it's always
14806                // okay to change it.
14807                if (setting != null) {
14808                    if (compareSignatures(callerSignature,
14809                            setting.signatures.mSignatures)
14810                            != PackageManager.SIGNATURE_MATCH) {
14811                        throw new SecurityException(
14812                                "Caller does not have same cert as old installer package "
14813                                + targetPackageSetting.installerPackageName);
14814                    }
14815                }
14816            }
14817
14818            // Okay!
14819            targetPackageSetting.installerPackageName = installerPackageName;
14820            if (installerPackageName != null) {
14821                mSettings.mInstallerPackages.add(installerPackageName);
14822            }
14823            scheduleWriteSettingsLocked();
14824        }
14825    }
14826
14827    @Override
14828    public void setApplicationCategoryHint(String packageName, int categoryHint,
14829            String callerPackageName) {
14830        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14831            throw new SecurityException("Instant applications don't have access to this method");
14832        }
14833        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14834                callerPackageName);
14835        synchronized (mPackages) {
14836            PackageSetting ps = mSettings.mPackages.get(packageName);
14837            if (ps == null) {
14838                throw new IllegalArgumentException("Unknown target package " + packageName);
14839            }
14840
14841            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14842                throw new IllegalArgumentException("Calling package " + callerPackageName
14843                        + " is not installer for " + packageName);
14844            }
14845
14846            if (ps.categoryHint != categoryHint) {
14847                ps.categoryHint = categoryHint;
14848                scheduleWriteSettingsLocked();
14849            }
14850        }
14851    }
14852
14853    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14854        // Queue up an async operation since the package installation may take a little while.
14855        mHandler.post(new Runnable() {
14856            public void run() {
14857                mHandler.removeCallbacks(this);
14858                 // Result object to be returned
14859                PackageInstalledInfo res = new PackageInstalledInfo();
14860                res.setReturnCode(currentStatus);
14861                res.uid = -1;
14862                res.pkg = null;
14863                res.removedInfo = null;
14864                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14865                    args.doPreInstall(res.returnCode);
14866                    synchronized (mInstallLock) {
14867                        installPackageTracedLI(args, res);
14868                    }
14869                    args.doPostInstall(res.returnCode, res.uid);
14870                }
14871
14872                // A restore should be performed at this point if (a) the install
14873                // succeeded, (b) the operation is not an update, and (c) the new
14874                // package has not opted out of backup participation.
14875                final boolean update = res.removedInfo != null
14876                        && res.removedInfo.removedPackage != null;
14877                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14878                boolean doRestore = !update
14879                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14880
14881                // Set up the post-install work request bookkeeping.  This will be used
14882                // and cleaned up by the post-install event handling regardless of whether
14883                // there's a restore pass performed.  Token values are >= 1.
14884                int token;
14885                if (mNextInstallToken < 0) mNextInstallToken = 1;
14886                token = mNextInstallToken++;
14887
14888                PostInstallData data = new PostInstallData(args, res);
14889                mRunningInstalls.put(token, data);
14890                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14891
14892                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14893                    // Pass responsibility to the Backup Manager.  It will perform a
14894                    // restore if appropriate, then pass responsibility back to the
14895                    // Package Manager to run the post-install observer callbacks
14896                    // and broadcasts.
14897                    IBackupManager bm = IBackupManager.Stub.asInterface(
14898                            ServiceManager.getService(Context.BACKUP_SERVICE));
14899                    if (bm != null) {
14900                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14901                                + " to BM for possible restore");
14902                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14903                        try {
14904                            // TODO: http://b/22388012
14905                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14906                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14907                            } else {
14908                                doRestore = false;
14909                            }
14910                        } catch (RemoteException e) {
14911                            // can't happen; the backup manager is local
14912                        } catch (Exception e) {
14913                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14914                            doRestore = false;
14915                        }
14916                    } else {
14917                        Slog.e(TAG, "Backup Manager not found!");
14918                        doRestore = false;
14919                    }
14920                }
14921
14922                if (!doRestore) {
14923                    // No restore possible, or the Backup Manager was mysteriously not
14924                    // available -- just fire the post-install work request directly.
14925                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14926
14927                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14928
14929                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14930                    mHandler.sendMessage(msg);
14931                }
14932            }
14933        });
14934    }
14935
14936    /**
14937     * Callback from PackageSettings whenever an app is first transitioned out of the
14938     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14939     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14940     * here whether the app is the target of an ongoing install, and only send the
14941     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14942     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14943     * handling.
14944     */
14945    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14946        // Serialize this with the rest of the install-process message chain.  In the
14947        // restore-at-install case, this Runnable will necessarily run before the
14948        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14949        // are coherent.  In the non-restore case, the app has already completed install
14950        // and been launched through some other means, so it is not in a problematic
14951        // state for observers to see the FIRST_LAUNCH signal.
14952        mHandler.post(new Runnable() {
14953            @Override
14954            public void run() {
14955                for (int i = 0; i < mRunningInstalls.size(); i++) {
14956                    final PostInstallData data = mRunningInstalls.valueAt(i);
14957                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14958                        continue;
14959                    }
14960                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14961                        // right package; but is it for the right user?
14962                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14963                            if (userId == data.res.newUsers[uIndex]) {
14964                                if (DEBUG_BACKUP) {
14965                                    Slog.i(TAG, "Package " + pkgName
14966                                            + " being restored so deferring FIRST_LAUNCH");
14967                                }
14968                                return;
14969                            }
14970                        }
14971                    }
14972                }
14973                // didn't find it, so not being restored
14974                if (DEBUG_BACKUP) {
14975                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14976                }
14977                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14978            }
14979        });
14980    }
14981
14982    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14983        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14984                installerPkg, null, userIds);
14985    }
14986
14987    private abstract class HandlerParams {
14988        private static final int MAX_RETRIES = 4;
14989
14990        /**
14991         * Number of times startCopy() has been attempted and had a non-fatal
14992         * error.
14993         */
14994        private int mRetries = 0;
14995
14996        /** User handle for the user requesting the information or installation. */
14997        private final UserHandle mUser;
14998        String traceMethod;
14999        int traceCookie;
15000
15001        HandlerParams(UserHandle user) {
15002            mUser = user;
15003        }
15004
15005        UserHandle getUser() {
15006            return mUser;
15007        }
15008
15009        HandlerParams setTraceMethod(String traceMethod) {
15010            this.traceMethod = traceMethod;
15011            return this;
15012        }
15013
15014        HandlerParams setTraceCookie(int traceCookie) {
15015            this.traceCookie = traceCookie;
15016            return this;
15017        }
15018
15019        final boolean startCopy() {
15020            boolean res;
15021            try {
15022                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15023
15024                if (++mRetries > MAX_RETRIES) {
15025                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15026                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15027                    handleServiceError();
15028                    return false;
15029                } else {
15030                    handleStartCopy();
15031                    res = true;
15032                }
15033            } catch (RemoteException e) {
15034                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15035                mHandler.sendEmptyMessage(MCS_RECONNECT);
15036                res = false;
15037            }
15038            handleReturnCode();
15039            return res;
15040        }
15041
15042        final void serviceError() {
15043            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15044            handleServiceError();
15045            handleReturnCode();
15046        }
15047
15048        abstract void handleStartCopy() throws RemoteException;
15049        abstract void handleServiceError();
15050        abstract void handleReturnCode();
15051    }
15052
15053    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15054        for (File path : paths) {
15055            try {
15056                mcs.clearDirectory(path.getAbsolutePath());
15057            } catch (RemoteException e) {
15058            }
15059        }
15060    }
15061
15062    static class OriginInfo {
15063        /**
15064         * Location where install is coming from, before it has been
15065         * copied/renamed into place. This could be a single monolithic APK
15066         * file, or a cluster directory. This location may be untrusted.
15067         */
15068        final File file;
15069        final String cid;
15070
15071        /**
15072         * Flag indicating that {@link #file} or {@link #cid} has already been
15073         * staged, meaning downstream users don't need to defensively copy the
15074         * contents.
15075         */
15076        final boolean staged;
15077
15078        /**
15079         * Flag indicating that {@link #file} or {@link #cid} is an already
15080         * installed app that is being moved.
15081         */
15082        final boolean existing;
15083
15084        final String resolvedPath;
15085        final File resolvedFile;
15086
15087        static OriginInfo fromNothing() {
15088            return new OriginInfo(null, null, false, false);
15089        }
15090
15091        static OriginInfo fromUntrustedFile(File file) {
15092            return new OriginInfo(file, null, false, false);
15093        }
15094
15095        static OriginInfo fromExistingFile(File file) {
15096            return new OriginInfo(file, null, false, true);
15097        }
15098
15099        static OriginInfo fromStagedFile(File file) {
15100            return new OriginInfo(file, null, true, false);
15101        }
15102
15103        static OriginInfo fromStagedContainer(String cid) {
15104            return new OriginInfo(null, cid, true, false);
15105        }
15106
15107        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15108            this.file = file;
15109            this.cid = cid;
15110            this.staged = staged;
15111            this.existing = existing;
15112
15113            if (cid != null) {
15114                resolvedPath = PackageHelper.getSdDir(cid);
15115                resolvedFile = new File(resolvedPath);
15116            } else if (file != null) {
15117                resolvedPath = file.getAbsolutePath();
15118                resolvedFile = file;
15119            } else {
15120                resolvedPath = null;
15121                resolvedFile = null;
15122            }
15123        }
15124    }
15125
15126    static class MoveInfo {
15127        final int moveId;
15128        final String fromUuid;
15129        final String toUuid;
15130        final String packageName;
15131        final String dataAppName;
15132        final int appId;
15133        final String seinfo;
15134        final int targetSdkVersion;
15135
15136        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15137                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15138            this.moveId = moveId;
15139            this.fromUuid = fromUuid;
15140            this.toUuid = toUuid;
15141            this.packageName = packageName;
15142            this.dataAppName = dataAppName;
15143            this.appId = appId;
15144            this.seinfo = seinfo;
15145            this.targetSdkVersion = targetSdkVersion;
15146        }
15147    }
15148
15149    static class VerificationInfo {
15150        /** A constant used to indicate that a uid value is not present. */
15151        public static final int NO_UID = -1;
15152
15153        /** URI referencing where the package was downloaded from. */
15154        final Uri originatingUri;
15155
15156        /** HTTP referrer URI associated with the originatingURI. */
15157        final Uri referrer;
15158
15159        /** UID of the application that the install request originated from. */
15160        final int originatingUid;
15161
15162        /** UID of application requesting the install */
15163        final int installerUid;
15164
15165        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15166            this.originatingUri = originatingUri;
15167            this.referrer = referrer;
15168            this.originatingUid = originatingUid;
15169            this.installerUid = installerUid;
15170        }
15171    }
15172
15173    class InstallParams extends HandlerParams {
15174        final OriginInfo origin;
15175        final MoveInfo move;
15176        final IPackageInstallObserver2 observer;
15177        int installFlags;
15178        final String installerPackageName;
15179        final String volumeUuid;
15180        private InstallArgs mArgs;
15181        private int mRet;
15182        final String packageAbiOverride;
15183        final String[] grantedRuntimePermissions;
15184        final VerificationInfo verificationInfo;
15185        final Certificate[][] certificates;
15186        final int installReason;
15187
15188        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15189                int installFlags, String installerPackageName, String volumeUuid,
15190                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15191                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15192            super(user);
15193            this.origin = origin;
15194            this.move = move;
15195            this.observer = observer;
15196            this.installFlags = installFlags;
15197            this.installerPackageName = installerPackageName;
15198            this.volumeUuid = volumeUuid;
15199            this.verificationInfo = verificationInfo;
15200            this.packageAbiOverride = packageAbiOverride;
15201            this.grantedRuntimePermissions = grantedPermissions;
15202            this.certificates = certificates;
15203            this.installReason = installReason;
15204        }
15205
15206        @Override
15207        public String toString() {
15208            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15209                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15210        }
15211
15212        private int installLocationPolicy(PackageInfoLite pkgLite) {
15213            String packageName = pkgLite.packageName;
15214            int installLocation = pkgLite.installLocation;
15215            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15216            // reader
15217            synchronized (mPackages) {
15218                // Currently installed package which the new package is attempting to replace or
15219                // null if no such package is installed.
15220                PackageParser.Package installedPkg = mPackages.get(packageName);
15221                // Package which currently owns the data which the new package will own if installed.
15222                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15223                // will be null whereas dataOwnerPkg will contain information about the package
15224                // which was uninstalled while keeping its data.
15225                PackageParser.Package dataOwnerPkg = installedPkg;
15226                if (dataOwnerPkg  == null) {
15227                    PackageSetting ps = mSettings.mPackages.get(packageName);
15228                    if (ps != null) {
15229                        dataOwnerPkg = ps.pkg;
15230                    }
15231                }
15232
15233                if (dataOwnerPkg != null) {
15234                    // If installed, the package will get access to data left on the device by its
15235                    // predecessor. As a security measure, this is permited only if this is not a
15236                    // version downgrade or if the predecessor package is marked as debuggable and
15237                    // a downgrade is explicitly requested.
15238                    //
15239                    // On debuggable platform builds, downgrades are permitted even for
15240                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15241                    // not offer security guarantees and thus it's OK to disable some security
15242                    // mechanisms to make debugging/testing easier on those builds. However, even on
15243                    // debuggable builds downgrades of packages are permitted only if requested via
15244                    // installFlags. This is because we aim to keep the behavior of debuggable
15245                    // platform builds as close as possible to the behavior of non-debuggable
15246                    // platform builds.
15247                    final boolean downgradeRequested =
15248                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15249                    final boolean packageDebuggable =
15250                                (dataOwnerPkg.applicationInfo.flags
15251                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15252                    final boolean downgradePermitted =
15253                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15254                    if (!downgradePermitted) {
15255                        try {
15256                            checkDowngrade(dataOwnerPkg, pkgLite);
15257                        } catch (PackageManagerException e) {
15258                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15259                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15260                        }
15261                    }
15262                }
15263
15264                if (installedPkg != null) {
15265                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15266                        // Check for updated system application.
15267                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15268                            if (onSd) {
15269                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15270                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15271                            }
15272                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15273                        } else {
15274                            if (onSd) {
15275                                // Install flag overrides everything.
15276                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15277                            }
15278                            // If current upgrade specifies particular preference
15279                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15280                                // Application explicitly specified internal.
15281                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15282                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15283                                // App explictly prefers external. Let policy decide
15284                            } else {
15285                                // Prefer previous location
15286                                if (isExternal(installedPkg)) {
15287                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15288                                }
15289                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15290                            }
15291                        }
15292                    } else {
15293                        // Invalid install. Return error code
15294                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15295                    }
15296                }
15297            }
15298            // All the special cases have been taken care of.
15299            // Return result based on recommended install location.
15300            if (onSd) {
15301                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15302            }
15303            return pkgLite.recommendedInstallLocation;
15304        }
15305
15306        /*
15307         * Invoke remote method to get package information and install
15308         * location values. Override install location based on default
15309         * policy if needed and then create install arguments based
15310         * on the install location.
15311         */
15312        public void handleStartCopy() throws RemoteException {
15313            int ret = PackageManager.INSTALL_SUCCEEDED;
15314
15315            // If we're already staged, we've firmly committed to an install location
15316            if (origin.staged) {
15317                if (origin.file != null) {
15318                    installFlags |= PackageManager.INSTALL_INTERNAL;
15319                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15320                } else if (origin.cid != null) {
15321                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15322                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15323                } else {
15324                    throw new IllegalStateException("Invalid stage location");
15325                }
15326            }
15327
15328            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15329            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15330            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15331            PackageInfoLite pkgLite = null;
15332
15333            if (onInt && onSd) {
15334                // Check if both bits are set.
15335                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15336                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15337            } else if (onSd && ephemeral) {
15338                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15339                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15340            } else {
15341                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15342                        packageAbiOverride);
15343
15344                if (DEBUG_EPHEMERAL && ephemeral) {
15345                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15346                }
15347
15348                /*
15349                 * If we have too little free space, try to free cache
15350                 * before giving up.
15351                 */
15352                if (!origin.staged && pkgLite.recommendedInstallLocation
15353                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15354                    // TODO: focus freeing disk space on the target device
15355                    final StorageManager storage = StorageManager.from(mContext);
15356                    final long lowThreshold = storage.getStorageLowBytes(
15357                            Environment.getDataDirectory());
15358
15359                    final long sizeBytes = mContainerService.calculateInstalledSize(
15360                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15361
15362                    try {
15363                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
15364                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15365                                installFlags, packageAbiOverride);
15366                    } catch (InstallerException e) {
15367                        Slog.w(TAG, "Failed to free cache", e);
15368                    }
15369
15370                    /*
15371                     * The cache free must have deleted the file we
15372                     * downloaded to install.
15373                     *
15374                     * TODO: fix the "freeCache" call to not delete
15375                     *       the file we care about.
15376                     */
15377                    if (pkgLite.recommendedInstallLocation
15378                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15379                        pkgLite.recommendedInstallLocation
15380                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15381                    }
15382                }
15383            }
15384
15385            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15386                int loc = pkgLite.recommendedInstallLocation;
15387                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15388                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15389                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15390                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15391                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15392                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15393                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15394                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15395                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15396                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15397                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15398                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15399                } else {
15400                    // Override with defaults if needed.
15401                    loc = installLocationPolicy(pkgLite);
15402                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15403                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15404                    } else if (!onSd && !onInt) {
15405                        // Override install location with flags
15406                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15407                            // Set the flag to install on external media.
15408                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15409                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15410                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15411                            if (DEBUG_EPHEMERAL) {
15412                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15413                            }
15414                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15415                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15416                                    |PackageManager.INSTALL_INTERNAL);
15417                        } else {
15418                            // Make sure the flag for installing on external
15419                            // media is unset
15420                            installFlags |= PackageManager.INSTALL_INTERNAL;
15421                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15422                        }
15423                    }
15424                }
15425            }
15426
15427            final InstallArgs args = createInstallArgs(this);
15428            mArgs = args;
15429
15430            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15431                // TODO: http://b/22976637
15432                // Apps installed for "all" users use the device owner to verify the app
15433                UserHandle verifierUser = getUser();
15434                if (verifierUser == UserHandle.ALL) {
15435                    verifierUser = UserHandle.SYSTEM;
15436                }
15437
15438                /*
15439                 * Determine if we have any installed package verifiers. If we
15440                 * do, then we'll defer to them to verify the packages.
15441                 */
15442                final int requiredUid = mRequiredVerifierPackage == null ? -1
15443                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15444                                verifierUser.getIdentifier());
15445                if (!origin.existing && requiredUid != -1
15446                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
15447                    final Intent verification = new Intent(
15448                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15449                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15450                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15451                            PACKAGE_MIME_TYPE);
15452                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15453
15454                    // Query all live verifiers based on current user state
15455                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15456                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15457
15458                    if (DEBUG_VERIFY) {
15459                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15460                                + verification.toString() + " with " + pkgLite.verifiers.length
15461                                + " optional verifiers");
15462                    }
15463
15464                    final int verificationId = mPendingVerificationToken++;
15465
15466                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15467
15468                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15469                            installerPackageName);
15470
15471                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15472                            installFlags);
15473
15474                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15475                            pkgLite.packageName);
15476
15477                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15478                            pkgLite.versionCode);
15479
15480                    if (verificationInfo != null) {
15481                        if (verificationInfo.originatingUri != null) {
15482                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15483                                    verificationInfo.originatingUri);
15484                        }
15485                        if (verificationInfo.referrer != null) {
15486                            verification.putExtra(Intent.EXTRA_REFERRER,
15487                                    verificationInfo.referrer);
15488                        }
15489                        if (verificationInfo.originatingUid >= 0) {
15490                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15491                                    verificationInfo.originatingUid);
15492                        }
15493                        if (verificationInfo.installerUid >= 0) {
15494                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15495                                    verificationInfo.installerUid);
15496                        }
15497                    }
15498
15499                    final PackageVerificationState verificationState = new PackageVerificationState(
15500                            requiredUid, args);
15501
15502                    mPendingVerification.append(verificationId, verificationState);
15503
15504                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15505                            receivers, verificationState);
15506
15507                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15508                    final long idleDuration = getVerificationTimeout();
15509
15510                    /*
15511                     * If any sufficient verifiers were listed in the package
15512                     * manifest, attempt to ask them.
15513                     */
15514                    if (sufficientVerifiers != null) {
15515                        final int N = sufficientVerifiers.size();
15516                        if (N == 0) {
15517                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15518                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15519                        } else {
15520                            for (int i = 0; i < N; i++) {
15521                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15522                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15523                                        verifierComponent.getPackageName(), idleDuration,
15524                                        verifierUser.getIdentifier(), false, "package verifier");
15525
15526                                final Intent sufficientIntent = new Intent(verification);
15527                                sufficientIntent.setComponent(verifierComponent);
15528                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15529                            }
15530                        }
15531                    }
15532
15533                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15534                            mRequiredVerifierPackage, receivers);
15535                    if (ret == PackageManager.INSTALL_SUCCEEDED
15536                            && mRequiredVerifierPackage != null) {
15537                        Trace.asyncTraceBegin(
15538                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15539                        /*
15540                         * Send the intent to the required verification agent,
15541                         * but only start the verification timeout after the
15542                         * target BroadcastReceivers have run.
15543                         */
15544                        verification.setComponent(requiredVerifierComponent);
15545                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15546                                mRequiredVerifierPackage, idleDuration,
15547                                verifierUser.getIdentifier(), false, "package verifier");
15548                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15549                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15550                                new BroadcastReceiver() {
15551                                    @Override
15552                                    public void onReceive(Context context, Intent intent) {
15553                                        final Message msg = mHandler
15554                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15555                                        msg.arg1 = verificationId;
15556                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15557                                    }
15558                                }, null, 0, null, null);
15559
15560                        /*
15561                         * We don't want the copy to proceed until verification
15562                         * succeeds, so null out this field.
15563                         */
15564                        mArgs = null;
15565                    }
15566                } else {
15567                    /*
15568                     * No package verification is enabled, so immediately start
15569                     * the remote call to initiate copy using temporary file.
15570                     */
15571                    ret = args.copyApk(mContainerService, true);
15572                }
15573            }
15574
15575            mRet = ret;
15576        }
15577
15578        @Override
15579        void handleReturnCode() {
15580            // If mArgs is null, then MCS couldn't be reached. When it
15581            // reconnects, it will try again to install. At that point, this
15582            // will succeed.
15583            if (mArgs != null) {
15584                processPendingInstall(mArgs, mRet);
15585            }
15586        }
15587
15588        @Override
15589        void handleServiceError() {
15590            mArgs = createInstallArgs(this);
15591            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15592        }
15593
15594        public boolean isForwardLocked() {
15595            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15596        }
15597    }
15598
15599    /**
15600     * Used during creation of InstallArgs
15601     *
15602     * @param installFlags package installation flags
15603     * @return true if should be installed on external storage
15604     */
15605    private static boolean installOnExternalAsec(int installFlags) {
15606        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15607            return false;
15608        }
15609        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
15610            return true;
15611        }
15612        return false;
15613    }
15614
15615    /**
15616     * Used during creation of InstallArgs
15617     *
15618     * @param installFlags package installation flags
15619     * @return true if should be installed as forward locked
15620     */
15621    private static boolean installForwardLocked(int installFlags) {
15622        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15623    }
15624
15625    private InstallArgs createInstallArgs(InstallParams params) {
15626        if (params.move != null) {
15627            return new MoveInstallArgs(params);
15628        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15629            return new AsecInstallArgs(params);
15630        } else {
15631            return new FileInstallArgs(params);
15632        }
15633    }
15634
15635    /**
15636     * Create args that describe an existing installed package. Typically used
15637     * when cleaning up old installs, or used as a move source.
15638     */
15639    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15640            String resourcePath, String[] instructionSets) {
15641        final boolean isInAsec;
15642        if (installOnExternalAsec(installFlags)) {
15643            /* Apps on SD card are always in ASEC containers. */
15644            isInAsec = true;
15645        } else if (installForwardLocked(installFlags)
15646                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15647            /*
15648             * Forward-locked apps are only in ASEC containers if they're the
15649             * new style
15650             */
15651            isInAsec = true;
15652        } else {
15653            isInAsec = false;
15654        }
15655
15656        if (isInAsec) {
15657            return new AsecInstallArgs(codePath, instructionSets,
15658                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
15659        } else {
15660            return new FileInstallArgs(codePath, resourcePath, instructionSets);
15661        }
15662    }
15663
15664    static abstract class InstallArgs {
15665        /** @see InstallParams#origin */
15666        final OriginInfo origin;
15667        /** @see InstallParams#move */
15668        final MoveInfo move;
15669
15670        final IPackageInstallObserver2 observer;
15671        // Always refers to PackageManager flags only
15672        final int installFlags;
15673        final String installerPackageName;
15674        final String volumeUuid;
15675        final UserHandle user;
15676        final String abiOverride;
15677        final String[] installGrantPermissions;
15678        /** If non-null, drop an async trace when the install completes */
15679        final String traceMethod;
15680        final int traceCookie;
15681        final Certificate[][] certificates;
15682        final int installReason;
15683
15684        // The list of instruction sets supported by this app. This is currently
15685        // only used during the rmdex() phase to clean up resources. We can get rid of this
15686        // if we move dex files under the common app path.
15687        /* nullable */ String[] instructionSets;
15688
15689        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15690                int installFlags, String installerPackageName, String volumeUuid,
15691                UserHandle user, String[] instructionSets,
15692                String abiOverride, String[] installGrantPermissions,
15693                String traceMethod, int traceCookie, Certificate[][] certificates,
15694                int installReason) {
15695            this.origin = origin;
15696            this.move = move;
15697            this.installFlags = installFlags;
15698            this.observer = observer;
15699            this.installerPackageName = installerPackageName;
15700            this.volumeUuid = volumeUuid;
15701            this.user = user;
15702            this.instructionSets = instructionSets;
15703            this.abiOverride = abiOverride;
15704            this.installGrantPermissions = installGrantPermissions;
15705            this.traceMethod = traceMethod;
15706            this.traceCookie = traceCookie;
15707            this.certificates = certificates;
15708            this.installReason = installReason;
15709        }
15710
15711        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15712        abstract int doPreInstall(int status);
15713
15714        /**
15715         * Rename package into final resting place. All paths on the given
15716         * scanned package should be updated to reflect the rename.
15717         */
15718        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15719        abstract int doPostInstall(int status, int uid);
15720
15721        /** @see PackageSettingBase#codePathString */
15722        abstract String getCodePath();
15723        /** @see PackageSettingBase#resourcePathString */
15724        abstract String getResourcePath();
15725
15726        // Need installer lock especially for dex file removal.
15727        abstract void cleanUpResourcesLI();
15728        abstract boolean doPostDeleteLI(boolean delete);
15729
15730        /**
15731         * Called before the source arguments are copied. This is used mostly
15732         * for MoveParams when it needs to read the source file to put it in the
15733         * destination.
15734         */
15735        int doPreCopy() {
15736            return PackageManager.INSTALL_SUCCEEDED;
15737        }
15738
15739        /**
15740         * Called after the source arguments are copied. This is used mostly for
15741         * MoveParams when it needs to read the source file to put it in the
15742         * destination.
15743         */
15744        int doPostCopy(int uid) {
15745            return PackageManager.INSTALL_SUCCEEDED;
15746        }
15747
15748        protected boolean isFwdLocked() {
15749            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15750        }
15751
15752        protected boolean isExternalAsec() {
15753            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15754        }
15755
15756        protected boolean isEphemeral() {
15757            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15758        }
15759
15760        UserHandle getUser() {
15761            return user;
15762        }
15763    }
15764
15765    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15766        if (!allCodePaths.isEmpty()) {
15767            if (instructionSets == null) {
15768                throw new IllegalStateException("instructionSet == null");
15769            }
15770            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15771            for (String codePath : allCodePaths) {
15772                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15773                    try {
15774                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15775                    } catch (InstallerException ignored) {
15776                    }
15777                }
15778            }
15779        }
15780    }
15781
15782    /**
15783     * Logic to handle installation of non-ASEC applications, including copying
15784     * and renaming logic.
15785     */
15786    class FileInstallArgs extends InstallArgs {
15787        private File codeFile;
15788        private File resourceFile;
15789
15790        // Example topology:
15791        // /data/app/com.example/base.apk
15792        // /data/app/com.example/split_foo.apk
15793        // /data/app/com.example/lib/arm/libfoo.so
15794        // /data/app/com.example/lib/arm64/libfoo.so
15795        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15796
15797        /** New install */
15798        FileInstallArgs(InstallParams params) {
15799            super(params.origin, params.move, params.observer, params.installFlags,
15800                    params.installerPackageName, params.volumeUuid,
15801                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15802                    params.grantedRuntimePermissions,
15803                    params.traceMethod, params.traceCookie, params.certificates,
15804                    params.installReason);
15805            if (isFwdLocked()) {
15806                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15807            }
15808        }
15809
15810        /** Existing install */
15811        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15812            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15813                    null, null, null, 0, null /*certificates*/,
15814                    PackageManager.INSTALL_REASON_UNKNOWN);
15815            this.codeFile = (codePath != null) ? new File(codePath) : null;
15816            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15817        }
15818
15819        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15820            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15821            try {
15822                return doCopyApk(imcs, temp);
15823            } finally {
15824                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15825            }
15826        }
15827
15828        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15829            if (origin.staged) {
15830                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15831                codeFile = origin.file;
15832                resourceFile = origin.file;
15833                return PackageManager.INSTALL_SUCCEEDED;
15834            }
15835
15836            try {
15837                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15838                final File tempDir =
15839                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15840                codeFile = tempDir;
15841                resourceFile = tempDir;
15842            } catch (IOException e) {
15843                Slog.w(TAG, "Failed to create copy file: " + e);
15844                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15845            }
15846
15847            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15848                @Override
15849                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15850                    if (!FileUtils.isValidExtFilename(name)) {
15851                        throw new IllegalArgumentException("Invalid filename: " + name);
15852                    }
15853                    try {
15854                        final File file = new File(codeFile, name);
15855                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15856                                O_RDWR | O_CREAT, 0644);
15857                        Os.chmod(file.getAbsolutePath(), 0644);
15858                        return new ParcelFileDescriptor(fd);
15859                    } catch (ErrnoException e) {
15860                        throw new RemoteException("Failed to open: " + e.getMessage());
15861                    }
15862                }
15863            };
15864
15865            int ret = PackageManager.INSTALL_SUCCEEDED;
15866            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15867            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15868                Slog.e(TAG, "Failed to copy package");
15869                return ret;
15870            }
15871
15872            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15873            NativeLibraryHelper.Handle handle = null;
15874            try {
15875                handle = NativeLibraryHelper.Handle.create(codeFile);
15876                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15877                        abiOverride);
15878            } catch (IOException e) {
15879                Slog.e(TAG, "Copying native libraries failed", e);
15880                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15881            } finally {
15882                IoUtils.closeQuietly(handle);
15883            }
15884
15885            return ret;
15886        }
15887
15888        int doPreInstall(int status) {
15889            if (status != PackageManager.INSTALL_SUCCEEDED) {
15890                cleanUp();
15891            }
15892            return status;
15893        }
15894
15895        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15896            if (status != PackageManager.INSTALL_SUCCEEDED) {
15897                cleanUp();
15898                return false;
15899            }
15900
15901            final File targetDir = codeFile.getParentFile();
15902            final File beforeCodeFile = codeFile;
15903            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15904
15905            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15906            try {
15907                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15908            } catch (ErrnoException e) {
15909                Slog.w(TAG, "Failed to rename", e);
15910                return false;
15911            }
15912
15913            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15914                Slog.w(TAG, "Failed to restorecon");
15915                return false;
15916            }
15917
15918            // Reflect the rename internally
15919            codeFile = afterCodeFile;
15920            resourceFile = afterCodeFile;
15921
15922            // Reflect the rename in scanned details
15923            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15924            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15925                    afterCodeFile, pkg.baseCodePath));
15926            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15927                    afterCodeFile, pkg.splitCodePaths));
15928
15929            // Reflect the rename in app info
15930            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15931            pkg.setApplicationInfoCodePath(pkg.codePath);
15932            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15933            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15934            pkg.setApplicationInfoResourcePath(pkg.codePath);
15935            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15936            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15937
15938            return true;
15939        }
15940
15941        int doPostInstall(int status, int uid) {
15942            if (status != PackageManager.INSTALL_SUCCEEDED) {
15943                cleanUp();
15944            }
15945            return status;
15946        }
15947
15948        @Override
15949        String getCodePath() {
15950            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15951        }
15952
15953        @Override
15954        String getResourcePath() {
15955            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15956        }
15957
15958        private boolean cleanUp() {
15959            if (codeFile == null || !codeFile.exists()) {
15960                return false;
15961            }
15962
15963            removeCodePathLI(codeFile);
15964
15965            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15966                resourceFile.delete();
15967            }
15968
15969            return true;
15970        }
15971
15972        void cleanUpResourcesLI() {
15973            // Try enumerating all code paths before deleting
15974            List<String> allCodePaths = Collections.EMPTY_LIST;
15975            if (codeFile != null && codeFile.exists()) {
15976                try {
15977                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15978                    allCodePaths = pkg.getAllCodePaths();
15979                } catch (PackageParserException e) {
15980                    // Ignored; we tried our best
15981                }
15982            }
15983
15984            cleanUp();
15985            removeDexFiles(allCodePaths, instructionSets);
15986        }
15987
15988        boolean doPostDeleteLI(boolean delete) {
15989            // XXX err, shouldn't we respect the delete flag?
15990            cleanUpResourcesLI();
15991            return true;
15992        }
15993    }
15994
15995    private boolean isAsecExternal(String cid) {
15996        final String asecPath = PackageHelper.getSdFilesystem(cid);
15997        return !asecPath.startsWith(mAsecInternalPath);
15998    }
15999
16000    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16001            PackageManagerException {
16002        if (copyRet < 0) {
16003            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16004                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16005                throw new PackageManagerException(copyRet, message);
16006            }
16007        }
16008    }
16009
16010    /**
16011     * Extract the StorageManagerService "container ID" from the full code path of an
16012     * .apk.
16013     */
16014    static String cidFromCodePath(String fullCodePath) {
16015        int eidx = fullCodePath.lastIndexOf("/");
16016        String subStr1 = fullCodePath.substring(0, eidx);
16017        int sidx = subStr1.lastIndexOf("/");
16018        return subStr1.substring(sidx+1, eidx);
16019    }
16020
16021    /**
16022     * Logic to handle installation of ASEC applications, including copying and
16023     * renaming logic.
16024     */
16025    class AsecInstallArgs extends InstallArgs {
16026        static final String RES_FILE_NAME = "pkg.apk";
16027        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16028
16029        String cid;
16030        String packagePath;
16031        String resourcePath;
16032
16033        /** New install */
16034        AsecInstallArgs(InstallParams params) {
16035            super(params.origin, params.move, params.observer, params.installFlags,
16036                    params.installerPackageName, params.volumeUuid,
16037                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16038                    params.grantedRuntimePermissions,
16039                    params.traceMethod, params.traceCookie, params.certificates,
16040                    params.installReason);
16041        }
16042
16043        /** Existing install */
16044        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16045                        boolean isExternal, boolean isForwardLocked) {
16046            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16047                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16048                    instructionSets, null, null, null, 0, null /*certificates*/,
16049                    PackageManager.INSTALL_REASON_UNKNOWN);
16050            // Hackily pretend we're still looking at a full code path
16051            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16052                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16053            }
16054
16055            // Extract cid from fullCodePath
16056            int eidx = fullCodePath.lastIndexOf("/");
16057            String subStr1 = fullCodePath.substring(0, eidx);
16058            int sidx = subStr1.lastIndexOf("/");
16059            cid = subStr1.substring(sidx+1, eidx);
16060            setMountPath(subStr1);
16061        }
16062
16063        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16064            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16065                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16066                    instructionSets, null, null, null, 0, null /*certificates*/,
16067                    PackageManager.INSTALL_REASON_UNKNOWN);
16068            this.cid = cid;
16069            setMountPath(PackageHelper.getSdDir(cid));
16070        }
16071
16072        void createCopyFile() {
16073            cid = mInstallerService.allocateExternalStageCidLegacy();
16074        }
16075
16076        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16077            if (origin.staged && origin.cid != null) {
16078                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16079                cid = origin.cid;
16080                setMountPath(PackageHelper.getSdDir(cid));
16081                return PackageManager.INSTALL_SUCCEEDED;
16082            }
16083
16084            if (temp) {
16085                createCopyFile();
16086            } else {
16087                /*
16088                 * Pre-emptively destroy the container since it's destroyed if
16089                 * copying fails due to it existing anyway.
16090                 */
16091                PackageHelper.destroySdDir(cid);
16092            }
16093
16094            final String newMountPath = imcs.copyPackageToContainer(
16095                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16096                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16097
16098            if (newMountPath != null) {
16099                setMountPath(newMountPath);
16100                return PackageManager.INSTALL_SUCCEEDED;
16101            } else {
16102                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16103            }
16104        }
16105
16106        @Override
16107        String getCodePath() {
16108            return packagePath;
16109        }
16110
16111        @Override
16112        String getResourcePath() {
16113            return resourcePath;
16114        }
16115
16116        int doPreInstall(int status) {
16117            if (status != PackageManager.INSTALL_SUCCEEDED) {
16118                // Destroy container
16119                PackageHelper.destroySdDir(cid);
16120            } else {
16121                boolean mounted = PackageHelper.isContainerMounted(cid);
16122                if (!mounted) {
16123                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16124                            Process.SYSTEM_UID);
16125                    if (newMountPath != null) {
16126                        setMountPath(newMountPath);
16127                    } else {
16128                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16129                    }
16130                }
16131            }
16132            return status;
16133        }
16134
16135        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16136            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16137            String newMountPath = null;
16138            if (PackageHelper.isContainerMounted(cid)) {
16139                // Unmount the container
16140                if (!PackageHelper.unMountSdDir(cid)) {
16141                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16142                    return false;
16143                }
16144            }
16145            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16146                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16147                        " which might be stale. Will try to clean up.");
16148                // Clean up the stale container and proceed to recreate.
16149                if (!PackageHelper.destroySdDir(newCacheId)) {
16150                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16151                    return false;
16152                }
16153                // Successfully cleaned up stale container. Try to rename again.
16154                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16155                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16156                            + " inspite of cleaning it up.");
16157                    return false;
16158                }
16159            }
16160            if (!PackageHelper.isContainerMounted(newCacheId)) {
16161                Slog.w(TAG, "Mounting container " + newCacheId);
16162                newMountPath = PackageHelper.mountSdDir(newCacheId,
16163                        getEncryptKey(), Process.SYSTEM_UID);
16164            } else {
16165                newMountPath = PackageHelper.getSdDir(newCacheId);
16166            }
16167            if (newMountPath == null) {
16168                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16169                return false;
16170            }
16171            Log.i(TAG, "Succesfully renamed " + cid +
16172                    " to " + newCacheId +
16173                    " at new path: " + newMountPath);
16174            cid = newCacheId;
16175
16176            final File beforeCodeFile = new File(packagePath);
16177            setMountPath(newMountPath);
16178            final File afterCodeFile = new File(packagePath);
16179
16180            // Reflect the rename in scanned details
16181            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16182            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16183                    afterCodeFile, pkg.baseCodePath));
16184            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16185                    afterCodeFile, pkg.splitCodePaths));
16186
16187            // Reflect the rename in app info
16188            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16189            pkg.setApplicationInfoCodePath(pkg.codePath);
16190            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16191            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16192            pkg.setApplicationInfoResourcePath(pkg.codePath);
16193            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16194            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16195
16196            return true;
16197        }
16198
16199        private void setMountPath(String mountPath) {
16200            final File mountFile = new File(mountPath);
16201
16202            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16203            if (monolithicFile.exists()) {
16204                packagePath = monolithicFile.getAbsolutePath();
16205                if (isFwdLocked()) {
16206                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16207                } else {
16208                    resourcePath = packagePath;
16209                }
16210            } else {
16211                packagePath = mountFile.getAbsolutePath();
16212                resourcePath = packagePath;
16213            }
16214        }
16215
16216        int doPostInstall(int status, int uid) {
16217            if (status != PackageManager.INSTALL_SUCCEEDED) {
16218                cleanUp();
16219            } else {
16220                final int groupOwner;
16221                final String protectedFile;
16222                if (isFwdLocked()) {
16223                    groupOwner = UserHandle.getSharedAppGid(uid);
16224                    protectedFile = RES_FILE_NAME;
16225                } else {
16226                    groupOwner = -1;
16227                    protectedFile = null;
16228                }
16229
16230                if (uid < Process.FIRST_APPLICATION_UID
16231                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16232                    Slog.e(TAG, "Failed to finalize " + cid);
16233                    PackageHelper.destroySdDir(cid);
16234                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16235                }
16236
16237                boolean mounted = PackageHelper.isContainerMounted(cid);
16238                if (!mounted) {
16239                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16240                }
16241            }
16242            return status;
16243        }
16244
16245        private void cleanUp() {
16246            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16247
16248            // Destroy secure container
16249            PackageHelper.destroySdDir(cid);
16250        }
16251
16252        private List<String> getAllCodePaths() {
16253            final File codeFile = new File(getCodePath());
16254            if (codeFile != null && codeFile.exists()) {
16255                try {
16256                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16257                    return pkg.getAllCodePaths();
16258                } catch (PackageParserException e) {
16259                    // Ignored; we tried our best
16260                }
16261            }
16262            return Collections.EMPTY_LIST;
16263        }
16264
16265        void cleanUpResourcesLI() {
16266            // Enumerate all code paths before deleting
16267            cleanUpResourcesLI(getAllCodePaths());
16268        }
16269
16270        private void cleanUpResourcesLI(List<String> allCodePaths) {
16271            cleanUp();
16272            removeDexFiles(allCodePaths, instructionSets);
16273        }
16274
16275        String getPackageName() {
16276            return getAsecPackageName(cid);
16277        }
16278
16279        boolean doPostDeleteLI(boolean delete) {
16280            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16281            final List<String> allCodePaths = getAllCodePaths();
16282            boolean mounted = PackageHelper.isContainerMounted(cid);
16283            if (mounted) {
16284                // Unmount first
16285                if (PackageHelper.unMountSdDir(cid)) {
16286                    mounted = false;
16287                }
16288            }
16289            if (!mounted && delete) {
16290                cleanUpResourcesLI(allCodePaths);
16291            }
16292            return !mounted;
16293        }
16294
16295        @Override
16296        int doPreCopy() {
16297            if (isFwdLocked()) {
16298                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16299                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16300                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16301                }
16302            }
16303
16304            return PackageManager.INSTALL_SUCCEEDED;
16305        }
16306
16307        @Override
16308        int doPostCopy(int uid) {
16309            if (isFwdLocked()) {
16310                if (uid < Process.FIRST_APPLICATION_UID
16311                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16312                                RES_FILE_NAME)) {
16313                    Slog.e(TAG, "Failed to finalize " + cid);
16314                    PackageHelper.destroySdDir(cid);
16315                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16316                }
16317            }
16318
16319            return PackageManager.INSTALL_SUCCEEDED;
16320        }
16321    }
16322
16323    /**
16324     * Logic to handle movement of existing installed applications.
16325     */
16326    class MoveInstallArgs extends InstallArgs {
16327        private File codeFile;
16328        private File resourceFile;
16329
16330        /** New install */
16331        MoveInstallArgs(InstallParams params) {
16332            super(params.origin, params.move, params.observer, params.installFlags,
16333                    params.installerPackageName, params.volumeUuid,
16334                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16335                    params.grantedRuntimePermissions,
16336                    params.traceMethod, params.traceCookie, params.certificates,
16337                    params.installReason);
16338        }
16339
16340        int copyApk(IMediaContainerService imcs, boolean temp) {
16341            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16342                    + move.fromUuid + " to " + move.toUuid);
16343            synchronized (mInstaller) {
16344                try {
16345                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16346                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16347                } catch (InstallerException e) {
16348                    Slog.w(TAG, "Failed to move app", e);
16349                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16350                }
16351            }
16352
16353            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16354            resourceFile = codeFile;
16355            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16356
16357            return PackageManager.INSTALL_SUCCEEDED;
16358        }
16359
16360        int doPreInstall(int status) {
16361            if (status != PackageManager.INSTALL_SUCCEEDED) {
16362                cleanUp(move.toUuid);
16363            }
16364            return status;
16365        }
16366
16367        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16368            if (status != PackageManager.INSTALL_SUCCEEDED) {
16369                cleanUp(move.toUuid);
16370                return false;
16371            }
16372
16373            // Reflect the move in app info
16374            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16375            pkg.setApplicationInfoCodePath(pkg.codePath);
16376            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16377            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16378            pkg.setApplicationInfoResourcePath(pkg.codePath);
16379            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16380            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16381
16382            return true;
16383        }
16384
16385        int doPostInstall(int status, int uid) {
16386            if (status == PackageManager.INSTALL_SUCCEEDED) {
16387                cleanUp(move.fromUuid);
16388            } else {
16389                cleanUp(move.toUuid);
16390            }
16391            return status;
16392        }
16393
16394        @Override
16395        String getCodePath() {
16396            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16397        }
16398
16399        @Override
16400        String getResourcePath() {
16401            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16402        }
16403
16404        private boolean cleanUp(String volumeUuid) {
16405            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16406                    move.dataAppName);
16407            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16408            final int[] userIds = sUserManager.getUserIds();
16409            synchronized (mInstallLock) {
16410                // Clean up both app data and code
16411                // All package moves are frozen until finished
16412                for (int userId : userIds) {
16413                    try {
16414                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16415                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16416                    } catch (InstallerException e) {
16417                        Slog.w(TAG, String.valueOf(e));
16418                    }
16419                }
16420                removeCodePathLI(codeFile);
16421            }
16422            return true;
16423        }
16424
16425        void cleanUpResourcesLI() {
16426            throw new UnsupportedOperationException();
16427        }
16428
16429        boolean doPostDeleteLI(boolean delete) {
16430            throw new UnsupportedOperationException();
16431        }
16432    }
16433
16434    static String getAsecPackageName(String packageCid) {
16435        int idx = packageCid.lastIndexOf("-");
16436        if (idx == -1) {
16437            return packageCid;
16438        }
16439        return packageCid.substring(0, idx);
16440    }
16441
16442    // Utility method used to create code paths based on package name and available index.
16443    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16444        String idxStr = "";
16445        int idx = 1;
16446        // Fall back to default value of idx=1 if prefix is not
16447        // part of oldCodePath
16448        if (oldCodePath != null) {
16449            String subStr = oldCodePath;
16450            // Drop the suffix right away
16451            if (suffix != null && subStr.endsWith(suffix)) {
16452                subStr = subStr.substring(0, subStr.length() - suffix.length());
16453            }
16454            // If oldCodePath already contains prefix find out the
16455            // ending index to either increment or decrement.
16456            int sidx = subStr.lastIndexOf(prefix);
16457            if (sidx != -1) {
16458                subStr = subStr.substring(sidx + prefix.length());
16459                if (subStr != null) {
16460                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16461                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16462                    }
16463                    try {
16464                        idx = Integer.parseInt(subStr);
16465                        if (idx <= 1) {
16466                            idx++;
16467                        } else {
16468                            idx--;
16469                        }
16470                    } catch(NumberFormatException e) {
16471                    }
16472                }
16473            }
16474        }
16475        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16476        return prefix + idxStr;
16477    }
16478
16479    private File getNextCodePath(File targetDir, String packageName) {
16480        File result;
16481        SecureRandom random = new SecureRandom();
16482        byte[] bytes = new byte[16];
16483        do {
16484            random.nextBytes(bytes);
16485            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16486            result = new File(targetDir, packageName + "-" + suffix);
16487        } while (result.exists());
16488        return result;
16489    }
16490
16491    // Utility method that returns the relative package path with respect
16492    // to the installation directory. Like say for /data/data/com.test-1.apk
16493    // string com.test-1 is returned.
16494    static String deriveCodePathName(String codePath) {
16495        if (codePath == null) {
16496            return null;
16497        }
16498        final File codeFile = new File(codePath);
16499        final String name = codeFile.getName();
16500        if (codeFile.isDirectory()) {
16501            return name;
16502        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16503            final int lastDot = name.lastIndexOf('.');
16504            return name.substring(0, lastDot);
16505        } else {
16506            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16507            return null;
16508        }
16509    }
16510
16511    static class PackageInstalledInfo {
16512        String name;
16513        int uid;
16514        // The set of users that originally had this package installed.
16515        int[] origUsers;
16516        // The set of users that now have this package installed.
16517        int[] newUsers;
16518        PackageParser.Package pkg;
16519        int returnCode;
16520        String returnMsg;
16521        PackageRemovedInfo removedInfo;
16522        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16523
16524        public void setError(int code, String msg) {
16525            setReturnCode(code);
16526            setReturnMessage(msg);
16527            Slog.w(TAG, msg);
16528        }
16529
16530        public void setError(String msg, PackageParserException e) {
16531            setReturnCode(e.error);
16532            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16533            Slog.w(TAG, msg, e);
16534        }
16535
16536        public void setError(String msg, PackageManagerException e) {
16537            returnCode = e.error;
16538            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16539            Slog.w(TAG, msg, e);
16540        }
16541
16542        public void setReturnCode(int returnCode) {
16543            this.returnCode = returnCode;
16544            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16545            for (int i = 0; i < childCount; i++) {
16546                addedChildPackages.valueAt(i).returnCode = returnCode;
16547            }
16548        }
16549
16550        private void setReturnMessage(String returnMsg) {
16551            this.returnMsg = returnMsg;
16552            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16553            for (int i = 0; i < childCount; i++) {
16554                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16555            }
16556        }
16557
16558        // In some error cases we want to convey more info back to the observer
16559        String origPackage;
16560        String origPermission;
16561    }
16562
16563    /*
16564     * Install a non-existing package.
16565     */
16566    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16567            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16568            PackageInstalledInfo res, int installReason) {
16569        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16570
16571        // Remember this for later, in case we need to rollback this install
16572        String pkgName = pkg.packageName;
16573
16574        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16575
16576        synchronized(mPackages) {
16577            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16578            if (renamedPackage != null) {
16579                // A package with the same name is already installed, though
16580                // it has been renamed to an older name.  The package we
16581                // are trying to install should be installed as an update to
16582                // the existing one, but that has not been requested, so bail.
16583                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16584                        + " without first uninstalling package running as "
16585                        + renamedPackage);
16586                return;
16587            }
16588            if (mPackages.containsKey(pkgName)) {
16589                // Don't allow installation over an existing package with the same name.
16590                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16591                        + " without first uninstalling.");
16592                return;
16593            }
16594        }
16595
16596        try {
16597            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16598                    System.currentTimeMillis(), user);
16599
16600            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16601
16602            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16603                prepareAppDataAfterInstallLIF(newPackage);
16604
16605            } else {
16606                // Remove package from internal structures, but keep around any
16607                // data that might have already existed
16608                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16609                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16610            }
16611        } catch (PackageManagerException e) {
16612            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16613        }
16614
16615        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16616    }
16617
16618    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16619        // Can't rotate keys during boot or if sharedUser.
16620        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16621                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16622            return false;
16623        }
16624        // app is using upgradeKeySets; make sure all are valid
16625        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16626        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16627        for (int i = 0; i < upgradeKeySets.length; i++) {
16628            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16629                Slog.wtf(TAG, "Package "
16630                         + (oldPs.name != null ? oldPs.name : "<null>")
16631                         + " contains upgrade-key-set reference to unknown key-set: "
16632                         + upgradeKeySets[i]
16633                         + " reverting to signatures check.");
16634                return false;
16635            }
16636        }
16637        return true;
16638    }
16639
16640    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16641        // Upgrade keysets are being used.  Determine if new package has a superset of the
16642        // required keys.
16643        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16644        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16645        for (int i = 0; i < upgradeKeySets.length; i++) {
16646            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16647            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16648                return true;
16649            }
16650        }
16651        return false;
16652    }
16653
16654    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16655        try (DigestInputStream digestStream =
16656                new DigestInputStream(new FileInputStream(file), digest)) {
16657            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16658        }
16659    }
16660
16661    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16662            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16663            int installReason) {
16664        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16665
16666        final PackageParser.Package oldPackage;
16667        final PackageSetting ps;
16668        final String pkgName = pkg.packageName;
16669        final int[] allUsers;
16670        final int[] installedUsers;
16671
16672        synchronized(mPackages) {
16673            oldPackage = mPackages.get(pkgName);
16674            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16675
16676            // don't allow upgrade to target a release SDK from a pre-release SDK
16677            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16678                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16679            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16680                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16681            if (oldTargetsPreRelease
16682                    && !newTargetsPreRelease
16683                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16684                Slog.w(TAG, "Can't install package targeting released sdk");
16685                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16686                return;
16687            }
16688
16689            ps = mSettings.mPackages.get(pkgName);
16690
16691            // verify signatures are valid
16692            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16693                if (!checkUpgradeKeySetLP(ps, pkg)) {
16694                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16695                            "New package not signed by keys specified by upgrade-keysets: "
16696                                    + pkgName);
16697                    return;
16698                }
16699            } else {
16700                // default to original signature matching
16701                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16702                        != PackageManager.SIGNATURE_MATCH) {
16703                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16704                            "New package has a different signature: " + pkgName);
16705                    return;
16706                }
16707            }
16708
16709            // don't allow a system upgrade unless the upgrade hash matches
16710            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16711                byte[] digestBytes = null;
16712                try {
16713                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16714                    updateDigest(digest, new File(pkg.baseCodePath));
16715                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16716                        for (String path : pkg.splitCodePaths) {
16717                            updateDigest(digest, new File(path));
16718                        }
16719                    }
16720                    digestBytes = digest.digest();
16721                } catch (NoSuchAlgorithmException | IOException e) {
16722                    res.setError(INSTALL_FAILED_INVALID_APK,
16723                            "Could not compute hash: " + pkgName);
16724                    return;
16725                }
16726                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16727                    res.setError(INSTALL_FAILED_INVALID_APK,
16728                            "New package fails restrict-update check: " + pkgName);
16729                    return;
16730                }
16731                // retain upgrade restriction
16732                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16733            }
16734
16735            // Check for shared user id changes
16736            String invalidPackageName =
16737                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16738            if (invalidPackageName != null) {
16739                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16740                        "Package " + invalidPackageName + " tried to change user "
16741                                + oldPackage.mSharedUserId);
16742                return;
16743            }
16744
16745            // In case of rollback, remember per-user/profile install state
16746            allUsers = sUserManager.getUserIds();
16747            installedUsers = ps.queryInstalledUsers(allUsers, true);
16748
16749            // don't allow an upgrade from full to ephemeral
16750            if (isInstantApp) {
16751                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16752                    for (int currentUser : allUsers) {
16753                        if (!ps.getInstantApp(currentUser)) {
16754                            // can't downgrade from full to instant
16755                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16756                                    + " for user: " + currentUser);
16757                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16758                            return;
16759                        }
16760                    }
16761                } else if (!ps.getInstantApp(user.getIdentifier())) {
16762                    // can't downgrade from full to instant
16763                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16764                            + " for user: " + user.getIdentifier());
16765                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16766                    return;
16767                }
16768            }
16769        }
16770
16771        // Update what is removed
16772        res.removedInfo = new PackageRemovedInfo(this);
16773        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16774        res.removedInfo.removedPackage = oldPackage.packageName;
16775        res.removedInfo.installerPackageName = ps.installerPackageName;
16776        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16777        res.removedInfo.isUpdate = true;
16778        res.removedInfo.origUsers = installedUsers;
16779        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16780        for (int i = 0; i < installedUsers.length; i++) {
16781            final int userId = installedUsers[i];
16782            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16783        }
16784
16785        final int childCount = (oldPackage.childPackages != null)
16786                ? oldPackage.childPackages.size() : 0;
16787        for (int i = 0; i < childCount; i++) {
16788            boolean childPackageUpdated = false;
16789            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16790            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16791            if (res.addedChildPackages != null) {
16792                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16793                if (childRes != null) {
16794                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16795                    childRes.removedInfo.removedPackage = childPkg.packageName;
16796                    if (childPs != null) {
16797                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16798                    }
16799                    childRes.removedInfo.isUpdate = true;
16800                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16801                    childPackageUpdated = true;
16802                }
16803            }
16804            if (!childPackageUpdated) {
16805                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16806                childRemovedRes.removedPackage = childPkg.packageName;
16807                if (childPs != null) {
16808                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16809                }
16810                childRemovedRes.isUpdate = false;
16811                childRemovedRes.dataRemoved = true;
16812                synchronized (mPackages) {
16813                    if (childPs != null) {
16814                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16815                    }
16816                }
16817                if (res.removedInfo.removedChildPackages == null) {
16818                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16819                }
16820                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16821            }
16822        }
16823
16824        boolean sysPkg = (isSystemApp(oldPackage));
16825        if (sysPkg) {
16826            // Set the system/privileged flags as needed
16827            final boolean privileged =
16828                    (oldPackage.applicationInfo.privateFlags
16829                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16830            final int systemPolicyFlags = policyFlags
16831                    | PackageParser.PARSE_IS_SYSTEM
16832                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16833
16834            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16835                    user, allUsers, installerPackageName, res, installReason);
16836        } else {
16837            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16838                    user, allUsers, installerPackageName, res, installReason);
16839        }
16840    }
16841
16842    @Override
16843    public List<String> getPreviousCodePaths(String packageName) {
16844        final List<String> result = new ArrayList<>();
16845        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
16846            return result;
16847        }
16848        final PackageSetting ps = mSettings.mPackages.get(packageName);
16849        if (ps != null && ps.oldCodePaths != null) {
16850            result.addAll(ps.oldCodePaths);
16851        }
16852        return result;
16853    }
16854
16855    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16856            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16857            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16858            int installReason) {
16859        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16860                + deletedPackage);
16861
16862        String pkgName = deletedPackage.packageName;
16863        boolean deletedPkg = true;
16864        boolean addedPkg = false;
16865        boolean updatedSettings = false;
16866        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16867        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16868                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16869
16870        final long origUpdateTime = (pkg.mExtras != null)
16871                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16872
16873        // First delete the existing package while retaining the data directory
16874        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16875                res.removedInfo, true, pkg)) {
16876            // If the existing package wasn't successfully deleted
16877            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16878            deletedPkg = false;
16879        } else {
16880            // Successfully deleted the old package; proceed with replace.
16881
16882            // If deleted package lived in a container, give users a chance to
16883            // relinquish resources before killing.
16884            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16885                if (DEBUG_INSTALL) {
16886                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16887                }
16888                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16889                final ArrayList<String> pkgList = new ArrayList<String>(1);
16890                pkgList.add(deletedPackage.applicationInfo.packageName);
16891                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16892            }
16893
16894            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16895                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16896            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16897
16898            try {
16899                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16900                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16901                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16902                        installReason);
16903
16904                // Update the in-memory copy of the previous code paths.
16905                PackageSetting ps = mSettings.mPackages.get(pkgName);
16906                if (!killApp) {
16907                    if (ps.oldCodePaths == null) {
16908                        ps.oldCodePaths = new ArraySet<>();
16909                    }
16910                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16911                    if (deletedPackage.splitCodePaths != null) {
16912                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16913                    }
16914                } else {
16915                    ps.oldCodePaths = null;
16916                }
16917                if (ps.childPackageNames != null) {
16918                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16919                        final String childPkgName = ps.childPackageNames.get(i);
16920                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16921                        childPs.oldCodePaths = ps.oldCodePaths;
16922                    }
16923                }
16924                // set instant app status, but, only if it's explicitly specified
16925                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16926                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16927                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16928                prepareAppDataAfterInstallLIF(newPackage);
16929                addedPkg = true;
16930                mDexManager.notifyPackageUpdated(newPackage.packageName,
16931                        newPackage.baseCodePath, newPackage.splitCodePaths);
16932            } catch (PackageManagerException e) {
16933                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16934            }
16935        }
16936
16937        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16938            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16939
16940            // Revert all internal state mutations and added folders for the failed install
16941            if (addedPkg) {
16942                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16943                        res.removedInfo, true, null);
16944            }
16945
16946            // Restore the old package
16947            if (deletedPkg) {
16948                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16949                File restoreFile = new File(deletedPackage.codePath);
16950                // Parse old package
16951                boolean oldExternal = isExternal(deletedPackage);
16952                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16953                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16954                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16955                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16956                try {
16957                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16958                            null);
16959                } catch (PackageManagerException e) {
16960                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16961                            + e.getMessage());
16962                    return;
16963                }
16964
16965                synchronized (mPackages) {
16966                    // Ensure the installer package name up to date
16967                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16968
16969                    // Update permissions for restored package
16970                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16971
16972                    mSettings.writeLPr();
16973                }
16974
16975                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16976            }
16977        } else {
16978            synchronized (mPackages) {
16979                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16980                if (ps != null) {
16981                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16982                    if (res.removedInfo.removedChildPackages != null) {
16983                        final int childCount = res.removedInfo.removedChildPackages.size();
16984                        // Iterate in reverse as we may modify the collection
16985                        for (int i = childCount - 1; i >= 0; i--) {
16986                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16987                            if (res.addedChildPackages.containsKey(childPackageName)) {
16988                                res.removedInfo.removedChildPackages.removeAt(i);
16989                            } else {
16990                                PackageRemovedInfo childInfo = res.removedInfo
16991                                        .removedChildPackages.valueAt(i);
16992                                childInfo.removedForAllUsers = mPackages.get(
16993                                        childInfo.removedPackage) == null;
16994                            }
16995                        }
16996                    }
16997                }
16998            }
16999        }
17000    }
17001
17002    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17003            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17004            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17005            int installReason) {
17006        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17007                + ", old=" + deletedPackage);
17008
17009        final boolean disabledSystem;
17010
17011        // Remove existing system package
17012        removePackageLI(deletedPackage, true);
17013
17014        synchronized (mPackages) {
17015            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17016        }
17017        if (!disabledSystem) {
17018            // We didn't need to disable the .apk as a current system package,
17019            // which means we are replacing another update that is already
17020            // installed.  We need to make sure to delete the older one's .apk.
17021            res.removedInfo.args = createInstallArgsForExisting(0,
17022                    deletedPackage.applicationInfo.getCodePath(),
17023                    deletedPackage.applicationInfo.getResourcePath(),
17024                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17025        } else {
17026            res.removedInfo.args = null;
17027        }
17028
17029        // Successfully disabled the old package. Now proceed with re-installation
17030        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17031                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17032        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17033
17034        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17035        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17036                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17037
17038        PackageParser.Package newPackage = null;
17039        try {
17040            // Add the package to the internal data structures
17041            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17042
17043            // Set the update and install times
17044            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17045            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17046                    System.currentTimeMillis());
17047
17048            // Update the package dynamic state if succeeded
17049            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17050                // Now that the install succeeded make sure we remove data
17051                // directories for any child package the update removed.
17052                final int deletedChildCount = (deletedPackage.childPackages != null)
17053                        ? deletedPackage.childPackages.size() : 0;
17054                final int newChildCount = (newPackage.childPackages != null)
17055                        ? newPackage.childPackages.size() : 0;
17056                for (int i = 0; i < deletedChildCount; i++) {
17057                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17058                    boolean childPackageDeleted = true;
17059                    for (int j = 0; j < newChildCount; j++) {
17060                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17061                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17062                            childPackageDeleted = false;
17063                            break;
17064                        }
17065                    }
17066                    if (childPackageDeleted) {
17067                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17068                                deletedChildPkg.packageName);
17069                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17070                            PackageRemovedInfo removedChildRes = res.removedInfo
17071                                    .removedChildPackages.get(deletedChildPkg.packageName);
17072                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17073                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17074                        }
17075                    }
17076                }
17077
17078                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17079                        installReason);
17080                prepareAppDataAfterInstallLIF(newPackage);
17081
17082                mDexManager.notifyPackageUpdated(newPackage.packageName,
17083                            newPackage.baseCodePath, newPackage.splitCodePaths);
17084            }
17085        } catch (PackageManagerException e) {
17086            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17087            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17088        }
17089
17090        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17091            // Re installation failed. Restore old information
17092            // Remove new pkg information
17093            if (newPackage != null) {
17094                removeInstalledPackageLI(newPackage, true);
17095            }
17096            // Add back the old system package
17097            try {
17098                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17099            } catch (PackageManagerException e) {
17100                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17101            }
17102
17103            synchronized (mPackages) {
17104                if (disabledSystem) {
17105                    enableSystemPackageLPw(deletedPackage);
17106                }
17107
17108                // Ensure the installer package name up to date
17109                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17110
17111                // Update permissions for restored package
17112                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17113
17114                mSettings.writeLPr();
17115            }
17116
17117            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17118                    + " after failed upgrade");
17119        }
17120    }
17121
17122    /**
17123     * Checks whether the parent or any of the child packages have a change shared
17124     * user. For a package to be a valid update the shred users of the parent and
17125     * the children should match. We may later support changing child shared users.
17126     * @param oldPkg The updated package.
17127     * @param newPkg The update package.
17128     * @return The shared user that change between the versions.
17129     */
17130    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17131            PackageParser.Package newPkg) {
17132        // Check parent shared user
17133        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17134            return newPkg.packageName;
17135        }
17136        // Check child shared users
17137        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17138        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17139        for (int i = 0; i < newChildCount; i++) {
17140            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17141            // If this child was present, did it have the same shared user?
17142            for (int j = 0; j < oldChildCount; j++) {
17143                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17144                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17145                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17146                    return newChildPkg.packageName;
17147                }
17148            }
17149        }
17150        return null;
17151    }
17152
17153    private void removeNativeBinariesLI(PackageSetting ps) {
17154        // Remove the lib path for the parent package
17155        if (ps != null) {
17156            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17157            // Remove the lib path for the child packages
17158            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17159            for (int i = 0; i < childCount; i++) {
17160                PackageSetting childPs = null;
17161                synchronized (mPackages) {
17162                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17163                }
17164                if (childPs != null) {
17165                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17166                            .legacyNativeLibraryPathString);
17167                }
17168            }
17169        }
17170    }
17171
17172    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17173        // Enable the parent package
17174        mSettings.enableSystemPackageLPw(pkg.packageName);
17175        // Enable the child packages
17176        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17177        for (int i = 0; i < childCount; i++) {
17178            PackageParser.Package childPkg = pkg.childPackages.get(i);
17179            mSettings.enableSystemPackageLPw(childPkg.packageName);
17180        }
17181    }
17182
17183    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17184            PackageParser.Package newPkg) {
17185        // Disable the parent package (parent always replaced)
17186        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17187        // Disable the child packages
17188        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17189        for (int i = 0; i < childCount; i++) {
17190            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17191            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17192            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17193        }
17194        return disabled;
17195    }
17196
17197    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17198            String installerPackageName) {
17199        // Enable the parent package
17200        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17201        // Enable the child packages
17202        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17203        for (int i = 0; i < childCount; i++) {
17204            PackageParser.Package childPkg = pkg.childPackages.get(i);
17205            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17206        }
17207    }
17208
17209    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17210        // Collect all used permissions in the UID
17211        ArraySet<String> usedPermissions = new ArraySet<>();
17212        final int packageCount = su.packages.size();
17213        for (int i = 0; i < packageCount; i++) {
17214            PackageSetting ps = su.packages.valueAt(i);
17215            if (ps.pkg == null) {
17216                continue;
17217            }
17218            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17219            for (int j = 0; j < requestedPermCount; j++) {
17220                String permission = ps.pkg.requestedPermissions.get(j);
17221                BasePermission bp = mSettings.mPermissions.get(permission);
17222                if (bp != null) {
17223                    usedPermissions.add(permission);
17224                }
17225            }
17226        }
17227
17228        PermissionsState permissionsState = su.getPermissionsState();
17229        // Prune install permissions
17230        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17231        final int installPermCount = installPermStates.size();
17232        for (int i = installPermCount - 1; i >= 0;  i--) {
17233            PermissionState permissionState = installPermStates.get(i);
17234            if (!usedPermissions.contains(permissionState.getName())) {
17235                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17236                if (bp != null) {
17237                    permissionsState.revokeInstallPermission(bp);
17238                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17239                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17240                }
17241            }
17242        }
17243
17244        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17245
17246        // Prune runtime permissions
17247        for (int userId : allUserIds) {
17248            List<PermissionState> runtimePermStates = permissionsState
17249                    .getRuntimePermissionStates(userId);
17250            final int runtimePermCount = runtimePermStates.size();
17251            for (int i = runtimePermCount - 1; i >= 0; i--) {
17252                PermissionState permissionState = runtimePermStates.get(i);
17253                if (!usedPermissions.contains(permissionState.getName())) {
17254                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17255                    if (bp != null) {
17256                        permissionsState.revokeRuntimePermission(bp, userId);
17257                        permissionsState.updatePermissionFlags(bp, userId,
17258                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17259                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17260                                runtimePermissionChangedUserIds, userId);
17261                    }
17262                }
17263            }
17264        }
17265
17266        return runtimePermissionChangedUserIds;
17267    }
17268
17269    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17270            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17271        // Update the parent package setting
17272        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17273                res, user, installReason);
17274        // Update the child packages setting
17275        final int childCount = (newPackage.childPackages != null)
17276                ? newPackage.childPackages.size() : 0;
17277        for (int i = 0; i < childCount; i++) {
17278            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17279            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17280            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17281                    childRes.origUsers, childRes, user, installReason);
17282        }
17283    }
17284
17285    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17286            String installerPackageName, int[] allUsers, int[] installedForUsers,
17287            PackageInstalledInfo res, UserHandle user, int installReason) {
17288        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17289
17290        String pkgName = newPackage.packageName;
17291        synchronized (mPackages) {
17292            //write settings. the installStatus will be incomplete at this stage.
17293            //note that the new package setting would have already been
17294            //added to mPackages. It hasn't been persisted yet.
17295            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17296            // TODO: Remove this write? It's also written at the end of this method
17297            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17298            mSettings.writeLPr();
17299            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17300        }
17301
17302        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17303        synchronized (mPackages) {
17304            updatePermissionsLPw(newPackage.packageName, newPackage,
17305                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17306                            ? UPDATE_PERMISSIONS_ALL : 0));
17307            // For system-bundled packages, we assume that installing an upgraded version
17308            // of the package implies that the user actually wants to run that new code,
17309            // so we enable the package.
17310            PackageSetting ps = mSettings.mPackages.get(pkgName);
17311            final int userId = user.getIdentifier();
17312            if (ps != null) {
17313                if (isSystemApp(newPackage)) {
17314                    if (DEBUG_INSTALL) {
17315                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17316                    }
17317                    // Enable system package for requested users
17318                    if (res.origUsers != null) {
17319                        for (int origUserId : res.origUsers) {
17320                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17321                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17322                                        origUserId, installerPackageName);
17323                            }
17324                        }
17325                    }
17326                    // Also convey the prior install/uninstall state
17327                    if (allUsers != null && installedForUsers != null) {
17328                        for (int currentUserId : allUsers) {
17329                            final boolean installed = ArrayUtils.contains(
17330                                    installedForUsers, currentUserId);
17331                            if (DEBUG_INSTALL) {
17332                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17333                            }
17334                            ps.setInstalled(installed, currentUserId);
17335                        }
17336                        // these install state changes will be persisted in the
17337                        // upcoming call to mSettings.writeLPr().
17338                    }
17339                }
17340                // It's implied that when a user requests installation, they want the app to be
17341                // installed and enabled.
17342                if (userId != UserHandle.USER_ALL) {
17343                    ps.setInstalled(true, userId);
17344                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17345                }
17346
17347                // When replacing an existing package, preserve the original install reason for all
17348                // users that had the package installed before.
17349                final Set<Integer> previousUserIds = new ArraySet<>();
17350                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17351                    final int installReasonCount = res.removedInfo.installReasons.size();
17352                    for (int i = 0; i < installReasonCount; i++) {
17353                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17354                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17355                        ps.setInstallReason(previousInstallReason, previousUserId);
17356                        previousUserIds.add(previousUserId);
17357                    }
17358                }
17359
17360                // Set install reason for users that are having the package newly installed.
17361                if (userId == UserHandle.USER_ALL) {
17362                    for (int currentUserId : sUserManager.getUserIds()) {
17363                        if (!previousUserIds.contains(currentUserId)) {
17364                            ps.setInstallReason(installReason, currentUserId);
17365                        }
17366                    }
17367                } else if (!previousUserIds.contains(userId)) {
17368                    ps.setInstallReason(installReason, userId);
17369                }
17370                mSettings.writeKernelMappingLPr(ps);
17371            }
17372            res.name = pkgName;
17373            res.uid = newPackage.applicationInfo.uid;
17374            res.pkg = newPackage;
17375            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17376            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17377            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17378            //to update install status
17379            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17380            mSettings.writeLPr();
17381            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17382        }
17383
17384        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17385    }
17386
17387    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17388        try {
17389            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17390            installPackageLI(args, res);
17391        } finally {
17392            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17393        }
17394    }
17395
17396    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17397        final int installFlags = args.installFlags;
17398        final String installerPackageName = args.installerPackageName;
17399        final String volumeUuid = args.volumeUuid;
17400        final File tmpPackageFile = new File(args.getCodePath());
17401        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17402        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17403                || (args.volumeUuid != null));
17404        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17405        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17406        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17407        boolean replace = false;
17408        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17409        if (args.move != null) {
17410            // moving a complete application; perform an initial scan on the new install location
17411            scanFlags |= SCAN_INITIAL;
17412        }
17413        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17414            scanFlags |= SCAN_DONT_KILL_APP;
17415        }
17416        if (instantApp) {
17417            scanFlags |= SCAN_AS_INSTANT_APP;
17418        }
17419        if (fullApp) {
17420            scanFlags |= SCAN_AS_FULL_APP;
17421        }
17422
17423        // Result object to be returned
17424        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17425
17426        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17427
17428        // Sanity check
17429        if (instantApp && (forwardLocked || onExternal)) {
17430            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17431                    + " external=" + onExternal);
17432            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17433            return;
17434        }
17435
17436        // Retrieve PackageSettings and parse package
17437        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17438                | PackageParser.PARSE_ENFORCE_CODE
17439                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17440                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17441                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17442                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17443        PackageParser pp = new PackageParser();
17444        pp.setSeparateProcesses(mSeparateProcesses);
17445        pp.setDisplayMetrics(mMetrics);
17446        pp.setCallback(mPackageParserCallback);
17447
17448        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17449        final PackageParser.Package pkg;
17450        try {
17451            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17452        } catch (PackageParserException e) {
17453            res.setError("Failed parse during installPackageLI", e);
17454            return;
17455        } finally {
17456            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17457        }
17458
17459        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17460        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17461            Slog.w(TAG, "Instant app package " + pkg.packageName
17462                    + " does not target O, this will be a fatal error.");
17463            // STOPSHIP: Make this a fatal error
17464            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
17465        }
17466        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17467            Slog.w(TAG, "Instant app package " + pkg.packageName
17468                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
17469            // STOPSHIP: Make this a fatal error
17470            pkg.applicationInfo.targetSandboxVersion = 2;
17471        }
17472
17473        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17474            // Static shared libraries have synthetic package names
17475            renameStaticSharedLibraryPackage(pkg);
17476
17477            // No static shared libs on external storage
17478            if (onExternal) {
17479                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17480                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17481                        "Packages declaring static-shared libs cannot be updated");
17482                return;
17483            }
17484        }
17485
17486        // If we are installing a clustered package add results for the children
17487        if (pkg.childPackages != null) {
17488            synchronized (mPackages) {
17489                final int childCount = pkg.childPackages.size();
17490                for (int i = 0; i < childCount; i++) {
17491                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17492                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17493                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17494                    childRes.pkg = childPkg;
17495                    childRes.name = childPkg.packageName;
17496                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17497                    if (childPs != null) {
17498                        childRes.origUsers = childPs.queryInstalledUsers(
17499                                sUserManager.getUserIds(), true);
17500                    }
17501                    if ((mPackages.containsKey(childPkg.packageName))) {
17502                        childRes.removedInfo = new PackageRemovedInfo(this);
17503                        childRes.removedInfo.removedPackage = childPkg.packageName;
17504                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17505                    }
17506                    if (res.addedChildPackages == null) {
17507                        res.addedChildPackages = new ArrayMap<>();
17508                    }
17509                    res.addedChildPackages.put(childPkg.packageName, childRes);
17510                }
17511            }
17512        }
17513
17514        // If package doesn't declare API override, mark that we have an install
17515        // time CPU ABI override.
17516        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17517            pkg.cpuAbiOverride = args.abiOverride;
17518        }
17519
17520        String pkgName = res.name = pkg.packageName;
17521        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17522            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17523                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17524                return;
17525            }
17526        }
17527
17528        try {
17529            // either use what we've been given or parse directly from the APK
17530            if (args.certificates != null) {
17531                try {
17532                    PackageParser.populateCertificates(pkg, args.certificates);
17533                } catch (PackageParserException e) {
17534                    // there was something wrong with the certificates we were given;
17535                    // try to pull them from the APK
17536                    PackageParser.collectCertificates(pkg, parseFlags);
17537                }
17538            } else {
17539                PackageParser.collectCertificates(pkg, parseFlags);
17540            }
17541        } catch (PackageParserException e) {
17542            res.setError("Failed collect during installPackageLI", e);
17543            return;
17544        }
17545
17546        // Get rid of all references to package scan path via parser.
17547        pp = null;
17548        String oldCodePath = null;
17549        boolean systemApp = false;
17550        synchronized (mPackages) {
17551            // Check if installing already existing package
17552            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17553                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17554                if (pkg.mOriginalPackages != null
17555                        && pkg.mOriginalPackages.contains(oldName)
17556                        && mPackages.containsKey(oldName)) {
17557                    // This package is derived from an original package,
17558                    // and this device has been updating from that original
17559                    // name.  We must continue using the original name, so
17560                    // rename the new package here.
17561                    pkg.setPackageName(oldName);
17562                    pkgName = pkg.packageName;
17563                    replace = true;
17564                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17565                            + oldName + " pkgName=" + pkgName);
17566                } else if (mPackages.containsKey(pkgName)) {
17567                    // This package, under its official name, already exists
17568                    // on the device; we should replace it.
17569                    replace = true;
17570                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17571                }
17572
17573                // Child packages are installed through the parent package
17574                if (pkg.parentPackage != null) {
17575                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17576                            "Package " + pkg.packageName + " is child of package "
17577                                    + pkg.parentPackage.parentPackage + ". Child packages "
17578                                    + "can be updated only through the parent package.");
17579                    return;
17580                }
17581
17582                if (replace) {
17583                    // Prevent apps opting out from runtime permissions
17584                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17585                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17586                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17587                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17588                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17589                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17590                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17591                                        + " doesn't support runtime permissions but the old"
17592                                        + " target SDK " + oldTargetSdk + " does.");
17593                        return;
17594                    }
17595                    // Prevent apps from downgrading their targetSandbox.
17596                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17597                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17598                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17599                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17600                                "Package " + pkg.packageName + " new target sandbox "
17601                                + newTargetSandbox + " is incompatible with the previous value of"
17602                                + oldTargetSandbox + ".");
17603                        return;
17604                    }
17605
17606                    // Prevent installing of child packages
17607                    if (oldPackage.parentPackage != null) {
17608                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17609                                "Package " + pkg.packageName + " is child of package "
17610                                        + oldPackage.parentPackage + ". Child packages "
17611                                        + "can be updated only through the parent package.");
17612                        return;
17613                    }
17614                }
17615            }
17616
17617            PackageSetting ps = mSettings.mPackages.get(pkgName);
17618            if (ps != null) {
17619                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17620
17621                // Static shared libs have same package with different versions where
17622                // we internally use a synthetic package name to allow multiple versions
17623                // of the same package, therefore we need to compare signatures against
17624                // the package setting for the latest library version.
17625                PackageSetting signatureCheckPs = ps;
17626                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17627                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17628                    if (libraryEntry != null) {
17629                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17630                    }
17631                }
17632
17633                // Quick sanity check that we're signed correctly if updating;
17634                // we'll check this again later when scanning, but we want to
17635                // bail early here before tripping over redefined permissions.
17636                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17637                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17638                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17639                                + pkg.packageName + " upgrade keys do not match the "
17640                                + "previously installed version");
17641                        return;
17642                    }
17643                } else {
17644                    try {
17645                        verifySignaturesLP(signatureCheckPs, pkg);
17646                    } catch (PackageManagerException e) {
17647                        res.setError(e.error, e.getMessage());
17648                        return;
17649                    }
17650                }
17651
17652                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17653                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17654                    systemApp = (ps.pkg.applicationInfo.flags &
17655                            ApplicationInfo.FLAG_SYSTEM) != 0;
17656                }
17657                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17658            }
17659
17660            int N = pkg.permissions.size();
17661            for (int i = N-1; i >= 0; i--) {
17662                PackageParser.Permission perm = pkg.permissions.get(i);
17663                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
17664
17665                // Don't allow anyone but the system to define ephemeral permissions.
17666                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
17667                        && !systemApp) {
17668                    Slog.w(TAG, "Non-System package " + pkg.packageName
17669                            + " attempting to delcare ephemeral permission "
17670                            + perm.info.name + "; Removing ephemeral.");
17671                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
17672                }
17673                // Check whether the newly-scanned package wants to define an already-defined perm
17674                if (bp != null) {
17675                    // If the defining package is signed with our cert, it's okay.  This
17676                    // also includes the "updating the same package" case, of course.
17677                    // "updating same package" could also involve key-rotation.
17678                    final boolean sigsOk;
17679                    if (bp.sourcePackage.equals(pkg.packageName)
17680                            && (bp.packageSetting instanceof PackageSetting)
17681                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
17682                                    scanFlags))) {
17683                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
17684                    } else {
17685                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
17686                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17687                    }
17688                    if (!sigsOk) {
17689                        // If the owning package is the system itself, we log but allow
17690                        // install to proceed; we fail the install on all other permission
17691                        // redefinitions.
17692                        if (!bp.sourcePackage.equals("android")) {
17693                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17694                                    + pkg.packageName + " attempting to redeclare permission "
17695                                    + perm.info.name + " already owned by " + bp.sourcePackage);
17696                            res.origPermission = perm.info.name;
17697                            res.origPackage = bp.sourcePackage;
17698                            return;
17699                        } else {
17700                            Slog.w(TAG, "Package " + pkg.packageName
17701                                    + " attempting to redeclare system permission "
17702                                    + perm.info.name + "; ignoring new declaration");
17703                            pkg.permissions.remove(i);
17704                        }
17705                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17706                        // Prevent apps to change protection level to dangerous from any other
17707                        // type as this would allow a privilege escalation where an app adds a
17708                        // normal/signature permission in other app's group and later redefines
17709                        // it as dangerous leading to the group auto-grant.
17710                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17711                                == PermissionInfo.PROTECTION_DANGEROUS) {
17712                            if (bp != null && !bp.isRuntime()) {
17713                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17714                                        + "non-runtime permission " + perm.info.name
17715                                        + " to runtime; keeping old protection level");
17716                                perm.info.protectionLevel = bp.protectionLevel;
17717                            }
17718                        }
17719                    }
17720                }
17721            }
17722        }
17723
17724        if (systemApp) {
17725            if (onExternal) {
17726                // Abort update; system app can't be replaced with app on sdcard
17727                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17728                        "Cannot install updates to system apps on sdcard");
17729                return;
17730            } else if (instantApp) {
17731                // Abort update; system app can't be replaced with an instant app
17732                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17733                        "Cannot update a system app with an instant app");
17734                return;
17735            }
17736        }
17737
17738        if (args.move != null) {
17739            // We did an in-place move, so dex is ready to roll
17740            scanFlags |= SCAN_NO_DEX;
17741            scanFlags |= SCAN_MOVE;
17742
17743            synchronized (mPackages) {
17744                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17745                if (ps == null) {
17746                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17747                            "Missing settings for moved package " + pkgName);
17748                }
17749
17750                // We moved the entire application as-is, so bring over the
17751                // previously derived ABI information.
17752                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17753                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17754            }
17755
17756        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17757            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17758            scanFlags |= SCAN_NO_DEX;
17759
17760            try {
17761                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17762                    args.abiOverride : pkg.cpuAbiOverride);
17763                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17764                        true /*extractLibs*/, mAppLib32InstallDir);
17765            } catch (PackageManagerException pme) {
17766                Slog.e(TAG, "Error deriving application ABI", pme);
17767                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17768                return;
17769            }
17770
17771            // Shared libraries for the package need to be updated.
17772            synchronized (mPackages) {
17773                try {
17774                    updateSharedLibrariesLPr(pkg, null);
17775                } catch (PackageManagerException e) {
17776                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17777                }
17778            }
17779
17780            // dexopt can take some time to complete, so, for instant apps, we skip this
17781            // step during installation. Instead, we'll take extra time the first time the
17782            // instant app starts. It's preferred to do it this way to provide continuous
17783            // progress to the user instead of mysteriously blocking somewhere in the
17784            // middle of running an instant app.
17785            if (!instantApp) {
17786                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17787                // Do not run PackageDexOptimizer through the local performDexOpt
17788                // method because `pkg` may not be in `mPackages` yet.
17789                //
17790                // Also, don't fail application installs if the dexopt step fails.
17791                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17792                        null /* instructionSets */, false /* checkProfiles */,
17793                        getCompilerFilterForReason(REASON_INSTALL),
17794                        getOrCreateCompilerPackageStats(pkg),
17795                        mDexManager.isUsedByOtherApps(pkg.packageName));
17796                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17797            }
17798
17799            // Notify BackgroundDexOptService that the package has been changed.
17800            // If this is an update of a package which used to fail to compile,
17801            // BDOS will remove it from its blacklist.
17802            // TODO: Layering violation
17803            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17804        }
17805
17806        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17807            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17808            return;
17809        }
17810
17811        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17812
17813        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17814                "installPackageLI")) {
17815            if (replace) {
17816                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17817                    // Static libs have a synthetic package name containing the version
17818                    // and cannot be updated as an update would get a new package name,
17819                    // unless this is the exact same version code which is useful for
17820                    // development.
17821                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17822                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17823                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17824                                + "static-shared libs cannot be updated");
17825                        return;
17826                    }
17827                }
17828                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17829                        installerPackageName, res, args.installReason);
17830            } else {
17831                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17832                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17833            }
17834        }
17835
17836        synchronized (mPackages) {
17837            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17838            if (ps != null) {
17839                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17840                ps.setUpdateAvailable(false /*updateAvailable*/);
17841            }
17842
17843            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17844            for (int i = 0; i < childCount; i++) {
17845                PackageParser.Package childPkg = pkg.childPackages.get(i);
17846                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17847                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17848                if (childPs != null) {
17849                    childRes.newUsers = childPs.queryInstalledUsers(
17850                            sUserManager.getUserIds(), true);
17851                }
17852            }
17853
17854            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17855                updateSequenceNumberLP(pkgName, res.newUsers);
17856                updateInstantAppInstallerLocked(pkgName);
17857            }
17858        }
17859    }
17860
17861    private void startIntentFilterVerifications(int userId, boolean replacing,
17862            PackageParser.Package pkg) {
17863        if (mIntentFilterVerifierComponent == null) {
17864            Slog.w(TAG, "No IntentFilter verification will not be done as "
17865                    + "there is no IntentFilterVerifier available!");
17866            return;
17867        }
17868
17869        final int verifierUid = getPackageUid(
17870                mIntentFilterVerifierComponent.getPackageName(),
17871                MATCH_DEBUG_TRIAGED_MISSING,
17872                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17873
17874        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17875        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17876        mHandler.sendMessage(msg);
17877
17878        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17879        for (int i = 0; i < childCount; i++) {
17880            PackageParser.Package childPkg = pkg.childPackages.get(i);
17881            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17882            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17883            mHandler.sendMessage(msg);
17884        }
17885    }
17886
17887    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17888            PackageParser.Package pkg) {
17889        int size = pkg.activities.size();
17890        if (size == 0) {
17891            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17892                    "No activity, so no need to verify any IntentFilter!");
17893            return;
17894        }
17895
17896        final boolean hasDomainURLs = hasDomainURLs(pkg);
17897        if (!hasDomainURLs) {
17898            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17899                    "No domain URLs, so no need to verify any IntentFilter!");
17900            return;
17901        }
17902
17903        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17904                + " if any IntentFilter from the " + size
17905                + " Activities needs verification ...");
17906
17907        int count = 0;
17908        final String packageName = pkg.packageName;
17909
17910        synchronized (mPackages) {
17911            // If this is a new install and we see that we've already run verification for this
17912            // package, we have nothing to do: it means the state was restored from backup.
17913            if (!replacing) {
17914                IntentFilterVerificationInfo ivi =
17915                        mSettings.getIntentFilterVerificationLPr(packageName);
17916                if (ivi != null) {
17917                    if (DEBUG_DOMAIN_VERIFICATION) {
17918                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17919                                + ivi.getStatusString());
17920                    }
17921                    return;
17922                }
17923            }
17924
17925            // If any filters need to be verified, then all need to be.
17926            boolean needToVerify = false;
17927            for (PackageParser.Activity a : pkg.activities) {
17928                for (ActivityIntentInfo filter : a.intents) {
17929                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17930                        if (DEBUG_DOMAIN_VERIFICATION) {
17931                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17932                        }
17933                        needToVerify = true;
17934                        break;
17935                    }
17936                }
17937            }
17938
17939            if (needToVerify) {
17940                final int verificationId = mIntentFilterVerificationToken++;
17941                for (PackageParser.Activity a : pkg.activities) {
17942                    for (ActivityIntentInfo filter : a.intents) {
17943                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17944                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17945                                    "Verification needed for IntentFilter:" + filter.toString());
17946                            mIntentFilterVerifier.addOneIntentFilterVerification(
17947                                    verifierUid, userId, verificationId, filter, packageName);
17948                            count++;
17949                        }
17950                    }
17951                }
17952            }
17953        }
17954
17955        if (count > 0) {
17956            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17957                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17958                    +  " for userId:" + userId);
17959            mIntentFilterVerifier.startVerifications(userId);
17960        } else {
17961            if (DEBUG_DOMAIN_VERIFICATION) {
17962                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17963            }
17964        }
17965    }
17966
17967    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17968        final ComponentName cn  = filter.activity.getComponentName();
17969        final String packageName = cn.getPackageName();
17970
17971        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17972                packageName);
17973        if (ivi == null) {
17974            return true;
17975        }
17976        int status = ivi.getStatus();
17977        switch (status) {
17978            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17979            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17980                return true;
17981
17982            default:
17983                // Nothing to do
17984                return false;
17985        }
17986    }
17987
17988    private static boolean isMultiArch(ApplicationInfo info) {
17989        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17990    }
17991
17992    private static boolean isExternal(PackageParser.Package pkg) {
17993        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17994    }
17995
17996    private static boolean isExternal(PackageSetting ps) {
17997        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17998    }
17999
18000    private static boolean isSystemApp(PackageParser.Package pkg) {
18001        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18002    }
18003
18004    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18005        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18006    }
18007
18008    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18009        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18010    }
18011
18012    private static boolean isSystemApp(PackageSetting ps) {
18013        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18014    }
18015
18016    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18017        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18018    }
18019
18020    private int packageFlagsToInstallFlags(PackageSetting ps) {
18021        int installFlags = 0;
18022        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18023            // This existing package was an external ASEC install when we have
18024            // the external flag without a UUID
18025            installFlags |= PackageManager.INSTALL_EXTERNAL;
18026        }
18027        if (ps.isForwardLocked()) {
18028            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18029        }
18030        return installFlags;
18031    }
18032
18033    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18034        if (isExternal(pkg)) {
18035            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18036                return StorageManager.UUID_PRIMARY_PHYSICAL;
18037            } else {
18038                return pkg.volumeUuid;
18039            }
18040        } else {
18041            return StorageManager.UUID_PRIVATE_INTERNAL;
18042        }
18043    }
18044
18045    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18046        if (isExternal(pkg)) {
18047            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18048                return mSettings.getExternalVersion();
18049            } else {
18050                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18051            }
18052        } else {
18053            return mSettings.getInternalVersion();
18054        }
18055    }
18056
18057    private void deleteTempPackageFiles() {
18058        final FilenameFilter filter = new FilenameFilter() {
18059            public boolean accept(File dir, String name) {
18060                return name.startsWith("vmdl") && name.endsWith(".tmp");
18061            }
18062        };
18063        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18064            file.delete();
18065        }
18066    }
18067
18068    @Override
18069    public void deletePackageAsUser(String packageName, int versionCode,
18070            IPackageDeleteObserver observer, int userId, int flags) {
18071        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18072                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18073    }
18074
18075    @Override
18076    public void deletePackageVersioned(VersionedPackage versionedPackage,
18077            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18078        mContext.enforceCallingOrSelfPermission(
18079                android.Manifest.permission.DELETE_PACKAGES, null);
18080        Preconditions.checkNotNull(versionedPackage);
18081        Preconditions.checkNotNull(observer);
18082        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18083                PackageManager.VERSION_CODE_HIGHEST,
18084                Integer.MAX_VALUE, "versionCode must be >= -1");
18085
18086        final String packageName = versionedPackage.getPackageName();
18087        final int versionCode = versionedPackage.getVersionCode();
18088        final String internalPackageName;
18089        synchronized (mPackages) {
18090            // Normalize package name to handle renamed packages and static libs
18091            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18092                    versionedPackage.getVersionCode());
18093        }
18094
18095        final int uid = Binder.getCallingUid();
18096        if (!isOrphaned(internalPackageName)
18097                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18098            try {
18099                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18100                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18101                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18102                observer.onUserActionRequired(intent);
18103            } catch (RemoteException re) {
18104            }
18105            return;
18106        }
18107        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18108        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18109        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18110            mContext.enforceCallingOrSelfPermission(
18111                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18112                    "deletePackage for user " + userId);
18113        }
18114
18115        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18116            try {
18117                observer.onPackageDeleted(packageName,
18118                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18119            } catch (RemoteException re) {
18120            }
18121            return;
18122        }
18123
18124        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18125            try {
18126                observer.onPackageDeleted(packageName,
18127                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18128            } catch (RemoteException re) {
18129            }
18130            return;
18131        }
18132
18133        if (DEBUG_REMOVE) {
18134            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18135                    + " deleteAllUsers: " + deleteAllUsers + " version="
18136                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18137                    ? "VERSION_CODE_HIGHEST" : versionCode));
18138        }
18139        // Queue up an async operation since the package deletion may take a little while.
18140        mHandler.post(new Runnable() {
18141            public void run() {
18142                mHandler.removeCallbacks(this);
18143                int returnCode;
18144                if (!deleteAllUsers) {
18145                    returnCode = deletePackageX(internalPackageName, versionCode,
18146                            userId, deleteFlags);
18147                } else {
18148                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
18149                            internalPackageName, users);
18150                    // If nobody is blocking uninstall, proceed with delete for all users
18151                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18152                        returnCode = deletePackageX(internalPackageName, versionCode,
18153                                userId, deleteFlags);
18154                    } else {
18155                        // Otherwise uninstall individually for users with blockUninstalls=false
18156                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18157                        for (int userId : users) {
18158                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18159                                returnCode = deletePackageX(internalPackageName, versionCode,
18160                                        userId, userFlags);
18161                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18162                                    Slog.w(TAG, "Package delete failed for user " + userId
18163                                            + ", returnCode " + returnCode);
18164                                }
18165                            }
18166                        }
18167                        // The app has only been marked uninstalled for certain users.
18168                        // We still need to report that delete was blocked
18169                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18170                    }
18171                }
18172                try {
18173                    observer.onPackageDeleted(packageName, returnCode, null);
18174                } catch (RemoteException e) {
18175                    Log.i(TAG, "Observer no longer exists.");
18176                } //end catch
18177            } //end run
18178        });
18179    }
18180
18181    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18182        if (pkg.staticSharedLibName != null) {
18183            return pkg.manifestPackageName;
18184        }
18185        return pkg.packageName;
18186    }
18187
18188    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18189        // Handle renamed packages
18190        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18191        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18192
18193        // Is this a static library?
18194        SparseArray<SharedLibraryEntry> versionedLib =
18195                mStaticLibsByDeclaringPackage.get(packageName);
18196        if (versionedLib == null || versionedLib.size() <= 0) {
18197            return packageName;
18198        }
18199
18200        // Figure out which lib versions the caller can see
18201        SparseIntArray versionsCallerCanSee = null;
18202        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18203        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18204                && callingAppId != Process.ROOT_UID) {
18205            versionsCallerCanSee = new SparseIntArray();
18206            String libName = versionedLib.valueAt(0).info.getName();
18207            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18208            if (uidPackages != null) {
18209                for (String uidPackage : uidPackages) {
18210                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18211                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18212                    if (libIdx >= 0) {
18213                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18214                        versionsCallerCanSee.append(libVersion, libVersion);
18215                    }
18216                }
18217            }
18218        }
18219
18220        // Caller can see nothing - done
18221        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18222            return packageName;
18223        }
18224
18225        // Find the version the caller can see and the app version code
18226        SharedLibraryEntry highestVersion = null;
18227        final int versionCount = versionedLib.size();
18228        for (int i = 0; i < versionCount; i++) {
18229            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18230            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18231                    libEntry.info.getVersion()) < 0) {
18232                continue;
18233            }
18234            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18235            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18236                if (libVersionCode == versionCode) {
18237                    return libEntry.apk;
18238                }
18239            } else if (highestVersion == null) {
18240                highestVersion = libEntry;
18241            } else if (libVersionCode  > highestVersion.info
18242                    .getDeclaringPackage().getVersionCode()) {
18243                highestVersion = libEntry;
18244            }
18245        }
18246
18247        if (highestVersion != null) {
18248            return highestVersion.apk;
18249        }
18250
18251        return packageName;
18252    }
18253
18254    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18255        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18256              || callingUid == Process.SYSTEM_UID) {
18257            return true;
18258        }
18259        final int callingUserId = UserHandle.getUserId(callingUid);
18260        // If the caller installed the pkgName, then allow it to silently uninstall.
18261        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18262            return true;
18263        }
18264
18265        // Allow package verifier to silently uninstall.
18266        if (mRequiredVerifierPackage != null &&
18267                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18268            return true;
18269        }
18270
18271        // Allow package uninstaller to silently uninstall.
18272        if (mRequiredUninstallerPackage != null &&
18273                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18274            return true;
18275        }
18276
18277        // Allow storage manager to silently uninstall.
18278        if (mStorageManagerPackage != null &&
18279                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18280            return true;
18281        }
18282        return false;
18283    }
18284
18285    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18286        int[] result = EMPTY_INT_ARRAY;
18287        for (int userId : userIds) {
18288            if (getBlockUninstallForUser(packageName, userId)) {
18289                result = ArrayUtils.appendInt(result, userId);
18290            }
18291        }
18292        return result;
18293    }
18294
18295    @Override
18296    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18297        final int callingUid = Binder.getCallingUid();
18298        if (getInstantAppPackageName(callingUid) != null
18299                && !isCallerSameApp(packageName, callingUid)) {
18300            return false;
18301        }
18302        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18303    }
18304
18305    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18306        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18307                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18308        try {
18309            if (dpm != null) {
18310                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18311                        /* callingUserOnly =*/ false);
18312                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18313                        : deviceOwnerComponentName.getPackageName();
18314                // Does the package contains the device owner?
18315                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18316                // this check is probably not needed, since DO should be registered as a device
18317                // admin on some user too. (Original bug for this: b/17657954)
18318                if (packageName.equals(deviceOwnerPackageName)) {
18319                    return true;
18320                }
18321                // Does it contain a device admin for any user?
18322                int[] users;
18323                if (userId == UserHandle.USER_ALL) {
18324                    users = sUserManager.getUserIds();
18325                } else {
18326                    users = new int[]{userId};
18327                }
18328                for (int i = 0; i < users.length; ++i) {
18329                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18330                        return true;
18331                    }
18332                }
18333            }
18334        } catch (RemoteException e) {
18335        }
18336        return false;
18337    }
18338
18339    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18340        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18341    }
18342
18343    /**
18344     *  This method is an internal method that could be get invoked either
18345     *  to delete an installed package or to clean up a failed installation.
18346     *  After deleting an installed package, a broadcast is sent to notify any
18347     *  listeners that the package has been removed. For cleaning up a failed
18348     *  installation, the broadcast is not necessary since the package's
18349     *  installation wouldn't have sent the initial broadcast either
18350     *  The key steps in deleting a package are
18351     *  deleting the package information in internal structures like mPackages,
18352     *  deleting the packages base directories through installd
18353     *  updating mSettings to reflect current status
18354     *  persisting settings for later use
18355     *  sending a broadcast if necessary
18356     */
18357    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18358        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18359        final boolean res;
18360
18361        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18362                ? UserHandle.USER_ALL : userId;
18363
18364        if (isPackageDeviceAdmin(packageName, removeUser)) {
18365            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18366            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18367        }
18368
18369        PackageSetting uninstalledPs = null;
18370        PackageParser.Package pkg = null;
18371
18372        // for the uninstall-updates case and restricted profiles, remember the per-
18373        // user handle installed state
18374        int[] allUsers;
18375        synchronized (mPackages) {
18376            uninstalledPs = mSettings.mPackages.get(packageName);
18377            if (uninstalledPs == null) {
18378                Slog.w(TAG, "Not removing non-existent package " + packageName);
18379                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18380            }
18381
18382            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18383                    && uninstalledPs.versionCode != versionCode) {
18384                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18385                        + uninstalledPs.versionCode + " != " + versionCode);
18386                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18387            }
18388
18389            // Static shared libs can be declared by any package, so let us not
18390            // allow removing a package if it provides a lib others depend on.
18391            pkg = mPackages.get(packageName);
18392
18393            allUsers = sUserManager.getUserIds();
18394
18395            if (pkg != null && pkg.staticSharedLibName != null) {
18396                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18397                        pkg.staticSharedLibVersion);
18398                if (libEntry != null) {
18399                    for (int currUserId : allUsers) {
18400                        if (userId != UserHandle.USER_ALL && userId != currUserId) {
18401                            continue;
18402                        }
18403                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18404                                libEntry.info, 0, currUserId);
18405                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18406                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18407                                    + " hosting lib " + libEntry.info.getName() + " version "
18408                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18409                                    + " for user " + currUserId);
18410                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18411                        }
18412                    }
18413                }
18414            }
18415
18416            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18417        }
18418
18419        final int freezeUser;
18420        if (isUpdatedSystemApp(uninstalledPs)
18421                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18422            // We're downgrading a system app, which will apply to all users, so
18423            // freeze them all during the downgrade
18424            freezeUser = UserHandle.USER_ALL;
18425        } else {
18426            freezeUser = removeUser;
18427        }
18428
18429        synchronized (mInstallLock) {
18430            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18431            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18432                    deleteFlags, "deletePackageX")) {
18433                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18434                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18435            }
18436            synchronized (mPackages) {
18437                if (res) {
18438                    if (pkg != null) {
18439                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18440                    }
18441                    updateSequenceNumberLP(packageName, info.removedUsers);
18442                    updateInstantAppInstallerLocked(packageName);
18443                }
18444            }
18445        }
18446
18447        if (res) {
18448            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18449            info.sendPackageRemovedBroadcasts(killApp);
18450            info.sendSystemPackageUpdatedBroadcasts();
18451            info.sendSystemPackageAppearedBroadcasts();
18452        }
18453        // Force a gc here.
18454        Runtime.getRuntime().gc();
18455        // Delete the resources here after sending the broadcast to let
18456        // other processes clean up before deleting resources.
18457        if (info.args != null) {
18458            synchronized (mInstallLock) {
18459                info.args.doPostDeleteLI(true);
18460            }
18461        }
18462
18463        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18464    }
18465
18466    static class PackageRemovedInfo {
18467        final PackageSender packageSender;
18468        String removedPackage;
18469        String installerPackageName;
18470        int uid = -1;
18471        int removedAppId = -1;
18472        int[] origUsers;
18473        int[] removedUsers = null;
18474        int[] broadcastUsers = null;
18475        SparseArray<Integer> installReasons;
18476        boolean isRemovedPackageSystemUpdate = false;
18477        boolean isUpdate;
18478        boolean dataRemoved;
18479        boolean removedForAllUsers;
18480        boolean isStaticSharedLib;
18481        // Clean up resources deleted packages.
18482        InstallArgs args = null;
18483        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18484        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18485
18486        PackageRemovedInfo(PackageSender packageSender) {
18487            this.packageSender = packageSender;
18488        }
18489
18490        void sendPackageRemovedBroadcasts(boolean killApp) {
18491            sendPackageRemovedBroadcastInternal(killApp);
18492            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18493            for (int i = 0; i < childCount; i++) {
18494                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18495                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18496            }
18497        }
18498
18499        void sendSystemPackageUpdatedBroadcasts() {
18500            if (isRemovedPackageSystemUpdate) {
18501                sendSystemPackageUpdatedBroadcastsInternal();
18502                final int childCount = (removedChildPackages != null)
18503                        ? removedChildPackages.size() : 0;
18504                for (int i = 0; i < childCount; i++) {
18505                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18506                    if (childInfo.isRemovedPackageSystemUpdate) {
18507                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18508                    }
18509                }
18510            }
18511        }
18512
18513        void sendSystemPackageAppearedBroadcasts() {
18514            final int packageCount = (appearedChildPackages != null)
18515                    ? appearedChildPackages.size() : 0;
18516            for (int i = 0; i < packageCount; i++) {
18517                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18518                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18519                    true, UserHandle.getAppId(installedInfo.uid),
18520                    installedInfo.newUsers);
18521            }
18522        }
18523
18524        private void sendSystemPackageUpdatedBroadcastsInternal() {
18525            Bundle extras = new Bundle(2);
18526            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18527            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18528            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18529                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18530            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18531                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18532            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18533                null, null, 0, removedPackage, null, null);
18534            if (installerPackageName != null) {
18535                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18536                        removedPackage, extras, 0 /*flags*/,
18537                        installerPackageName, null, null);
18538                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18539                        removedPackage, extras, 0 /*flags*/,
18540                        installerPackageName, null, null);
18541            }
18542        }
18543
18544        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18545            // Don't send static shared library removal broadcasts as these
18546            // libs are visible only the the apps that depend on them an one
18547            // cannot remove the library if it has a dependency.
18548            if (isStaticSharedLib) {
18549                return;
18550            }
18551            Bundle extras = new Bundle(2);
18552            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18553            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18554            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18555            if (isUpdate || isRemovedPackageSystemUpdate) {
18556                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18557            }
18558            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18559            if (removedPackage != null) {
18560                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18561                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18562                if (installerPackageName != null) {
18563                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18564                            removedPackage, extras, 0 /*flags*/,
18565                            installerPackageName, null, broadcastUsers);
18566                }
18567                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18568                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18569                        removedPackage, extras,
18570                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18571                        null, null, broadcastUsers);
18572                }
18573            }
18574            if (removedAppId >= 0) {
18575                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
18576                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
18577            }
18578        }
18579
18580        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18581            removedUsers = userIds;
18582            if (removedUsers == null) {
18583                broadcastUsers = null;
18584                return;
18585            }
18586
18587            broadcastUsers = EMPTY_INT_ARRAY;
18588            for (int i = userIds.length - 1; i >= 0; --i) {
18589                final int userId = userIds[i];
18590                if (deletedPackageSetting.getInstantApp(userId)) {
18591                    continue;
18592                }
18593                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18594            }
18595        }
18596    }
18597
18598    /*
18599     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18600     * flag is not set, the data directory is removed as well.
18601     * make sure this flag is set for partially installed apps. If not its meaningless to
18602     * delete a partially installed application.
18603     */
18604    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18605            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18606        String packageName = ps.name;
18607        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18608        // Retrieve object to delete permissions for shared user later on
18609        final PackageParser.Package deletedPkg;
18610        final PackageSetting deletedPs;
18611        // reader
18612        synchronized (mPackages) {
18613            deletedPkg = mPackages.get(packageName);
18614            deletedPs = mSettings.mPackages.get(packageName);
18615            if (outInfo != null) {
18616                outInfo.removedPackage = packageName;
18617                outInfo.installerPackageName = ps.installerPackageName;
18618                outInfo.isStaticSharedLib = deletedPkg != null
18619                        && deletedPkg.staticSharedLibName != null;
18620                outInfo.populateUsers(deletedPs == null ? null
18621                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18622            }
18623        }
18624
18625        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18626
18627        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18628            final PackageParser.Package resolvedPkg;
18629            if (deletedPkg != null) {
18630                resolvedPkg = deletedPkg;
18631            } else {
18632                // We don't have a parsed package when it lives on an ejected
18633                // adopted storage device, so fake something together
18634                resolvedPkg = new PackageParser.Package(ps.name);
18635                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18636            }
18637            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18638                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18639            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18640            if (outInfo != null) {
18641                outInfo.dataRemoved = true;
18642            }
18643            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18644        }
18645
18646        int removedAppId = -1;
18647
18648        // writer
18649        synchronized (mPackages) {
18650            boolean installedStateChanged = false;
18651            if (deletedPs != null) {
18652                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18653                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18654                    clearDefaultBrowserIfNeeded(packageName);
18655                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18656                    removedAppId = mSettings.removePackageLPw(packageName);
18657                    if (outInfo != null) {
18658                        outInfo.removedAppId = removedAppId;
18659                    }
18660                    updatePermissionsLPw(deletedPs.name, null, 0);
18661                    if (deletedPs.sharedUser != null) {
18662                        // Remove permissions associated with package. Since runtime
18663                        // permissions are per user we have to kill the removed package
18664                        // or packages running under the shared user of the removed
18665                        // package if revoking the permissions requested only by the removed
18666                        // package is successful and this causes a change in gids.
18667                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18668                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18669                                    userId);
18670                            if (userIdToKill == UserHandle.USER_ALL
18671                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18672                                // If gids changed for this user, kill all affected packages.
18673                                mHandler.post(new Runnable() {
18674                                    @Override
18675                                    public void run() {
18676                                        // This has to happen with no lock held.
18677                                        killApplication(deletedPs.name, deletedPs.appId,
18678                                                KILL_APP_REASON_GIDS_CHANGED);
18679                                    }
18680                                });
18681                                break;
18682                            }
18683                        }
18684                    }
18685                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18686                }
18687                // make sure to preserve per-user disabled state if this removal was just
18688                // a downgrade of a system app to the factory package
18689                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18690                    if (DEBUG_REMOVE) {
18691                        Slog.d(TAG, "Propagating install state across downgrade");
18692                    }
18693                    for (int userId : allUserHandles) {
18694                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18695                        if (DEBUG_REMOVE) {
18696                            Slog.d(TAG, "    user " + userId + " => " + installed);
18697                        }
18698                        if (installed != ps.getInstalled(userId)) {
18699                            installedStateChanged = true;
18700                        }
18701                        ps.setInstalled(installed, userId);
18702                    }
18703                }
18704            }
18705            // can downgrade to reader
18706            if (writeSettings) {
18707                // Save settings now
18708                mSettings.writeLPr();
18709            }
18710            if (installedStateChanged) {
18711                mSettings.writeKernelMappingLPr(ps);
18712            }
18713        }
18714        if (removedAppId != -1) {
18715            // A user ID was deleted here. Go through all users and remove it
18716            // from KeyStore.
18717            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18718        }
18719    }
18720
18721    static boolean locationIsPrivileged(File path) {
18722        try {
18723            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18724                    .getCanonicalPath();
18725            return path.getCanonicalPath().startsWith(privilegedAppDir);
18726        } catch (IOException e) {
18727            Slog.e(TAG, "Unable to access code path " + path);
18728        }
18729        return false;
18730    }
18731
18732    /*
18733     * Tries to delete system package.
18734     */
18735    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18736            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18737            boolean writeSettings) {
18738        if (deletedPs.parentPackageName != null) {
18739            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18740            return false;
18741        }
18742
18743        final boolean applyUserRestrictions
18744                = (allUserHandles != null) && (outInfo.origUsers != null);
18745        final PackageSetting disabledPs;
18746        // Confirm if the system package has been updated
18747        // An updated system app can be deleted. This will also have to restore
18748        // the system pkg from system partition
18749        // reader
18750        synchronized (mPackages) {
18751            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18752        }
18753
18754        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18755                + " disabledPs=" + disabledPs);
18756
18757        if (disabledPs == null) {
18758            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18759            return false;
18760        } else if (DEBUG_REMOVE) {
18761            Slog.d(TAG, "Deleting system pkg from data partition");
18762        }
18763
18764        if (DEBUG_REMOVE) {
18765            if (applyUserRestrictions) {
18766                Slog.d(TAG, "Remembering install states:");
18767                for (int userId : allUserHandles) {
18768                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18769                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18770                }
18771            }
18772        }
18773
18774        // Delete the updated package
18775        outInfo.isRemovedPackageSystemUpdate = true;
18776        if (outInfo.removedChildPackages != null) {
18777            final int childCount = (deletedPs.childPackageNames != null)
18778                    ? deletedPs.childPackageNames.size() : 0;
18779            for (int i = 0; i < childCount; i++) {
18780                String childPackageName = deletedPs.childPackageNames.get(i);
18781                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18782                        .contains(childPackageName)) {
18783                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18784                            childPackageName);
18785                    if (childInfo != null) {
18786                        childInfo.isRemovedPackageSystemUpdate = true;
18787                    }
18788                }
18789            }
18790        }
18791
18792        if (disabledPs.versionCode < deletedPs.versionCode) {
18793            // Delete data for downgrades
18794            flags &= ~PackageManager.DELETE_KEEP_DATA;
18795        } else {
18796            // Preserve data by setting flag
18797            flags |= PackageManager.DELETE_KEEP_DATA;
18798        }
18799
18800        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18801                outInfo, writeSettings, disabledPs.pkg);
18802        if (!ret) {
18803            return false;
18804        }
18805
18806        // writer
18807        synchronized (mPackages) {
18808            // Reinstate the old system package
18809            enableSystemPackageLPw(disabledPs.pkg);
18810            // Remove any native libraries from the upgraded package.
18811            removeNativeBinariesLI(deletedPs);
18812        }
18813
18814        // Install the system package
18815        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18816        int parseFlags = mDefParseFlags
18817                | PackageParser.PARSE_MUST_BE_APK
18818                | PackageParser.PARSE_IS_SYSTEM
18819                | PackageParser.PARSE_IS_SYSTEM_DIR;
18820        if (locationIsPrivileged(disabledPs.codePath)) {
18821            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18822        }
18823
18824        final PackageParser.Package newPkg;
18825        try {
18826            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
18827                0 /* currentTime */, null);
18828        } catch (PackageManagerException e) {
18829            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18830                    + e.getMessage());
18831            return false;
18832        }
18833
18834        try {
18835            // update shared libraries for the newly re-installed system package
18836            updateSharedLibrariesLPr(newPkg, null);
18837        } catch (PackageManagerException e) {
18838            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18839        }
18840
18841        prepareAppDataAfterInstallLIF(newPkg);
18842
18843        // writer
18844        synchronized (mPackages) {
18845            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18846
18847            // Propagate the permissions state as we do not want to drop on the floor
18848            // runtime permissions. The update permissions method below will take
18849            // care of removing obsolete permissions and grant install permissions.
18850            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
18851            updatePermissionsLPw(newPkg.packageName, newPkg,
18852                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18853
18854            if (applyUserRestrictions) {
18855                boolean installedStateChanged = false;
18856                if (DEBUG_REMOVE) {
18857                    Slog.d(TAG, "Propagating install state across reinstall");
18858                }
18859                for (int userId : allUserHandles) {
18860                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18861                    if (DEBUG_REMOVE) {
18862                        Slog.d(TAG, "    user " + userId + " => " + installed);
18863                    }
18864                    if (installed != ps.getInstalled(userId)) {
18865                        installedStateChanged = true;
18866                    }
18867                    ps.setInstalled(installed, userId);
18868
18869                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18870                }
18871                // Regardless of writeSettings we need to ensure that this restriction
18872                // state propagation is persisted
18873                mSettings.writeAllUsersPackageRestrictionsLPr();
18874                if (installedStateChanged) {
18875                    mSettings.writeKernelMappingLPr(ps);
18876                }
18877            }
18878            // can downgrade to reader here
18879            if (writeSettings) {
18880                mSettings.writeLPr();
18881            }
18882        }
18883        return true;
18884    }
18885
18886    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18887            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18888            PackageRemovedInfo outInfo, boolean writeSettings,
18889            PackageParser.Package replacingPackage) {
18890        synchronized (mPackages) {
18891            if (outInfo != null) {
18892                outInfo.uid = ps.appId;
18893            }
18894
18895            if (outInfo != null && outInfo.removedChildPackages != null) {
18896                final int childCount = (ps.childPackageNames != null)
18897                        ? ps.childPackageNames.size() : 0;
18898                for (int i = 0; i < childCount; i++) {
18899                    String childPackageName = ps.childPackageNames.get(i);
18900                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18901                    if (childPs == null) {
18902                        return false;
18903                    }
18904                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18905                            childPackageName);
18906                    if (childInfo != null) {
18907                        childInfo.uid = childPs.appId;
18908                    }
18909                }
18910            }
18911        }
18912
18913        // Delete package data from internal structures and also remove data if flag is set
18914        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18915
18916        // Delete the child packages data
18917        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18918        for (int i = 0; i < childCount; i++) {
18919            PackageSetting childPs;
18920            synchronized (mPackages) {
18921                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18922            }
18923            if (childPs != null) {
18924                PackageRemovedInfo childOutInfo = (outInfo != null
18925                        && outInfo.removedChildPackages != null)
18926                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18927                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18928                        && (replacingPackage != null
18929                        && !replacingPackage.hasChildPackage(childPs.name))
18930                        ? flags & ~DELETE_KEEP_DATA : flags;
18931                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18932                        deleteFlags, writeSettings);
18933            }
18934        }
18935
18936        // Delete application code and resources only for parent packages
18937        if (ps.parentPackageName == null) {
18938            if (deleteCodeAndResources && (outInfo != null)) {
18939                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18940                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18941                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18942            }
18943        }
18944
18945        return true;
18946    }
18947
18948    @Override
18949    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18950            int userId) {
18951        mContext.enforceCallingOrSelfPermission(
18952                android.Manifest.permission.DELETE_PACKAGES, null);
18953        synchronized (mPackages) {
18954            // Cannot block uninstall of static shared libs as they are
18955            // considered a part of the using app (emulating static linking).
18956            // Also static libs are installed always on internal storage.
18957            PackageParser.Package pkg = mPackages.get(packageName);
18958            if (pkg != null && pkg.staticSharedLibName != null) {
18959                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18960                        + " providing static shared library: " + pkg.staticSharedLibName);
18961                return false;
18962            }
18963            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18964            mSettings.writePackageRestrictionsLPr(userId);
18965        }
18966        return true;
18967    }
18968
18969    @Override
18970    public boolean getBlockUninstallForUser(String packageName, int userId) {
18971        synchronized (mPackages) {
18972            return mSettings.getBlockUninstallLPr(userId, packageName);
18973        }
18974    }
18975
18976    @Override
18977    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18978        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18979        synchronized (mPackages) {
18980            PackageSetting ps = mSettings.mPackages.get(packageName);
18981            if (ps == null) {
18982                Log.w(TAG, "Package doesn't exist: " + packageName);
18983                return false;
18984            }
18985            if (systemUserApp) {
18986                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18987            } else {
18988                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18989            }
18990            mSettings.writeLPr();
18991        }
18992        return true;
18993    }
18994
18995    /*
18996     * This method handles package deletion in general
18997     */
18998    private boolean deletePackageLIF(String packageName, UserHandle user,
18999            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19000            PackageRemovedInfo outInfo, boolean writeSettings,
19001            PackageParser.Package replacingPackage) {
19002        if (packageName == null) {
19003            Slog.w(TAG, "Attempt to delete null packageName.");
19004            return false;
19005        }
19006
19007        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19008
19009        PackageSetting ps;
19010        synchronized (mPackages) {
19011            ps = mSettings.mPackages.get(packageName);
19012            if (ps == null) {
19013                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19014                return false;
19015            }
19016
19017            if (ps.parentPackageName != null && (!isSystemApp(ps)
19018                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19019                if (DEBUG_REMOVE) {
19020                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19021                            + ((user == null) ? UserHandle.USER_ALL : user));
19022                }
19023                final int removedUserId = (user != null) ? user.getIdentifier()
19024                        : UserHandle.USER_ALL;
19025                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19026                    return false;
19027                }
19028                markPackageUninstalledForUserLPw(ps, user);
19029                scheduleWritePackageRestrictionsLocked(user);
19030                return true;
19031            }
19032        }
19033
19034        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19035                && user.getIdentifier() != UserHandle.USER_ALL)) {
19036            // The caller is asking that the package only be deleted for a single
19037            // user.  To do this, we just mark its uninstalled state and delete
19038            // its data. If this is a system app, we only allow this to happen if
19039            // they have set the special DELETE_SYSTEM_APP which requests different
19040            // semantics than normal for uninstalling system apps.
19041            markPackageUninstalledForUserLPw(ps, user);
19042
19043            if (!isSystemApp(ps)) {
19044                // Do not uninstall the APK if an app should be cached
19045                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19046                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19047                    // Other user still have this package installed, so all
19048                    // we need to do is clear this user's data and save that
19049                    // it is uninstalled.
19050                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19051                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19052                        return false;
19053                    }
19054                    scheduleWritePackageRestrictionsLocked(user);
19055                    return true;
19056                } else {
19057                    // We need to set it back to 'installed' so the uninstall
19058                    // broadcasts will be sent correctly.
19059                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19060                    ps.setInstalled(true, user.getIdentifier());
19061                    mSettings.writeKernelMappingLPr(ps);
19062                }
19063            } else {
19064                // This is a system app, so we assume that the
19065                // other users still have this package installed, so all
19066                // we need to do is clear this user's data and save that
19067                // it is uninstalled.
19068                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19069                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19070                    return false;
19071                }
19072                scheduleWritePackageRestrictionsLocked(user);
19073                return true;
19074            }
19075        }
19076
19077        // If we are deleting a composite package for all users, keep track
19078        // of result for each child.
19079        if (ps.childPackageNames != null && outInfo != null) {
19080            synchronized (mPackages) {
19081                final int childCount = ps.childPackageNames.size();
19082                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19083                for (int i = 0; i < childCount; i++) {
19084                    String childPackageName = ps.childPackageNames.get(i);
19085                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19086                    childInfo.removedPackage = childPackageName;
19087                    childInfo.installerPackageName = ps.installerPackageName;
19088                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19089                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19090                    if (childPs != null) {
19091                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19092                    }
19093                }
19094            }
19095        }
19096
19097        boolean ret = false;
19098        if (isSystemApp(ps)) {
19099            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19100            // When an updated system application is deleted we delete the existing resources
19101            // as well and fall back to existing code in system partition
19102            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19103        } else {
19104            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19105            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19106                    outInfo, writeSettings, replacingPackage);
19107        }
19108
19109        // Take a note whether we deleted the package for all users
19110        if (outInfo != null) {
19111            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19112            if (outInfo.removedChildPackages != null) {
19113                synchronized (mPackages) {
19114                    final int childCount = outInfo.removedChildPackages.size();
19115                    for (int i = 0; i < childCount; i++) {
19116                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19117                        if (childInfo != null) {
19118                            childInfo.removedForAllUsers = mPackages.get(
19119                                    childInfo.removedPackage) == null;
19120                        }
19121                    }
19122                }
19123            }
19124            // If we uninstalled an update to a system app there may be some
19125            // child packages that appeared as they are declared in the system
19126            // app but were not declared in the update.
19127            if (isSystemApp(ps)) {
19128                synchronized (mPackages) {
19129                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19130                    final int childCount = (updatedPs.childPackageNames != null)
19131                            ? updatedPs.childPackageNames.size() : 0;
19132                    for (int i = 0; i < childCount; i++) {
19133                        String childPackageName = updatedPs.childPackageNames.get(i);
19134                        if (outInfo.removedChildPackages == null
19135                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19136                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19137                            if (childPs == null) {
19138                                continue;
19139                            }
19140                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19141                            installRes.name = childPackageName;
19142                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19143                            installRes.pkg = mPackages.get(childPackageName);
19144                            installRes.uid = childPs.pkg.applicationInfo.uid;
19145                            if (outInfo.appearedChildPackages == null) {
19146                                outInfo.appearedChildPackages = new ArrayMap<>();
19147                            }
19148                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19149                        }
19150                    }
19151                }
19152            }
19153        }
19154
19155        return ret;
19156    }
19157
19158    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19159        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19160                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19161        for (int nextUserId : userIds) {
19162            if (DEBUG_REMOVE) {
19163                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19164            }
19165            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19166                    false /*installed*/,
19167                    true /*stopped*/,
19168                    true /*notLaunched*/,
19169                    false /*hidden*/,
19170                    false /*suspended*/,
19171                    false /*instantApp*/,
19172                    null /*lastDisableAppCaller*/,
19173                    null /*enabledComponents*/,
19174                    null /*disabledComponents*/,
19175                    ps.readUserState(nextUserId).domainVerificationStatus,
19176                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19177        }
19178        mSettings.writeKernelMappingLPr(ps);
19179    }
19180
19181    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19182            PackageRemovedInfo outInfo) {
19183        final PackageParser.Package pkg;
19184        synchronized (mPackages) {
19185            pkg = mPackages.get(ps.name);
19186        }
19187
19188        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19189                : new int[] {userId};
19190        for (int nextUserId : userIds) {
19191            if (DEBUG_REMOVE) {
19192                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19193                        + nextUserId);
19194            }
19195
19196            destroyAppDataLIF(pkg, userId,
19197                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19198            destroyAppProfilesLIF(pkg, userId);
19199            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19200            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19201            schedulePackageCleaning(ps.name, nextUserId, false);
19202            synchronized (mPackages) {
19203                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19204                    scheduleWritePackageRestrictionsLocked(nextUserId);
19205                }
19206                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19207            }
19208        }
19209
19210        if (outInfo != null) {
19211            outInfo.removedPackage = ps.name;
19212            outInfo.installerPackageName = ps.installerPackageName;
19213            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19214            outInfo.removedAppId = ps.appId;
19215            outInfo.removedUsers = userIds;
19216            outInfo.broadcastUsers = userIds;
19217        }
19218
19219        return true;
19220    }
19221
19222    private final class ClearStorageConnection implements ServiceConnection {
19223        IMediaContainerService mContainerService;
19224
19225        @Override
19226        public void onServiceConnected(ComponentName name, IBinder service) {
19227            synchronized (this) {
19228                mContainerService = IMediaContainerService.Stub
19229                        .asInterface(Binder.allowBlocking(service));
19230                notifyAll();
19231            }
19232        }
19233
19234        @Override
19235        public void onServiceDisconnected(ComponentName name) {
19236        }
19237    }
19238
19239    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19240        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19241
19242        final boolean mounted;
19243        if (Environment.isExternalStorageEmulated()) {
19244            mounted = true;
19245        } else {
19246            final String status = Environment.getExternalStorageState();
19247
19248            mounted = status.equals(Environment.MEDIA_MOUNTED)
19249                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19250        }
19251
19252        if (!mounted) {
19253            return;
19254        }
19255
19256        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19257        int[] users;
19258        if (userId == UserHandle.USER_ALL) {
19259            users = sUserManager.getUserIds();
19260        } else {
19261            users = new int[] { userId };
19262        }
19263        final ClearStorageConnection conn = new ClearStorageConnection();
19264        if (mContext.bindServiceAsUser(
19265                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19266            try {
19267                for (int curUser : users) {
19268                    long timeout = SystemClock.uptimeMillis() + 5000;
19269                    synchronized (conn) {
19270                        long now;
19271                        while (conn.mContainerService == null &&
19272                                (now = SystemClock.uptimeMillis()) < timeout) {
19273                            try {
19274                                conn.wait(timeout - now);
19275                            } catch (InterruptedException e) {
19276                            }
19277                        }
19278                    }
19279                    if (conn.mContainerService == null) {
19280                        return;
19281                    }
19282
19283                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19284                    clearDirectory(conn.mContainerService,
19285                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19286                    if (allData) {
19287                        clearDirectory(conn.mContainerService,
19288                                userEnv.buildExternalStorageAppDataDirs(packageName));
19289                        clearDirectory(conn.mContainerService,
19290                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19291                    }
19292                }
19293            } finally {
19294                mContext.unbindService(conn);
19295            }
19296        }
19297    }
19298
19299    @Override
19300    public void clearApplicationProfileData(String packageName) {
19301        enforceSystemOrRoot("Only the system can clear all profile data");
19302
19303        final PackageParser.Package pkg;
19304        synchronized (mPackages) {
19305            pkg = mPackages.get(packageName);
19306        }
19307
19308        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19309            synchronized (mInstallLock) {
19310                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19311            }
19312        }
19313    }
19314
19315    @Override
19316    public void clearApplicationUserData(final String packageName,
19317            final IPackageDataObserver observer, final int userId) {
19318        mContext.enforceCallingOrSelfPermission(
19319                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19320
19321        enforceCrossUserPermission(Binder.getCallingUid(), userId,
19322                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19323
19324        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19325            throw new SecurityException("Cannot clear data for a protected package: "
19326                    + packageName);
19327        }
19328        // Queue up an async operation since the package deletion may take a little while.
19329        mHandler.post(new Runnable() {
19330            public void run() {
19331                mHandler.removeCallbacks(this);
19332                final boolean succeeded;
19333                try (PackageFreezer freezer = freezePackage(packageName,
19334                        "clearApplicationUserData")) {
19335                    synchronized (mInstallLock) {
19336                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19337                    }
19338                    clearExternalStorageDataSync(packageName, userId, true);
19339                    synchronized (mPackages) {
19340                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19341                                packageName, userId);
19342                    }
19343                }
19344                if (succeeded) {
19345                    // invoke DeviceStorageMonitor's update method to clear any notifications
19346                    DeviceStorageMonitorInternal dsm = LocalServices
19347                            .getService(DeviceStorageMonitorInternal.class);
19348                    if (dsm != null) {
19349                        dsm.checkMemory();
19350                    }
19351                }
19352                if(observer != null) {
19353                    try {
19354                        observer.onRemoveCompleted(packageName, succeeded);
19355                    } catch (RemoteException e) {
19356                        Log.i(TAG, "Observer no longer exists.");
19357                    }
19358                } //end if observer
19359            } //end run
19360        });
19361    }
19362
19363    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19364        if (packageName == null) {
19365            Slog.w(TAG, "Attempt to delete null packageName.");
19366            return false;
19367        }
19368
19369        // Try finding details about the requested package
19370        PackageParser.Package pkg;
19371        synchronized (mPackages) {
19372            pkg = mPackages.get(packageName);
19373            if (pkg == null) {
19374                final PackageSetting ps = mSettings.mPackages.get(packageName);
19375                if (ps != null) {
19376                    pkg = ps.pkg;
19377                }
19378            }
19379
19380            if (pkg == null) {
19381                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19382                return false;
19383            }
19384
19385            PackageSetting ps = (PackageSetting) pkg.mExtras;
19386            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19387        }
19388
19389        clearAppDataLIF(pkg, userId,
19390                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19391
19392        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19393        removeKeystoreDataIfNeeded(userId, appId);
19394
19395        UserManagerInternal umInternal = getUserManagerInternal();
19396        final int flags;
19397        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19398            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19399        } else if (umInternal.isUserRunning(userId)) {
19400            flags = StorageManager.FLAG_STORAGE_DE;
19401        } else {
19402            flags = 0;
19403        }
19404        prepareAppDataContentsLIF(pkg, userId, flags);
19405
19406        return true;
19407    }
19408
19409    /**
19410     * Reverts user permission state changes (permissions and flags) in
19411     * all packages for a given user.
19412     *
19413     * @param userId The device user for which to do a reset.
19414     */
19415    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19416        final int packageCount = mPackages.size();
19417        for (int i = 0; i < packageCount; i++) {
19418            PackageParser.Package pkg = mPackages.valueAt(i);
19419            PackageSetting ps = (PackageSetting) pkg.mExtras;
19420            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19421        }
19422    }
19423
19424    private void resetNetworkPolicies(int userId) {
19425        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19426    }
19427
19428    /**
19429     * Reverts user permission state changes (permissions and flags).
19430     *
19431     * @param ps The package for which to reset.
19432     * @param userId The device user for which to do a reset.
19433     */
19434    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19435            final PackageSetting ps, final int userId) {
19436        if (ps.pkg == null) {
19437            return;
19438        }
19439
19440        // These are flags that can change base on user actions.
19441        final int userSettableMask = FLAG_PERMISSION_USER_SET
19442                | FLAG_PERMISSION_USER_FIXED
19443                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19444                | FLAG_PERMISSION_REVIEW_REQUIRED;
19445
19446        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19447                | FLAG_PERMISSION_POLICY_FIXED;
19448
19449        boolean writeInstallPermissions = false;
19450        boolean writeRuntimePermissions = false;
19451
19452        final int permissionCount = ps.pkg.requestedPermissions.size();
19453        for (int i = 0; i < permissionCount; i++) {
19454            String permission = ps.pkg.requestedPermissions.get(i);
19455
19456            BasePermission bp = mSettings.mPermissions.get(permission);
19457            if (bp == null) {
19458                continue;
19459            }
19460
19461            // If shared user we just reset the state to which only this app contributed.
19462            if (ps.sharedUser != null) {
19463                boolean used = false;
19464                final int packageCount = ps.sharedUser.packages.size();
19465                for (int j = 0; j < packageCount; j++) {
19466                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19467                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19468                            && pkg.pkg.requestedPermissions.contains(permission)) {
19469                        used = true;
19470                        break;
19471                    }
19472                }
19473                if (used) {
19474                    continue;
19475                }
19476            }
19477
19478            PermissionsState permissionsState = ps.getPermissionsState();
19479
19480            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19481
19482            // Always clear the user settable flags.
19483            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19484                    bp.name) != null;
19485            // If permission review is enabled and this is a legacy app, mark the
19486            // permission as requiring a review as this is the initial state.
19487            int flags = 0;
19488            if (mPermissionReviewRequired
19489                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19490                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19491            }
19492            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19493                if (hasInstallState) {
19494                    writeInstallPermissions = true;
19495                } else {
19496                    writeRuntimePermissions = true;
19497                }
19498            }
19499
19500            // Below is only runtime permission handling.
19501            if (!bp.isRuntime()) {
19502                continue;
19503            }
19504
19505            // Never clobber system or policy.
19506            if ((oldFlags & policyOrSystemFlags) != 0) {
19507                continue;
19508            }
19509
19510            // If this permission was granted by default, make sure it is.
19511            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19512                if (permissionsState.grantRuntimePermission(bp, userId)
19513                        != PERMISSION_OPERATION_FAILURE) {
19514                    writeRuntimePermissions = true;
19515                }
19516            // If permission review is enabled the permissions for a legacy apps
19517            // are represented as constantly granted runtime ones, so don't revoke.
19518            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19519                // Otherwise, reset the permission.
19520                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19521                switch (revokeResult) {
19522                    case PERMISSION_OPERATION_SUCCESS:
19523                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19524                        writeRuntimePermissions = true;
19525                        final int appId = ps.appId;
19526                        mHandler.post(new Runnable() {
19527                            @Override
19528                            public void run() {
19529                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19530                            }
19531                        });
19532                    } break;
19533                }
19534            }
19535        }
19536
19537        // Synchronously write as we are taking permissions away.
19538        if (writeRuntimePermissions) {
19539            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19540        }
19541
19542        // Synchronously write as we are taking permissions away.
19543        if (writeInstallPermissions) {
19544            mSettings.writeLPr();
19545        }
19546    }
19547
19548    /**
19549     * Remove entries from the keystore daemon. Will only remove it if the
19550     * {@code appId} is valid.
19551     */
19552    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19553        if (appId < 0) {
19554            return;
19555        }
19556
19557        final KeyStore keyStore = KeyStore.getInstance();
19558        if (keyStore != null) {
19559            if (userId == UserHandle.USER_ALL) {
19560                for (final int individual : sUserManager.getUserIds()) {
19561                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19562                }
19563            } else {
19564                keyStore.clearUid(UserHandle.getUid(userId, appId));
19565            }
19566        } else {
19567            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19568        }
19569    }
19570
19571    @Override
19572    public void deleteApplicationCacheFiles(final String packageName,
19573            final IPackageDataObserver observer) {
19574        final int userId = UserHandle.getCallingUserId();
19575        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19576    }
19577
19578    @Override
19579    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19580            final IPackageDataObserver observer) {
19581        mContext.enforceCallingOrSelfPermission(
19582                android.Manifest.permission.DELETE_CACHE_FILES, null);
19583        enforceCrossUserPermission(Binder.getCallingUid(), userId,
19584                /* requireFullPermission= */ true, /* checkShell= */ false,
19585                "delete application cache files");
19586
19587        final PackageParser.Package pkg;
19588        synchronized (mPackages) {
19589            pkg = mPackages.get(packageName);
19590        }
19591
19592        // Queue up an async operation since the package deletion may take a little while.
19593        mHandler.post(new Runnable() {
19594            public void run() {
19595                synchronized (mInstallLock) {
19596                    final int flags = StorageManager.FLAG_STORAGE_DE
19597                            | StorageManager.FLAG_STORAGE_CE;
19598                    // We're only clearing cache files, so we don't care if the
19599                    // app is unfrozen and still able to run
19600                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19601                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19602                }
19603                clearExternalStorageDataSync(packageName, userId, false);
19604                if (observer != null) {
19605                    try {
19606                        observer.onRemoveCompleted(packageName, true);
19607                    } catch (RemoteException e) {
19608                        Log.i(TAG, "Observer no longer exists.");
19609                    }
19610                }
19611            }
19612        });
19613    }
19614
19615    @Override
19616    public void getPackageSizeInfo(final String packageName, int userHandle,
19617            final IPackageStatsObserver observer) {
19618        throw new UnsupportedOperationException(
19619                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19620    }
19621
19622    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19623        final PackageSetting ps;
19624        synchronized (mPackages) {
19625            ps = mSettings.mPackages.get(packageName);
19626            if (ps == null) {
19627                Slog.w(TAG, "Failed to find settings for " + packageName);
19628                return false;
19629            }
19630        }
19631
19632        final String[] packageNames = { packageName };
19633        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19634        final String[] codePaths = { ps.codePathString };
19635
19636        try {
19637            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19638                    ps.appId, ceDataInodes, codePaths, stats);
19639
19640            // For now, ignore code size of packages on system partition
19641            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19642                stats.codeSize = 0;
19643            }
19644
19645            // External clients expect these to be tracked separately
19646            stats.dataSize -= stats.cacheSize;
19647
19648        } catch (InstallerException e) {
19649            Slog.w(TAG, String.valueOf(e));
19650            return false;
19651        }
19652
19653        return true;
19654    }
19655
19656    private int getUidTargetSdkVersionLockedLPr(int uid) {
19657        Object obj = mSettings.getUserIdLPr(uid);
19658        if (obj instanceof SharedUserSetting) {
19659            final SharedUserSetting sus = (SharedUserSetting) obj;
19660            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19661            final Iterator<PackageSetting> it = sus.packages.iterator();
19662            while (it.hasNext()) {
19663                final PackageSetting ps = it.next();
19664                if (ps.pkg != null) {
19665                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19666                    if (v < vers) vers = v;
19667                }
19668            }
19669            return vers;
19670        } else if (obj instanceof PackageSetting) {
19671            final PackageSetting ps = (PackageSetting) obj;
19672            if (ps.pkg != null) {
19673                return ps.pkg.applicationInfo.targetSdkVersion;
19674            }
19675        }
19676        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19677    }
19678
19679    @Override
19680    public void addPreferredActivity(IntentFilter filter, int match,
19681            ComponentName[] set, ComponentName activity, int userId) {
19682        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19683                "Adding preferred");
19684    }
19685
19686    private void addPreferredActivityInternal(IntentFilter filter, int match,
19687            ComponentName[] set, ComponentName activity, boolean always, int userId,
19688            String opname) {
19689        // writer
19690        int callingUid = Binder.getCallingUid();
19691        enforceCrossUserPermission(callingUid, userId,
19692                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19693        if (filter.countActions() == 0) {
19694            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19695            return;
19696        }
19697        synchronized (mPackages) {
19698            if (mContext.checkCallingOrSelfPermission(
19699                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19700                    != PackageManager.PERMISSION_GRANTED) {
19701                if (getUidTargetSdkVersionLockedLPr(callingUid)
19702                        < Build.VERSION_CODES.FROYO) {
19703                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19704                            + callingUid);
19705                    return;
19706                }
19707                mContext.enforceCallingOrSelfPermission(
19708                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19709            }
19710
19711            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19712            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19713                    + userId + ":");
19714            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19715            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19716            scheduleWritePackageRestrictionsLocked(userId);
19717            postPreferredActivityChangedBroadcast(userId);
19718        }
19719    }
19720
19721    private void postPreferredActivityChangedBroadcast(int userId) {
19722        mHandler.post(() -> {
19723            final IActivityManager am = ActivityManager.getService();
19724            if (am == null) {
19725                return;
19726            }
19727
19728            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19729            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19730            try {
19731                am.broadcastIntent(null, intent, null, null,
19732                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19733                        null, false, false, userId);
19734            } catch (RemoteException e) {
19735            }
19736        });
19737    }
19738
19739    @Override
19740    public void replacePreferredActivity(IntentFilter filter, int match,
19741            ComponentName[] set, ComponentName activity, int userId) {
19742        if (filter.countActions() != 1) {
19743            throw new IllegalArgumentException(
19744                    "replacePreferredActivity expects filter to have only 1 action.");
19745        }
19746        if (filter.countDataAuthorities() != 0
19747                || filter.countDataPaths() != 0
19748                || filter.countDataSchemes() > 1
19749                || filter.countDataTypes() != 0) {
19750            throw new IllegalArgumentException(
19751                    "replacePreferredActivity expects filter to have no data authorities, " +
19752                    "paths, or types; and at most one scheme.");
19753        }
19754
19755        final int callingUid = Binder.getCallingUid();
19756        enforceCrossUserPermission(callingUid, userId,
19757                true /* requireFullPermission */, false /* checkShell */,
19758                "replace preferred activity");
19759        synchronized (mPackages) {
19760            if (mContext.checkCallingOrSelfPermission(
19761                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19762                    != PackageManager.PERMISSION_GRANTED) {
19763                if (getUidTargetSdkVersionLockedLPr(callingUid)
19764                        < Build.VERSION_CODES.FROYO) {
19765                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19766                            + Binder.getCallingUid());
19767                    return;
19768                }
19769                mContext.enforceCallingOrSelfPermission(
19770                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19771            }
19772
19773            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19774            if (pir != null) {
19775                // Get all of the existing entries that exactly match this filter.
19776                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19777                if (existing != null && existing.size() == 1) {
19778                    PreferredActivity cur = existing.get(0);
19779                    if (DEBUG_PREFERRED) {
19780                        Slog.i(TAG, "Checking replace of preferred:");
19781                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19782                        if (!cur.mPref.mAlways) {
19783                            Slog.i(TAG, "  -- CUR; not mAlways!");
19784                        } else {
19785                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19786                            Slog.i(TAG, "  -- CUR: mSet="
19787                                    + Arrays.toString(cur.mPref.mSetComponents));
19788                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19789                            Slog.i(TAG, "  -- NEW: mMatch="
19790                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19791                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19792                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19793                        }
19794                    }
19795                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19796                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19797                            && cur.mPref.sameSet(set)) {
19798                        // Setting the preferred activity to what it happens to be already
19799                        if (DEBUG_PREFERRED) {
19800                            Slog.i(TAG, "Replacing with same preferred activity "
19801                                    + cur.mPref.mShortComponent + " for user "
19802                                    + userId + ":");
19803                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19804                        }
19805                        return;
19806                    }
19807                }
19808
19809                if (existing != null) {
19810                    if (DEBUG_PREFERRED) {
19811                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19812                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19813                    }
19814                    for (int i = 0; i < existing.size(); i++) {
19815                        PreferredActivity pa = existing.get(i);
19816                        if (DEBUG_PREFERRED) {
19817                            Slog.i(TAG, "Removing existing preferred activity "
19818                                    + pa.mPref.mComponent + ":");
19819                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19820                        }
19821                        pir.removeFilter(pa);
19822                    }
19823                }
19824            }
19825            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19826                    "Replacing preferred");
19827        }
19828    }
19829
19830    @Override
19831    public void clearPackagePreferredActivities(String packageName) {
19832        final int callingUid = Binder.getCallingUid();
19833        if (getInstantAppPackageName(callingUid) != null) {
19834            return;
19835        }
19836        // writer
19837        synchronized (mPackages) {
19838            PackageParser.Package pkg = mPackages.get(packageName);
19839            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19840                if (mContext.checkCallingOrSelfPermission(
19841                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19842                        != PackageManager.PERMISSION_GRANTED) {
19843                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19844                            < Build.VERSION_CODES.FROYO) {
19845                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19846                                + callingUid);
19847                        return;
19848                    }
19849                    mContext.enforceCallingOrSelfPermission(
19850                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19851                }
19852            }
19853
19854            int user = UserHandle.getCallingUserId();
19855            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19856                scheduleWritePackageRestrictionsLocked(user);
19857            }
19858        }
19859    }
19860
19861    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19862    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19863        ArrayList<PreferredActivity> removed = null;
19864        boolean changed = false;
19865        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19866            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19867            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19868            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19869                continue;
19870            }
19871            Iterator<PreferredActivity> it = pir.filterIterator();
19872            while (it.hasNext()) {
19873                PreferredActivity pa = it.next();
19874                // Mark entry for removal only if it matches the package name
19875                // and the entry is of type "always".
19876                if (packageName == null ||
19877                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19878                                && pa.mPref.mAlways)) {
19879                    if (removed == null) {
19880                        removed = new ArrayList<PreferredActivity>();
19881                    }
19882                    removed.add(pa);
19883                }
19884            }
19885            if (removed != null) {
19886                for (int j=0; j<removed.size(); j++) {
19887                    PreferredActivity pa = removed.get(j);
19888                    pir.removeFilter(pa);
19889                }
19890                changed = true;
19891            }
19892        }
19893        if (changed) {
19894            postPreferredActivityChangedBroadcast(userId);
19895        }
19896        return changed;
19897    }
19898
19899    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19900    private void clearIntentFilterVerificationsLPw(int userId) {
19901        final int packageCount = mPackages.size();
19902        for (int i = 0; i < packageCount; i++) {
19903            PackageParser.Package pkg = mPackages.valueAt(i);
19904            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19905        }
19906    }
19907
19908    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19909    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19910        if (userId == UserHandle.USER_ALL) {
19911            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19912                    sUserManager.getUserIds())) {
19913                for (int oneUserId : sUserManager.getUserIds()) {
19914                    scheduleWritePackageRestrictionsLocked(oneUserId);
19915                }
19916            }
19917        } else {
19918            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19919                scheduleWritePackageRestrictionsLocked(userId);
19920            }
19921        }
19922    }
19923
19924    /** Clears state for all users, and touches intent filter verification policy */
19925    void clearDefaultBrowserIfNeeded(String packageName) {
19926        for (int oneUserId : sUserManager.getUserIds()) {
19927            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19928        }
19929    }
19930
19931    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19932        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19933        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19934            if (packageName.equals(defaultBrowserPackageName)) {
19935                setDefaultBrowserPackageName(null, userId);
19936            }
19937        }
19938    }
19939
19940    @Override
19941    public void resetApplicationPreferences(int userId) {
19942        mContext.enforceCallingOrSelfPermission(
19943                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19944        final long identity = Binder.clearCallingIdentity();
19945        // writer
19946        try {
19947            synchronized (mPackages) {
19948                clearPackagePreferredActivitiesLPw(null, userId);
19949                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19950                // TODO: We have to reset the default SMS and Phone. This requires
19951                // significant refactoring to keep all default apps in the package
19952                // manager (cleaner but more work) or have the services provide
19953                // callbacks to the package manager to request a default app reset.
19954                applyFactoryDefaultBrowserLPw(userId);
19955                clearIntentFilterVerificationsLPw(userId);
19956                primeDomainVerificationsLPw(userId);
19957                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19958                scheduleWritePackageRestrictionsLocked(userId);
19959            }
19960            resetNetworkPolicies(userId);
19961        } finally {
19962            Binder.restoreCallingIdentity(identity);
19963        }
19964    }
19965
19966    @Override
19967    public int getPreferredActivities(List<IntentFilter> outFilters,
19968            List<ComponentName> outActivities, String packageName) {
19969        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19970            return 0;
19971        }
19972        int num = 0;
19973        final int userId = UserHandle.getCallingUserId();
19974        // reader
19975        synchronized (mPackages) {
19976            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19977            if (pir != null) {
19978                final Iterator<PreferredActivity> it = pir.filterIterator();
19979                while (it.hasNext()) {
19980                    final PreferredActivity pa = it.next();
19981                    if (packageName == null
19982                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19983                                    && pa.mPref.mAlways)) {
19984                        if (outFilters != null) {
19985                            outFilters.add(new IntentFilter(pa));
19986                        }
19987                        if (outActivities != null) {
19988                            outActivities.add(pa.mPref.mComponent);
19989                        }
19990                    }
19991                }
19992            }
19993        }
19994
19995        return num;
19996    }
19997
19998    @Override
19999    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20000            int userId) {
20001        int callingUid = Binder.getCallingUid();
20002        if (callingUid != Process.SYSTEM_UID) {
20003            throw new SecurityException(
20004                    "addPersistentPreferredActivity can only be run by the system");
20005        }
20006        if (filter.countActions() == 0) {
20007            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20008            return;
20009        }
20010        synchronized (mPackages) {
20011            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20012                    ":");
20013            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20014            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20015                    new PersistentPreferredActivity(filter, activity));
20016            scheduleWritePackageRestrictionsLocked(userId);
20017            postPreferredActivityChangedBroadcast(userId);
20018        }
20019    }
20020
20021    @Override
20022    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20023        int callingUid = Binder.getCallingUid();
20024        if (callingUid != Process.SYSTEM_UID) {
20025            throw new SecurityException(
20026                    "clearPackagePersistentPreferredActivities can only be run by the system");
20027        }
20028        ArrayList<PersistentPreferredActivity> removed = null;
20029        boolean changed = false;
20030        synchronized (mPackages) {
20031            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20032                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20033                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20034                        .valueAt(i);
20035                if (userId != thisUserId) {
20036                    continue;
20037                }
20038                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20039                while (it.hasNext()) {
20040                    PersistentPreferredActivity ppa = it.next();
20041                    // Mark entry for removal only if it matches the package name.
20042                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20043                        if (removed == null) {
20044                            removed = new ArrayList<PersistentPreferredActivity>();
20045                        }
20046                        removed.add(ppa);
20047                    }
20048                }
20049                if (removed != null) {
20050                    for (int j=0; j<removed.size(); j++) {
20051                        PersistentPreferredActivity ppa = removed.get(j);
20052                        ppir.removeFilter(ppa);
20053                    }
20054                    changed = true;
20055                }
20056            }
20057
20058            if (changed) {
20059                scheduleWritePackageRestrictionsLocked(userId);
20060                postPreferredActivityChangedBroadcast(userId);
20061            }
20062        }
20063    }
20064
20065    /**
20066     * Common machinery for picking apart a restored XML blob and passing
20067     * it to a caller-supplied functor to be applied to the running system.
20068     */
20069    private void restoreFromXml(XmlPullParser parser, int userId,
20070            String expectedStartTag, BlobXmlRestorer functor)
20071            throws IOException, XmlPullParserException {
20072        int type;
20073        while ((type = parser.next()) != XmlPullParser.START_TAG
20074                && type != XmlPullParser.END_DOCUMENT) {
20075        }
20076        if (type != XmlPullParser.START_TAG) {
20077            // oops didn't find a start tag?!
20078            if (DEBUG_BACKUP) {
20079                Slog.e(TAG, "Didn't find start tag during restore");
20080            }
20081            return;
20082        }
20083Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20084        // this is supposed to be TAG_PREFERRED_BACKUP
20085        if (!expectedStartTag.equals(parser.getName())) {
20086            if (DEBUG_BACKUP) {
20087                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20088            }
20089            return;
20090        }
20091
20092        // skip interfering stuff, then we're aligned with the backing implementation
20093        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20094Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20095        functor.apply(parser, userId);
20096    }
20097
20098    private interface BlobXmlRestorer {
20099        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20100    }
20101
20102    /**
20103     * Non-Binder method, support for the backup/restore mechanism: write the
20104     * full set of preferred activities in its canonical XML format.  Returns the
20105     * XML output as a byte array, or null if there is none.
20106     */
20107    @Override
20108    public byte[] getPreferredActivityBackup(int userId) {
20109        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20110            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20111        }
20112
20113        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20114        try {
20115            final XmlSerializer serializer = new FastXmlSerializer();
20116            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20117            serializer.startDocument(null, true);
20118            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20119
20120            synchronized (mPackages) {
20121                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20122            }
20123
20124            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20125            serializer.endDocument();
20126            serializer.flush();
20127        } catch (Exception e) {
20128            if (DEBUG_BACKUP) {
20129                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20130            }
20131            return null;
20132        }
20133
20134        return dataStream.toByteArray();
20135    }
20136
20137    @Override
20138    public void restorePreferredActivities(byte[] backup, int userId) {
20139        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20140            throw new SecurityException("Only the system may call restorePreferredActivities()");
20141        }
20142
20143        try {
20144            final XmlPullParser parser = Xml.newPullParser();
20145            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20146            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20147                    new BlobXmlRestorer() {
20148                        @Override
20149                        public void apply(XmlPullParser parser, int userId)
20150                                throws XmlPullParserException, IOException {
20151                            synchronized (mPackages) {
20152                                mSettings.readPreferredActivitiesLPw(parser, userId);
20153                            }
20154                        }
20155                    } );
20156        } catch (Exception e) {
20157            if (DEBUG_BACKUP) {
20158                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20159            }
20160        }
20161    }
20162
20163    /**
20164     * Non-Binder method, support for the backup/restore mechanism: write the
20165     * default browser (etc) settings in its canonical XML format.  Returns the default
20166     * browser XML representation as a byte array, or null if there is none.
20167     */
20168    @Override
20169    public byte[] getDefaultAppsBackup(int userId) {
20170        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20171            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20172        }
20173
20174        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20175        try {
20176            final XmlSerializer serializer = new FastXmlSerializer();
20177            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20178            serializer.startDocument(null, true);
20179            serializer.startTag(null, TAG_DEFAULT_APPS);
20180
20181            synchronized (mPackages) {
20182                mSettings.writeDefaultAppsLPr(serializer, userId);
20183            }
20184
20185            serializer.endTag(null, TAG_DEFAULT_APPS);
20186            serializer.endDocument();
20187            serializer.flush();
20188        } catch (Exception e) {
20189            if (DEBUG_BACKUP) {
20190                Slog.e(TAG, "Unable to write default apps for backup", e);
20191            }
20192            return null;
20193        }
20194
20195        return dataStream.toByteArray();
20196    }
20197
20198    @Override
20199    public void restoreDefaultApps(byte[] backup, int userId) {
20200        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20201            throw new SecurityException("Only the system may call restoreDefaultApps()");
20202        }
20203
20204        try {
20205            final XmlPullParser parser = Xml.newPullParser();
20206            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20207            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20208                    new BlobXmlRestorer() {
20209                        @Override
20210                        public void apply(XmlPullParser parser, int userId)
20211                                throws XmlPullParserException, IOException {
20212                            synchronized (mPackages) {
20213                                mSettings.readDefaultAppsLPw(parser, userId);
20214                            }
20215                        }
20216                    } );
20217        } catch (Exception e) {
20218            if (DEBUG_BACKUP) {
20219                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20220            }
20221        }
20222    }
20223
20224    @Override
20225    public byte[] getIntentFilterVerificationBackup(int userId) {
20226        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20227            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20228        }
20229
20230        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20231        try {
20232            final XmlSerializer serializer = new FastXmlSerializer();
20233            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20234            serializer.startDocument(null, true);
20235            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20236
20237            synchronized (mPackages) {
20238                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20239            }
20240
20241            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20242            serializer.endDocument();
20243            serializer.flush();
20244        } catch (Exception e) {
20245            if (DEBUG_BACKUP) {
20246                Slog.e(TAG, "Unable to write default apps for backup", e);
20247            }
20248            return null;
20249        }
20250
20251        return dataStream.toByteArray();
20252    }
20253
20254    @Override
20255    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20256        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20257            throw new SecurityException("Only the system may call restorePreferredActivities()");
20258        }
20259
20260        try {
20261            final XmlPullParser parser = Xml.newPullParser();
20262            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20263            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20264                    new BlobXmlRestorer() {
20265                        @Override
20266                        public void apply(XmlPullParser parser, int userId)
20267                                throws XmlPullParserException, IOException {
20268                            synchronized (mPackages) {
20269                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20270                                mSettings.writeLPr();
20271                            }
20272                        }
20273                    } );
20274        } catch (Exception e) {
20275            if (DEBUG_BACKUP) {
20276                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20277            }
20278        }
20279    }
20280
20281    @Override
20282    public byte[] getPermissionGrantBackup(int userId) {
20283        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20284            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20285        }
20286
20287        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20288        try {
20289            final XmlSerializer serializer = new FastXmlSerializer();
20290            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20291            serializer.startDocument(null, true);
20292            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20293
20294            synchronized (mPackages) {
20295                serializeRuntimePermissionGrantsLPr(serializer, userId);
20296            }
20297
20298            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20299            serializer.endDocument();
20300            serializer.flush();
20301        } catch (Exception e) {
20302            if (DEBUG_BACKUP) {
20303                Slog.e(TAG, "Unable to write default apps for backup", e);
20304            }
20305            return null;
20306        }
20307
20308        return dataStream.toByteArray();
20309    }
20310
20311    @Override
20312    public void restorePermissionGrants(byte[] backup, int userId) {
20313        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20314            throw new SecurityException("Only the system may call restorePermissionGrants()");
20315        }
20316
20317        try {
20318            final XmlPullParser parser = Xml.newPullParser();
20319            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20320            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20321                    new BlobXmlRestorer() {
20322                        @Override
20323                        public void apply(XmlPullParser parser, int userId)
20324                                throws XmlPullParserException, IOException {
20325                            synchronized (mPackages) {
20326                                processRestoredPermissionGrantsLPr(parser, userId);
20327                            }
20328                        }
20329                    } );
20330        } catch (Exception e) {
20331            if (DEBUG_BACKUP) {
20332                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20333            }
20334        }
20335    }
20336
20337    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20338            throws IOException {
20339        serializer.startTag(null, TAG_ALL_GRANTS);
20340
20341        final int N = mSettings.mPackages.size();
20342        for (int i = 0; i < N; i++) {
20343            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20344            boolean pkgGrantsKnown = false;
20345
20346            PermissionsState packagePerms = ps.getPermissionsState();
20347
20348            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20349                final int grantFlags = state.getFlags();
20350                // only look at grants that are not system/policy fixed
20351                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20352                    final boolean isGranted = state.isGranted();
20353                    // And only back up the user-twiddled state bits
20354                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20355                        final String packageName = mSettings.mPackages.keyAt(i);
20356                        if (!pkgGrantsKnown) {
20357                            serializer.startTag(null, TAG_GRANT);
20358                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20359                            pkgGrantsKnown = true;
20360                        }
20361
20362                        final boolean userSet =
20363                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20364                        final boolean userFixed =
20365                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20366                        final boolean revoke =
20367                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20368
20369                        serializer.startTag(null, TAG_PERMISSION);
20370                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20371                        if (isGranted) {
20372                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20373                        }
20374                        if (userSet) {
20375                            serializer.attribute(null, ATTR_USER_SET, "true");
20376                        }
20377                        if (userFixed) {
20378                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20379                        }
20380                        if (revoke) {
20381                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20382                        }
20383                        serializer.endTag(null, TAG_PERMISSION);
20384                    }
20385                }
20386            }
20387
20388            if (pkgGrantsKnown) {
20389                serializer.endTag(null, TAG_GRANT);
20390            }
20391        }
20392
20393        serializer.endTag(null, TAG_ALL_GRANTS);
20394    }
20395
20396    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20397            throws XmlPullParserException, IOException {
20398        String pkgName = null;
20399        int outerDepth = parser.getDepth();
20400        int type;
20401        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20402                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20403            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20404                continue;
20405            }
20406
20407            final String tagName = parser.getName();
20408            if (tagName.equals(TAG_GRANT)) {
20409                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20410                if (DEBUG_BACKUP) {
20411                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20412                }
20413            } else if (tagName.equals(TAG_PERMISSION)) {
20414
20415                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20416                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20417
20418                int newFlagSet = 0;
20419                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20420                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20421                }
20422                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20423                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20424                }
20425                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20426                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20427                }
20428                if (DEBUG_BACKUP) {
20429                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20430                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20431                }
20432                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20433                if (ps != null) {
20434                    // Already installed so we apply the grant immediately
20435                    if (DEBUG_BACKUP) {
20436                        Slog.v(TAG, "        + already installed; applying");
20437                    }
20438                    PermissionsState perms = ps.getPermissionsState();
20439                    BasePermission bp = mSettings.mPermissions.get(permName);
20440                    if (bp != null) {
20441                        if (isGranted) {
20442                            perms.grantRuntimePermission(bp, userId);
20443                        }
20444                        if (newFlagSet != 0) {
20445                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20446                        }
20447                    }
20448                } else {
20449                    // Need to wait for post-restore install to apply the grant
20450                    if (DEBUG_BACKUP) {
20451                        Slog.v(TAG, "        - not yet installed; saving for later");
20452                    }
20453                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20454                            isGranted, newFlagSet, userId);
20455                }
20456            } else {
20457                PackageManagerService.reportSettingsProblem(Log.WARN,
20458                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20459                XmlUtils.skipCurrentTag(parser);
20460            }
20461        }
20462
20463        scheduleWriteSettingsLocked();
20464        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20465    }
20466
20467    @Override
20468    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20469            int sourceUserId, int targetUserId, int flags) {
20470        mContext.enforceCallingOrSelfPermission(
20471                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20472        int callingUid = Binder.getCallingUid();
20473        enforceOwnerRights(ownerPackage, callingUid);
20474        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20475        if (intentFilter.countActions() == 0) {
20476            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20477            return;
20478        }
20479        synchronized (mPackages) {
20480            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20481                    ownerPackage, targetUserId, flags);
20482            CrossProfileIntentResolver resolver =
20483                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20484            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20485            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20486            if (existing != null) {
20487                int size = existing.size();
20488                for (int i = 0; i < size; i++) {
20489                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20490                        return;
20491                    }
20492                }
20493            }
20494            resolver.addFilter(newFilter);
20495            scheduleWritePackageRestrictionsLocked(sourceUserId);
20496        }
20497    }
20498
20499    @Override
20500    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20501        mContext.enforceCallingOrSelfPermission(
20502                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20503        int callingUid = Binder.getCallingUid();
20504        enforceOwnerRights(ownerPackage, callingUid);
20505        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20506        synchronized (mPackages) {
20507            CrossProfileIntentResolver resolver =
20508                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20509            ArraySet<CrossProfileIntentFilter> set =
20510                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20511            for (CrossProfileIntentFilter filter : set) {
20512                if (filter.getOwnerPackage().equals(ownerPackage)) {
20513                    resolver.removeFilter(filter);
20514                }
20515            }
20516            scheduleWritePackageRestrictionsLocked(sourceUserId);
20517        }
20518    }
20519
20520    // Enforcing that callingUid is owning pkg on userId
20521    private void enforceOwnerRights(String pkg, int callingUid) {
20522        // The system owns everything.
20523        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20524            return;
20525        }
20526        int callingUserId = UserHandle.getUserId(callingUid);
20527        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20528        if (pi == null) {
20529            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20530                    + callingUserId);
20531        }
20532        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20533            throw new SecurityException("Calling uid " + callingUid
20534                    + " does not own package " + pkg);
20535        }
20536    }
20537
20538    @Override
20539    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20540        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20541            return null;
20542        }
20543        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20544    }
20545
20546    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20547        UserManagerService ums = UserManagerService.getInstance();
20548        if (ums != null) {
20549            final UserInfo parent = ums.getProfileParent(userId);
20550            final int launcherUid = (parent != null) ? parent.id : userId;
20551            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20552            if (launcherComponent != null) {
20553                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20554                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20555                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20556                        .setPackage(launcherComponent.getPackageName());
20557                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20558            }
20559        }
20560    }
20561
20562    /**
20563     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20564     * then reports the most likely home activity or null if there are more than one.
20565     */
20566    private ComponentName getDefaultHomeActivity(int userId) {
20567        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20568        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20569        if (cn != null) {
20570            return cn;
20571        }
20572
20573        // Find the launcher with the highest priority and return that component if there are no
20574        // other home activity with the same priority.
20575        int lastPriority = Integer.MIN_VALUE;
20576        ComponentName lastComponent = null;
20577        final int size = allHomeCandidates.size();
20578        for (int i = 0; i < size; i++) {
20579            final ResolveInfo ri = allHomeCandidates.get(i);
20580            if (ri.priority > lastPriority) {
20581                lastComponent = ri.activityInfo.getComponentName();
20582                lastPriority = ri.priority;
20583            } else if (ri.priority == lastPriority) {
20584                // Two components found with same priority.
20585                lastComponent = null;
20586            }
20587        }
20588        return lastComponent;
20589    }
20590
20591    private Intent getHomeIntent() {
20592        Intent intent = new Intent(Intent.ACTION_MAIN);
20593        intent.addCategory(Intent.CATEGORY_HOME);
20594        intent.addCategory(Intent.CATEGORY_DEFAULT);
20595        return intent;
20596    }
20597
20598    private IntentFilter getHomeFilter() {
20599        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20600        filter.addCategory(Intent.CATEGORY_HOME);
20601        filter.addCategory(Intent.CATEGORY_DEFAULT);
20602        return filter;
20603    }
20604
20605    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20606            int userId) {
20607        Intent intent  = getHomeIntent();
20608        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20609                PackageManager.GET_META_DATA, userId);
20610        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20611                true, false, false, userId);
20612
20613        allHomeCandidates.clear();
20614        if (list != null) {
20615            for (ResolveInfo ri : list) {
20616                allHomeCandidates.add(ri);
20617            }
20618        }
20619        return (preferred == null || preferred.activityInfo == null)
20620                ? null
20621                : new ComponentName(preferred.activityInfo.packageName,
20622                        preferred.activityInfo.name);
20623    }
20624
20625    @Override
20626    public void setHomeActivity(ComponentName comp, int userId) {
20627        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20628            return;
20629        }
20630        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20631        getHomeActivitiesAsUser(homeActivities, userId);
20632
20633        boolean found = false;
20634
20635        final int size = homeActivities.size();
20636        final ComponentName[] set = new ComponentName[size];
20637        for (int i = 0; i < size; i++) {
20638            final ResolveInfo candidate = homeActivities.get(i);
20639            final ActivityInfo info = candidate.activityInfo;
20640            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20641            set[i] = activityName;
20642            if (!found && activityName.equals(comp)) {
20643                found = true;
20644            }
20645        }
20646        if (!found) {
20647            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20648                    + userId);
20649        }
20650        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20651                set, comp, userId);
20652    }
20653
20654    private @Nullable String getSetupWizardPackageName() {
20655        final Intent intent = new Intent(Intent.ACTION_MAIN);
20656        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20657
20658        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20659                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20660                        | MATCH_DISABLED_COMPONENTS,
20661                UserHandle.myUserId());
20662        if (matches.size() == 1) {
20663            return matches.get(0).getComponentInfo().packageName;
20664        } else {
20665            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20666                    + ": matches=" + matches);
20667            return null;
20668        }
20669    }
20670
20671    private @Nullable String getStorageManagerPackageName() {
20672        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20673
20674        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20675                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20676                        | MATCH_DISABLED_COMPONENTS,
20677                UserHandle.myUserId());
20678        if (matches.size() == 1) {
20679            return matches.get(0).getComponentInfo().packageName;
20680        } else {
20681            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20682                    + matches.size() + ": matches=" + matches);
20683            return null;
20684        }
20685    }
20686
20687    @Override
20688    public void setApplicationEnabledSetting(String appPackageName,
20689            int newState, int flags, int userId, String callingPackage) {
20690        if (!sUserManager.exists(userId)) return;
20691        if (callingPackage == null) {
20692            callingPackage = Integer.toString(Binder.getCallingUid());
20693        }
20694        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20695    }
20696
20697    @Override
20698    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20699        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20700        synchronized (mPackages) {
20701            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20702            if (pkgSetting != null) {
20703                pkgSetting.setUpdateAvailable(updateAvailable);
20704            }
20705        }
20706    }
20707
20708    @Override
20709    public void setComponentEnabledSetting(ComponentName componentName,
20710            int newState, int flags, int userId) {
20711        if (!sUserManager.exists(userId)) return;
20712        setEnabledSetting(componentName.getPackageName(),
20713                componentName.getClassName(), newState, flags, userId, null);
20714    }
20715
20716    private void setEnabledSetting(final String packageName, String className, int newState,
20717            final int flags, int userId, String callingPackage) {
20718        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20719              || newState == COMPONENT_ENABLED_STATE_ENABLED
20720              || newState == COMPONENT_ENABLED_STATE_DISABLED
20721              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20722              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20723            throw new IllegalArgumentException("Invalid new component state: "
20724                    + newState);
20725        }
20726        PackageSetting pkgSetting;
20727        final int callingUid = Binder.getCallingUid();
20728        final int permission;
20729        if (callingUid == Process.SYSTEM_UID) {
20730            permission = PackageManager.PERMISSION_GRANTED;
20731        } else {
20732            permission = mContext.checkCallingOrSelfPermission(
20733                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20734        }
20735        enforceCrossUserPermission(callingUid, userId,
20736                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20737        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20738        boolean sendNow = false;
20739        boolean isApp = (className == null);
20740        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20741        String componentName = isApp ? packageName : className;
20742        int packageUid = -1;
20743        ArrayList<String> components;
20744
20745        // reader
20746        synchronized (mPackages) {
20747            pkgSetting = mSettings.mPackages.get(packageName);
20748            if (pkgSetting == null) {
20749                if (!isCallerInstantApp) {
20750                    if (className == null) {
20751                        throw new IllegalArgumentException("Unknown package: " + packageName);
20752                    }
20753                    throw new IllegalArgumentException(
20754                            "Unknown component: " + packageName + "/" + className);
20755                } else {
20756                    // throw SecurityException to prevent leaking package information
20757                    throw new SecurityException(
20758                            "Attempt to change component state; "
20759                            + "pid=" + Binder.getCallingPid()
20760                            + ", uid=" + callingUid
20761                            + (className == null
20762                                    ? ", package=" + packageName
20763                                    : ", component=" + packageName + "/" + className));
20764                }
20765            }
20766        }
20767
20768        // Limit who can change which apps
20769        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20770            // Don't allow apps that don't have permission to modify other apps
20771            if (!allowedByPermission) {
20772                throw new SecurityException(
20773                        "Attempt to change component state; "
20774                        + "pid=" + Binder.getCallingPid()
20775                        + ", uid=" + callingUid
20776                        + (className == null
20777                                ? ", package=" + packageName
20778                                : ", component=" + packageName + "/" + className));
20779            }
20780            // Don't allow changing protected packages.
20781            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20782                throw new SecurityException("Cannot disable a protected package: " + packageName);
20783            }
20784        }
20785
20786        synchronized (mPackages) {
20787            if (callingUid == Process.SHELL_UID
20788                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20789                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20790                // unless it is a test package.
20791                int oldState = pkgSetting.getEnabled(userId);
20792                if (className == null
20793                    &&
20794                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20795                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20796                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20797                    &&
20798                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20799                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
20800                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20801                    // ok
20802                } else {
20803                    throw new SecurityException(
20804                            "Shell cannot change component state for " + packageName + "/"
20805                            + className + " to " + newState);
20806                }
20807            }
20808            if (className == null) {
20809                // We're dealing with an application/package level state change
20810                if (pkgSetting.getEnabled(userId) == newState) {
20811                    // Nothing to do
20812                    return;
20813                }
20814                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20815                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20816                    // Don't care about who enables an app.
20817                    callingPackage = null;
20818                }
20819                pkgSetting.setEnabled(newState, userId, callingPackage);
20820                // pkgSetting.pkg.mSetEnabled = newState;
20821            } else {
20822                // We're dealing with a component level state change
20823                // First, verify that this is a valid class name.
20824                PackageParser.Package pkg = pkgSetting.pkg;
20825                if (pkg == null || !pkg.hasComponentClassName(className)) {
20826                    if (pkg != null &&
20827                            pkg.applicationInfo.targetSdkVersion >=
20828                                    Build.VERSION_CODES.JELLY_BEAN) {
20829                        throw new IllegalArgumentException("Component class " + className
20830                                + " does not exist in " + packageName);
20831                    } else {
20832                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20833                                + className + " does not exist in " + packageName);
20834                    }
20835                }
20836                switch (newState) {
20837                case COMPONENT_ENABLED_STATE_ENABLED:
20838                    if (!pkgSetting.enableComponentLPw(className, userId)) {
20839                        return;
20840                    }
20841                    break;
20842                case COMPONENT_ENABLED_STATE_DISABLED:
20843                    if (!pkgSetting.disableComponentLPw(className, userId)) {
20844                        return;
20845                    }
20846                    break;
20847                case COMPONENT_ENABLED_STATE_DEFAULT:
20848                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
20849                        return;
20850                    }
20851                    break;
20852                default:
20853                    Slog.e(TAG, "Invalid new component state: " + newState);
20854                    return;
20855                }
20856            }
20857            scheduleWritePackageRestrictionsLocked(userId);
20858            updateSequenceNumberLP(packageName, new int[] { userId });
20859            final long callingId = Binder.clearCallingIdentity();
20860            try {
20861                updateInstantAppInstallerLocked(packageName);
20862            } finally {
20863                Binder.restoreCallingIdentity(callingId);
20864            }
20865            components = mPendingBroadcasts.get(userId, packageName);
20866            final boolean newPackage = components == null;
20867            if (newPackage) {
20868                components = new ArrayList<String>();
20869            }
20870            if (!components.contains(componentName)) {
20871                components.add(componentName);
20872            }
20873            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20874                sendNow = true;
20875                // Purge entry from pending broadcast list if another one exists already
20876                // since we are sending one right away.
20877                mPendingBroadcasts.remove(userId, packageName);
20878            } else {
20879                if (newPackage) {
20880                    mPendingBroadcasts.put(userId, packageName, components);
20881                }
20882                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20883                    // Schedule a message
20884                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20885                }
20886            }
20887        }
20888
20889        long callingId = Binder.clearCallingIdentity();
20890        try {
20891            if (sendNow) {
20892                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20893                sendPackageChangedBroadcast(packageName,
20894                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20895            }
20896        } finally {
20897            Binder.restoreCallingIdentity(callingId);
20898        }
20899    }
20900
20901    @Override
20902    public void flushPackageRestrictionsAsUser(int userId) {
20903        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20904            return;
20905        }
20906        if (!sUserManager.exists(userId)) {
20907            return;
20908        }
20909        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20910                false /* checkShell */, "flushPackageRestrictions");
20911        synchronized (mPackages) {
20912            mSettings.writePackageRestrictionsLPr(userId);
20913            mDirtyUsers.remove(userId);
20914            if (mDirtyUsers.isEmpty()) {
20915                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20916            }
20917        }
20918    }
20919
20920    private void sendPackageChangedBroadcast(String packageName,
20921            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20922        if (DEBUG_INSTALL)
20923            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20924                    + componentNames);
20925        Bundle extras = new Bundle(4);
20926        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20927        String nameList[] = new String[componentNames.size()];
20928        componentNames.toArray(nameList);
20929        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20930        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20931        extras.putInt(Intent.EXTRA_UID, packageUid);
20932        // If this is not reporting a change of the overall package, then only send it
20933        // to registered receivers.  We don't want to launch a swath of apps for every
20934        // little component state change.
20935        final int flags = !componentNames.contains(packageName)
20936                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20937        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20938                new int[] {UserHandle.getUserId(packageUid)});
20939    }
20940
20941    @Override
20942    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20943        if (!sUserManager.exists(userId)) return;
20944        final int callingUid = Binder.getCallingUid();
20945        if (getInstantAppPackageName(callingUid) != null) {
20946            return;
20947        }
20948        final int permission = mContext.checkCallingOrSelfPermission(
20949                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20950        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20951        enforceCrossUserPermission(callingUid, userId,
20952                true /* requireFullPermission */, true /* checkShell */, "stop package");
20953        // writer
20954        synchronized (mPackages) {
20955            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20956                    allowedByPermission, callingUid, userId)) {
20957                scheduleWritePackageRestrictionsLocked(userId);
20958            }
20959        }
20960    }
20961
20962    @Override
20963    public String getInstallerPackageName(String packageName) {
20964        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20965            return null;
20966        }
20967        // reader
20968        synchronized (mPackages) {
20969            return mSettings.getInstallerPackageNameLPr(packageName);
20970        }
20971    }
20972
20973    public boolean isOrphaned(String packageName) {
20974        // reader
20975        synchronized (mPackages) {
20976            return mSettings.isOrphaned(packageName);
20977        }
20978    }
20979
20980    @Override
20981    public int getApplicationEnabledSetting(String packageName, int userId) {
20982        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20983        int callingUid = Binder.getCallingUid();
20984        enforceCrossUserPermission(callingUid, userId,
20985                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20986        // reader
20987        synchronized (mPackages) {
20988            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20989                return COMPONENT_ENABLED_STATE_DISABLED;
20990            }
20991            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20992        }
20993    }
20994
20995    @Override
20996    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20997        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20998        int uid = Binder.getCallingUid();
20999        enforceCrossUserPermission(uid, userId,
21000                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
21001        // reader
21002        synchronized (mPackages) {
21003            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
21004        }
21005    }
21006
21007    @Override
21008    public void enterSafeMode() {
21009        enforceSystemOrRoot("Only the system can request entering safe mode");
21010
21011        if (!mSystemReady) {
21012            mSafeMode = true;
21013        }
21014    }
21015
21016    @Override
21017    public void systemReady() {
21018        enforceSystemOrRoot("Only the system can claim the system is ready");
21019
21020        mSystemReady = true;
21021        final ContentResolver resolver = mContext.getContentResolver();
21022        ContentObserver co = new ContentObserver(mHandler) {
21023            @Override
21024            public void onChange(boolean selfChange) {
21025                mEphemeralAppsDisabled =
21026                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21027                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21028            }
21029        };
21030        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21031                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21032                false, co, UserHandle.USER_SYSTEM);
21033        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21034                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21035        co.onChange(true);
21036
21037        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21038        // disabled after already being started.
21039        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21040                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21041
21042        // Read the compatibilty setting when the system is ready.
21043        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21044                mContext.getContentResolver(),
21045                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21046        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21047        if (DEBUG_SETTINGS) {
21048            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21049        }
21050
21051        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21052
21053        synchronized (mPackages) {
21054            // Verify that all of the preferred activity components actually
21055            // exist.  It is possible for applications to be updated and at
21056            // that point remove a previously declared activity component that
21057            // had been set as a preferred activity.  We try to clean this up
21058            // the next time we encounter that preferred activity, but it is
21059            // possible for the user flow to never be able to return to that
21060            // situation so here we do a sanity check to make sure we haven't
21061            // left any junk around.
21062            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21063            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21064                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21065                removed.clear();
21066                for (PreferredActivity pa : pir.filterSet()) {
21067                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21068                        removed.add(pa);
21069                    }
21070                }
21071                if (removed.size() > 0) {
21072                    for (int r=0; r<removed.size(); r++) {
21073                        PreferredActivity pa = removed.get(r);
21074                        Slog.w(TAG, "Removing dangling preferred activity: "
21075                                + pa.mPref.mComponent);
21076                        pir.removeFilter(pa);
21077                    }
21078                    mSettings.writePackageRestrictionsLPr(
21079                            mSettings.mPreferredActivities.keyAt(i));
21080                }
21081            }
21082
21083            for (int userId : UserManagerService.getInstance().getUserIds()) {
21084                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21085                    grantPermissionsUserIds = ArrayUtils.appendInt(
21086                            grantPermissionsUserIds, userId);
21087                }
21088            }
21089        }
21090        sUserManager.systemReady();
21091
21092        // If we upgraded grant all default permissions before kicking off.
21093        for (int userId : grantPermissionsUserIds) {
21094            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21095        }
21096
21097        // If we did not grant default permissions, we preload from this the
21098        // default permission exceptions lazily to ensure we don't hit the
21099        // disk on a new user creation.
21100        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21101            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21102        }
21103
21104        // Kick off any messages waiting for system ready
21105        if (mPostSystemReadyMessages != null) {
21106            for (Message msg : mPostSystemReadyMessages) {
21107                msg.sendToTarget();
21108            }
21109            mPostSystemReadyMessages = null;
21110        }
21111
21112        // Watch for external volumes that come and go over time
21113        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21114        storage.registerListener(mStorageListener);
21115
21116        mInstallerService.systemReady();
21117        mPackageDexOptimizer.systemReady();
21118
21119        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21120                StorageManagerInternal.class);
21121        StorageManagerInternal.addExternalStoragePolicy(
21122                new StorageManagerInternal.ExternalStorageMountPolicy() {
21123            @Override
21124            public int getMountMode(int uid, String packageName) {
21125                if (Process.isIsolated(uid)) {
21126                    return Zygote.MOUNT_EXTERNAL_NONE;
21127                }
21128                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21129                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21130                }
21131                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21132                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21133                }
21134                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21135                    return Zygote.MOUNT_EXTERNAL_READ;
21136                }
21137                return Zygote.MOUNT_EXTERNAL_WRITE;
21138            }
21139
21140            @Override
21141            public boolean hasExternalStorage(int uid, String packageName) {
21142                return true;
21143            }
21144        });
21145
21146        // Now that we're mostly running, clean up stale users and apps
21147        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21148        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21149
21150        if (mPrivappPermissionsViolations != null) {
21151            Slog.wtf(TAG,"Signature|privileged permissions not in "
21152                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21153            mPrivappPermissionsViolations = null;
21154        }
21155    }
21156
21157    public void waitForAppDataPrepared() {
21158        if (mPrepareAppDataFuture == null) {
21159            return;
21160        }
21161        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21162        mPrepareAppDataFuture = null;
21163    }
21164
21165    @Override
21166    public boolean isSafeMode() {
21167        // allow instant applications
21168        return mSafeMode;
21169    }
21170
21171    @Override
21172    public boolean hasSystemUidErrors() {
21173        // allow instant applications
21174        return mHasSystemUidErrors;
21175    }
21176
21177    static String arrayToString(int[] array) {
21178        StringBuffer buf = new StringBuffer(128);
21179        buf.append('[');
21180        if (array != null) {
21181            for (int i=0; i<array.length; i++) {
21182                if (i > 0) buf.append(", ");
21183                buf.append(array[i]);
21184            }
21185        }
21186        buf.append(']');
21187        return buf.toString();
21188    }
21189
21190    static class DumpState {
21191        public static final int DUMP_LIBS = 1 << 0;
21192        public static final int DUMP_FEATURES = 1 << 1;
21193        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21194        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21195        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21196        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21197        public static final int DUMP_PERMISSIONS = 1 << 6;
21198        public static final int DUMP_PACKAGES = 1 << 7;
21199        public static final int DUMP_SHARED_USERS = 1 << 8;
21200        public static final int DUMP_MESSAGES = 1 << 9;
21201        public static final int DUMP_PROVIDERS = 1 << 10;
21202        public static final int DUMP_VERIFIERS = 1 << 11;
21203        public static final int DUMP_PREFERRED = 1 << 12;
21204        public static final int DUMP_PREFERRED_XML = 1 << 13;
21205        public static final int DUMP_KEYSETS = 1 << 14;
21206        public static final int DUMP_VERSION = 1 << 15;
21207        public static final int DUMP_INSTALLS = 1 << 16;
21208        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21209        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21210        public static final int DUMP_FROZEN = 1 << 19;
21211        public static final int DUMP_DEXOPT = 1 << 20;
21212        public static final int DUMP_COMPILER_STATS = 1 << 21;
21213        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
21214        public static final int DUMP_CHANGES = 1 << 23;
21215
21216        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21217
21218        private int mTypes;
21219
21220        private int mOptions;
21221
21222        private boolean mTitlePrinted;
21223
21224        private SharedUserSetting mSharedUser;
21225
21226        public boolean isDumping(int type) {
21227            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21228                return true;
21229            }
21230
21231            return (mTypes & type) != 0;
21232        }
21233
21234        public void setDump(int type) {
21235            mTypes |= type;
21236        }
21237
21238        public boolean isOptionEnabled(int option) {
21239            return (mOptions & option) != 0;
21240        }
21241
21242        public void setOptionEnabled(int option) {
21243            mOptions |= option;
21244        }
21245
21246        public boolean onTitlePrinted() {
21247            final boolean printed = mTitlePrinted;
21248            mTitlePrinted = true;
21249            return printed;
21250        }
21251
21252        public boolean getTitlePrinted() {
21253            return mTitlePrinted;
21254        }
21255
21256        public void setTitlePrinted(boolean enabled) {
21257            mTitlePrinted = enabled;
21258        }
21259
21260        public SharedUserSetting getSharedUser() {
21261            return mSharedUser;
21262        }
21263
21264        public void setSharedUser(SharedUserSetting user) {
21265            mSharedUser = user;
21266        }
21267    }
21268
21269    @Override
21270    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21271            FileDescriptor err, String[] args, ShellCallback callback,
21272            ResultReceiver resultReceiver) {
21273        (new PackageManagerShellCommand(this)).exec(
21274                this, in, out, err, args, callback, resultReceiver);
21275    }
21276
21277    @Override
21278    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21279        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21280
21281        DumpState dumpState = new DumpState();
21282        boolean fullPreferred = false;
21283        boolean checkin = false;
21284
21285        String packageName = null;
21286        ArraySet<String> permissionNames = null;
21287
21288        int opti = 0;
21289        while (opti < args.length) {
21290            String opt = args[opti];
21291            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21292                break;
21293            }
21294            opti++;
21295
21296            if ("-a".equals(opt)) {
21297                // Right now we only know how to print all.
21298            } else if ("-h".equals(opt)) {
21299                pw.println("Package manager dump options:");
21300                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21301                pw.println("    --checkin: dump for a checkin");
21302                pw.println("    -f: print details of intent filters");
21303                pw.println("    -h: print this help");
21304                pw.println("  cmd may be one of:");
21305                pw.println("    l[ibraries]: list known shared libraries");
21306                pw.println("    f[eatures]: list device features");
21307                pw.println("    k[eysets]: print known keysets");
21308                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21309                pw.println("    perm[issions]: dump permissions");
21310                pw.println("    permission [name ...]: dump declaration and use of given permission");
21311                pw.println("    pref[erred]: print preferred package settings");
21312                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21313                pw.println("    prov[iders]: dump content providers");
21314                pw.println("    p[ackages]: dump installed packages");
21315                pw.println("    s[hared-users]: dump shared user IDs");
21316                pw.println("    m[essages]: print collected runtime messages");
21317                pw.println("    v[erifiers]: print package verifier info");
21318                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21319                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21320                pw.println("    version: print database version info");
21321                pw.println("    write: write current settings now");
21322                pw.println("    installs: details about install sessions");
21323                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21324                pw.println("    dexopt: dump dexopt state");
21325                pw.println("    compiler-stats: dump compiler statistics");
21326                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21327                pw.println("    <package.name>: info about given package");
21328                return;
21329            } else if ("--checkin".equals(opt)) {
21330                checkin = true;
21331            } else if ("-f".equals(opt)) {
21332                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21333            } else if ("--proto".equals(opt)) {
21334                dumpProto(fd);
21335                return;
21336            } else {
21337                pw.println("Unknown argument: " + opt + "; use -h for help");
21338            }
21339        }
21340
21341        // Is the caller requesting to dump a particular piece of data?
21342        if (opti < args.length) {
21343            String cmd = args[opti];
21344            opti++;
21345            // Is this a package name?
21346            if ("android".equals(cmd) || cmd.contains(".")) {
21347                packageName = cmd;
21348                // When dumping a single package, we always dump all of its
21349                // filter information since the amount of data will be reasonable.
21350                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21351            } else if ("check-permission".equals(cmd)) {
21352                if (opti >= args.length) {
21353                    pw.println("Error: check-permission missing permission argument");
21354                    return;
21355                }
21356                String perm = args[opti];
21357                opti++;
21358                if (opti >= args.length) {
21359                    pw.println("Error: check-permission missing package argument");
21360                    return;
21361                }
21362
21363                String pkg = args[opti];
21364                opti++;
21365                int user = UserHandle.getUserId(Binder.getCallingUid());
21366                if (opti < args.length) {
21367                    try {
21368                        user = Integer.parseInt(args[opti]);
21369                    } catch (NumberFormatException e) {
21370                        pw.println("Error: check-permission user argument is not a number: "
21371                                + args[opti]);
21372                        return;
21373                    }
21374                }
21375
21376                // Normalize package name to handle renamed packages and static libs
21377                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21378
21379                pw.println(checkPermission(perm, pkg, user));
21380                return;
21381            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21382                dumpState.setDump(DumpState.DUMP_LIBS);
21383            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21384                dumpState.setDump(DumpState.DUMP_FEATURES);
21385            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21386                if (opti >= args.length) {
21387                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21388                            | DumpState.DUMP_SERVICE_RESOLVERS
21389                            | DumpState.DUMP_RECEIVER_RESOLVERS
21390                            | DumpState.DUMP_CONTENT_RESOLVERS);
21391                } else {
21392                    while (opti < args.length) {
21393                        String name = args[opti];
21394                        if ("a".equals(name) || "activity".equals(name)) {
21395                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21396                        } else if ("s".equals(name) || "service".equals(name)) {
21397                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21398                        } else if ("r".equals(name) || "receiver".equals(name)) {
21399                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21400                        } else if ("c".equals(name) || "content".equals(name)) {
21401                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21402                        } else {
21403                            pw.println("Error: unknown resolver table type: " + name);
21404                            return;
21405                        }
21406                        opti++;
21407                    }
21408                }
21409            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21410                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21411            } else if ("permission".equals(cmd)) {
21412                if (opti >= args.length) {
21413                    pw.println("Error: permission requires permission name");
21414                    return;
21415                }
21416                permissionNames = new ArraySet<>();
21417                while (opti < args.length) {
21418                    permissionNames.add(args[opti]);
21419                    opti++;
21420                }
21421                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21422                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21423            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21424                dumpState.setDump(DumpState.DUMP_PREFERRED);
21425            } else if ("preferred-xml".equals(cmd)) {
21426                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21427                if (opti < args.length && "--full".equals(args[opti])) {
21428                    fullPreferred = true;
21429                    opti++;
21430                }
21431            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21432                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21433            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21434                dumpState.setDump(DumpState.DUMP_PACKAGES);
21435            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21436                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21437            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21438                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21439            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21440                dumpState.setDump(DumpState.DUMP_MESSAGES);
21441            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21442                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21443            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21444                    || "intent-filter-verifiers".equals(cmd)) {
21445                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21446            } else if ("version".equals(cmd)) {
21447                dumpState.setDump(DumpState.DUMP_VERSION);
21448            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21449                dumpState.setDump(DumpState.DUMP_KEYSETS);
21450            } else if ("installs".equals(cmd)) {
21451                dumpState.setDump(DumpState.DUMP_INSTALLS);
21452            } else if ("frozen".equals(cmd)) {
21453                dumpState.setDump(DumpState.DUMP_FROZEN);
21454            } else if ("dexopt".equals(cmd)) {
21455                dumpState.setDump(DumpState.DUMP_DEXOPT);
21456            } else if ("compiler-stats".equals(cmd)) {
21457                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21458            } else if ("enabled-overlays".equals(cmd)) {
21459                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
21460            } else if ("changes".equals(cmd)) {
21461                dumpState.setDump(DumpState.DUMP_CHANGES);
21462            } else if ("write".equals(cmd)) {
21463                synchronized (mPackages) {
21464                    mSettings.writeLPr();
21465                    pw.println("Settings written.");
21466                    return;
21467                }
21468            }
21469        }
21470
21471        if (checkin) {
21472            pw.println("vers,1");
21473        }
21474
21475        // reader
21476        synchronized (mPackages) {
21477            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21478                if (!checkin) {
21479                    if (dumpState.onTitlePrinted())
21480                        pw.println();
21481                    pw.println("Database versions:");
21482                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21483                }
21484            }
21485
21486            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21487                if (!checkin) {
21488                    if (dumpState.onTitlePrinted())
21489                        pw.println();
21490                    pw.println("Verifiers:");
21491                    pw.print("  Required: ");
21492                    pw.print(mRequiredVerifierPackage);
21493                    pw.print(" (uid=");
21494                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21495                            UserHandle.USER_SYSTEM));
21496                    pw.println(")");
21497                } else if (mRequiredVerifierPackage != null) {
21498                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21499                    pw.print(",");
21500                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21501                            UserHandle.USER_SYSTEM));
21502                }
21503            }
21504
21505            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21506                    packageName == null) {
21507                if (mIntentFilterVerifierComponent != null) {
21508                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21509                    if (!checkin) {
21510                        if (dumpState.onTitlePrinted())
21511                            pw.println();
21512                        pw.println("Intent Filter Verifier:");
21513                        pw.print("  Using: ");
21514                        pw.print(verifierPackageName);
21515                        pw.print(" (uid=");
21516                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21517                                UserHandle.USER_SYSTEM));
21518                        pw.println(")");
21519                    } else if (verifierPackageName != null) {
21520                        pw.print("ifv,"); pw.print(verifierPackageName);
21521                        pw.print(",");
21522                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21523                                UserHandle.USER_SYSTEM));
21524                    }
21525                } else {
21526                    pw.println();
21527                    pw.println("No Intent Filter Verifier available!");
21528                }
21529            }
21530
21531            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21532                boolean printedHeader = false;
21533                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21534                while (it.hasNext()) {
21535                    String libName = it.next();
21536                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21537                    if (versionedLib == null) {
21538                        continue;
21539                    }
21540                    final int versionCount = versionedLib.size();
21541                    for (int i = 0; i < versionCount; i++) {
21542                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21543                        if (!checkin) {
21544                            if (!printedHeader) {
21545                                if (dumpState.onTitlePrinted())
21546                                    pw.println();
21547                                pw.println("Libraries:");
21548                                printedHeader = true;
21549                            }
21550                            pw.print("  ");
21551                        } else {
21552                            pw.print("lib,");
21553                        }
21554                        pw.print(libEntry.info.getName());
21555                        if (libEntry.info.isStatic()) {
21556                            pw.print(" version=" + libEntry.info.getVersion());
21557                        }
21558                        if (!checkin) {
21559                            pw.print(" -> ");
21560                        }
21561                        if (libEntry.path != null) {
21562                            pw.print(" (jar) ");
21563                            pw.print(libEntry.path);
21564                        } else {
21565                            pw.print(" (apk) ");
21566                            pw.print(libEntry.apk);
21567                        }
21568                        pw.println();
21569                    }
21570                }
21571            }
21572
21573            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21574                if (dumpState.onTitlePrinted())
21575                    pw.println();
21576                if (!checkin) {
21577                    pw.println("Features:");
21578                }
21579
21580                synchronized (mAvailableFeatures) {
21581                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21582                        if (checkin) {
21583                            pw.print("feat,");
21584                            pw.print(feat.name);
21585                            pw.print(",");
21586                            pw.println(feat.version);
21587                        } else {
21588                            pw.print("  ");
21589                            pw.print(feat.name);
21590                            if (feat.version > 0) {
21591                                pw.print(" version=");
21592                                pw.print(feat.version);
21593                            }
21594                            pw.println();
21595                        }
21596                    }
21597                }
21598            }
21599
21600            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21601                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21602                        : "Activity Resolver Table:", "  ", packageName,
21603                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21604                    dumpState.setTitlePrinted(true);
21605                }
21606            }
21607            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21608                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21609                        : "Receiver Resolver Table:", "  ", packageName,
21610                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21611                    dumpState.setTitlePrinted(true);
21612                }
21613            }
21614            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21615                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21616                        : "Service Resolver Table:", "  ", packageName,
21617                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21618                    dumpState.setTitlePrinted(true);
21619                }
21620            }
21621            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21622                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21623                        : "Provider Resolver Table:", "  ", packageName,
21624                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21625                    dumpState.setTitlePrinted(true);
21626                }
21627            }
21628
21629            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21630                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21631                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21632                    int user = mSettings.mPreferredActivities.keyAt(i);
21633                    if (pir.dump(pw,
21634                            dumpState.getTitlePrinted()
21635                                ? "\nPreferred Activities User " + user + ":"
21636                                : "Preferred Activities User " + user + ":", "  ",
21637                            packageName, true, false)) {
21638                        dumpState.setTitlePrinted(true);
21639                    }
21640                }
21641            }
21642
21643            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21644                pw.flush();
21645                FileOutputStream fout = new FileOutputStream(fd);
21646                BufferedOutputStream str = new BufferedOutputStream(fout);
21647                XmlSerializer serializer = new FastXmlSerializer();
21648                try {
21649                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21650                    serializer.startDocument(null, true);
21651                    serializer.setFeature(
21652                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21653                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21654                    serializer.endDocument();
21655                    serializer.flush();
21656                } catch (IllegalArgumentException e) {
21657                    pw.println("Failed writing: " + e);
21658                } catch (IllegalStateException e) {
21659                    pw.println("Failed writing: " + e);
21660                } catch (IOException e) {
21661                    pw.println("Failed writing: " + e);
21662                }
21663            }
21664
21665            if (!checkin
21666                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21667                    && packageName == null) {
21668                pw.println();
21669                int count = mSettings.mPackages.size();
21670                if (count == 0) {
21671                    pw.println("No applications!");
21672                    pw.println();
21673                } else {
21674                    final String prefix = "  ";
21675                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21676                    if (allPackageSettings.size() == 0) {
21677                        pw.println("No domain preferred apps!");
21678                        pw.println();
21679                    } else {
21680                        pw.println("App verification status:");
21681                        pw.println();
21682                        count = 0;
21683                        for (PackageSetting ps : allPackageSettings) {
21684                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21685                            if (ivi == null || ivi.getPackageName() == null) continue;
21686                            pw.println(prefix + "Package: " + ivi.getPackageName());
21687                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21688                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21689                            pw.println();
21690                            count++;
21691                        }
21692                        if (count == 0) {
21693                            pw.println(prefix + "No app verification established.");
21694                            pw.println();
21695                        }
21696                        for (int userId : sUserManager.getUserIds()) {
21697                            pw.println("App linkages for user " + userId + ":");
21698                            pw.println();
21699                            count = 0;
21700                            for (PackageSetting ps : allPackageSettings) {
21701                                final long status = ps.getDomainVerificationStatusForUser(userId);
21702                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21703                                        && !DEBUG_DOMAIN_VERIFICATION) {
21704                                    continue;
21705                                }
21706                                pw.println(prefix + "Package: " + ps.name);
21707                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21708                                String statusStr = IntentFilterVerificationInfo.
21709                                        getStatusStringFromValue(status);
21710                                pw.println(prefix + "Status:  " + statusStr);
21711                                pw.println();
21712                                count++;
21713                            }
21714                            if (count == 0) {
21715                                pw.println(prefix + "No configured app linkages.");
21716                                pw.println();
21717                            }
21718                        }
21719                    }
21720                }
21721            }
21722
21723            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21724                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21725                if (packageName == null && permissionNames == null) {
21726                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
21727                        if (iperm == 0) {
21728                            if (dumpState.onTitlePrinted())
21729                                pw.println();
21730                            pw.println("AppOp Permissions:");
21731                        }
21732                        pw.print("  AppOp Permission ");
21733                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
21734                        pw.println(":");
21735                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
21736                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
21737                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
21738                        }
21739                    }
21740                }
21741            }
21742
21743            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21744                boolean printedSomething = false;
21745                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21746                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21747                        continue;
21748                    }
21749                    if (!printedSomething) {
21750                        if (dumpState.onTitlePrinted())
21751                            pw.println();
21752                        pw.println("Registered ContentProviders:");
21753                        printedSomething = true;
21754                    }
21755                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21756                    pw.print("    "); pw.println(p.toString());
21757                }
21758                printedSomething = false;
21759                for (Map.Entry<String, PackageParser.Provider> entry :
21760                        mProvidersByAuthority.entrySet()) {
21761                    PackageParser.Provider p = entry.getValue();
21762                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21763                        continue;
21764                    }
21765                    if (!printedSomething) {
21766                        if (dumpState.onTitlePrinted())
21767                            pw.println();
21768                        pw.println("ContentProvider Authorities:");
21769                        printedSomething = true;
21770                    }
21771                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21772                    pw.print("    "); pw.println(p.toString());
21773                    if (p.info != null && p.info.applicationInfo != null) {
21774                        final String appInfo = p.info.applicationInfo.toString();
21775                        pw.print("      applicationInfo="); pw.println(appInfo);
21776                    }
21777                }
21778            }
21779
21780            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21781                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21782            }
21783
21784            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21785                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21786            }
21787
21788            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21789                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21790            }
21791
21792            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21793                if (dumpState.onTitlePrinted()) pw.println();
21794                pw.println("Package Changes:");
21795                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21796                final int K = mChangedPackages.size();
21797                for (int i = 0; i < K; i++) {
21798                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21799                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21800                    final int N = changes.size();
21801                    if (N == 0) {
21802                        pw.print("    "); pw.println("No packages changed");
21803                    } else {
21804                        for (int j = 0; j < N; j++) {
21805                            final String pkgName = changes.valueAt(j);
21806                            final int sequenceNumber = changes.keyAt(j);
21807                            pw.print("    ");
21808                            pw.print("seq=");
21809                            pw.print(sequenceNumber);
21810                            pw.print(", package=");
21811                            pw.println(pkgName);
21812                        }
21813                    }
21814                }
21815            }
21816
21817            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21818                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21819            }
21820
21821            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21822                // XXX should handle packageName != null by dumping only install data that
21823                // the given package is involved with.
21824                if (dumpState.onTitlePrinted()) pw.println();
21825
21826                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21827                ipw.println();
21828                ipw.println("Frozen packages:");
21829                ipw.increaseIndent();
21830                if (mFrozenPackages.size() == 0) {
21831                    ipw.println("(none)");
21832                } else {
21833                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21834                        ipw.println(mFrozenPackages.valueAt(i));
21835                    }
21836                }
21837                ipw.decreaseIndent();
21838            }
21839
21840            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21841                if (dumpState.onTitlePrinted()) pw.println();
21842                dumpDexoptStateLPr(pw, packageName);
21843            }
21844
21845            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21846                if (dumpState.onTitlePrinted()) pw.println();
21847                dumpCompilerStatsLPr(pw, packageName);
21848            }
21849
21850            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
21851                if (dumpState.onTitlePrinted()) pw.println();
21852                dumpEnabledOverlaysLPr(pw);
21853            }
21854
21855            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21856                if (dumpState.onTitlePrinted()) pw.println();
21857                mSettings.dumpReadMessagesLPr(pw, dumpState);
21858
21859                pw.println();
21860                pw.println("Package warning messages:");
21861                BufferedReader in = null;
21862                String line = null;
21863                try {
21864                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21865                    while ((line = in.readLine()) != null) {
21866                        if (line.contains("ignored: updated version")) continue;
21867                        pw.println(line);
21868                    }
21869                } catch (IOException ignored) {
21870                } finally {
21871                    IoUtils.closeQuietly(in);
21872                }
21873            }
21874
21875            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21876                BufferedReader in = null;
21877                String line = null;
21878                try {
21879                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21880                    while ((line = in.readLine()) != null) {
21881                        if (line.contains("ignored: updated version")) continue;
21882                        pw.print("msg,");
21883                        pw.println(line);
21884                    }
21885                } catch (IOException ignored) {
21886                } finally {
21887                    IoUtils.closeQuietly(in);
21888                }
21889            }
21890        }
21891
21892        // PackageInstaller should be called outside of mPackages lock
21893        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21894            // XXX should handle packageName != null by dumping only install data that
21895            // the given package is involved with.
21896            if (dumpState.onTitlePrinted()) pw.println();
21897            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21898        }
21899    }
21900
21901    private void dumpProto(FileDescriptor fd) {
21902        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21903
21904        synchronized (mPackages) {
21905            final long requiredVerifierPackageToken =
21906                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21907            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21908            proto.write(
21909                    PackageServiceDumpProto.PackageShortProto.UID,
21910                    getPackageUid(
21911                            mRequiredVerifierPackage,
21912                            MATCH_DEBUG_TRIAGED_MISSING,
21913                            UserHandle.USER_SYSTEM));
21914            proto.end(requiredVerifierPackageToken);
21915
21916            if (mIntentFilterVerifierComponent != null) {
21917                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21918                final long verifierPackageToken =
21919                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21920                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21921                proto.write(
21922                        PackageServiceDumpProto.PackageShortProto.UID,
21923                        getPackageUid(
21924                                verifierPackageName,
21925                                MATCH_DEBUG_TRIAGED_MISSING,
21926                                UserHandle.USER_SYSTEM));
21927                proto.end(verifierPackageToken);
21928            }
21929
21930            dumpSharedLibrariesProto(proto);
21931            dumpFeaturesProto(proto);
21932            mSettings.dumpPackagesProto(proto);
21933            mSettings.dumpSharedUsersProto(proto);
21934            dumpMessagesProto(proto);
21935        }
21936        proto.flush();
21937    }
21938
21939    private void dumpMessagesProto(ProtoOutputStream proto) {
21940        BufferedReader in = null;
21941        String line = null;
21942        try {
21943            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21944            while ((line = in.readLine()) != null) {
21945                if (line.contains("ignored: updated version")) continue;
21946                proto.write(PackageServiceDumpProto.MESSAGES, line);
21947            }
21948        } catch (IOException ignored) {
21949        } finally {
21950            IoUtils.closeQuietly(in);
21951        }
21952    }
21953
21954    private void dumpFeaturesProto(ProtoOutputStream proto) {
21955        synchronized (mAvailableFeatures) {
21956            final int count = mAvailableFeatures.size();
21957            for (int i = 0; i < count; i++) {
21958                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
21959                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
21960                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
21961                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
21962                proto.end(featureToken);
21963            }
21964        }
21965    }
21966
21967    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21968        final int count = mSharedLibraries.size();
21969        for (int i = 0; i < count; i++) {
21970            final String libName = mSharedLibraries.keyAt(i);
21971            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21972            if (versionedLib == null) {
21973                continue;
21974            }
21975            final int versionCount = versionedLib.size();
21976            for (int j = 0; j < versionCount; j++) {
21977                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21978                final long sharedLibraryToken =
21979                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21980                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21981                final boolean isJar = (libEntry.path != null);
21982                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21983                if (isJar) {
21984                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21985                } else {
21986                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21987                }
21988                proto.end(sharedLibraryToken);
21989            }
21990        }
21991    }
21992
21993    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21994        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21995        ipw.println();
21996        ipw.println("Dexopt state:");
21997        ipw.increaseIndent();
21998        Collection<PackageParser.Package> packages = null;
21999        if (packageName != null) {
22000            PackageParser.Package targetPackage = mPackages.get(packageName);
22001            if (targetPackage != null) {
22002                packages = Collections.singletonList(targetPackage);
22003            } else {
22004                ipw.println("Unable to find package: " + packageName);
22005                return;
22006            }
22007        } else {
22008            packages = mPackages.values();
22009        }
22010
22011        for (PackageParser.Package pkg : packages) {
22012            ipw.println("[" + pkg.packageName + "]");
22013            ipw.increaseIndent();
22014            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22015            ipw.decreaseIndent();
22016        }
22017    }
22018
22019    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22020        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22021        ipw.println();
22022        ipw.println("Compiler stats:");
22023        ipw.increaseIndent();
22024        Collection<PackageParser.Package> packages = null;
22025        if (packageName != null) {
22026            PackageParser.Package targetPackage = mPackages.get(packageName);
22027            if (targetPackage != null) {
22028                packages = Collections.singletonList(targetPackage);
22029            } else {
22030                ipw.println("Unable to find package: " + packageName);
22031                return;
22032            }
22033        } else {
22034            packages = mPackages.values();
22035        }
22036
22037        for (PackageParser.Package pkg : packages) {
22038            ipw.println("[" + pkg.packageName + "]");
22039            ipw.increaseIndent();
22040
22041            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22042            if (stats == null) {
22043                ipw.println("(No recorded stats)");
22044            } else {
22045                stats.dump(ipw);
22046            }
22047            ipw.decreaseIndent();
22048        }
22049    }
22050
22051    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
22052        pw.println("Enabled overlay paths:");
22053        final int N = mEnabledOverlayPaths.size();
22054        for (int i = 0; i < N; i++) {
22055            final int userId = mEnabledOverlayPaths.keyAt(i);
22056            pw.println(String.format("    User %d:", userId));
22057            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
22058                mEnabledOverlayPaths.valueAt(i);
22059            final int M = userSpecificOverlays.size();
22060            for (int j = 0; j < M; j++) {
22061                final String targetPackageName = userSpecificOverlays.keyAt(j);
22062                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
22063                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
22064            }
22065        }
22066    }
22067
22068    private String dumpDomainString(String packageName) {
22069        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22070                .getList();
22071        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22072
22073        ArraySet<String> result = new ArraySet<>();
22074        if (iviList.size() > 0) {
22075            for (IntentFilterVerificationInfo ivi : iviList) {
22076                for (String host : ivi.getDomains()) {
22077                    result.add(host);
22078                }
22079            }
22080        }
22081        if (filters != null && filters.size() > 0) {
22082            for (IntentFilter filter : filters) {
22083                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22084                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22085                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22086                    result.addAll(filter.getHostsList());
22087                }
22088            }
22089        }
22090
22091        StringBuilder sb = new StringBuilder(result.size() * 16);
22092        for (String domain : result) {
22093            if (sb.length() > 0) sb.append(" ");
22094            sb.append(domain);
22095        }
22096        return sb.toString();
22097    }
22098
22099    // ------- apps on sdcard specific code -------
22100    static final boolean DEBUG_SD_INSTALL = false;
22101
22102    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22103
22104    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22105
22106    private boolean mMediaMounted = false;
22107
22108    static String getEncryptKey() {
22109        try {
22110            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22111                    SD_ENCRYPTION_KEYSTORE_NAME);
22112            if (sdEncKey == null) {
22113                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22114                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22115                if (sdEncKey == null) {
22116                    Slog.e(TAG, "Failed to create encryption keys");
22117                    return null;
22118                }
22119            }
22120            return sdEncKey;
22121        } catch (NoSuchAlgorithmException nsae) {
22122            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22123            return null;
22124        } catch (IOException ioe) {
22125            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22126            return null;
22127        }
22128    }
22129
22130    /*
22131     * Update media status on PackageManager.
22132     */
22133    @Override
22134    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22135        enforceSystemOrRoot("Media status can only be updated by the system");
22136        // reader; this apparently protects mMediaMounted, but should probably
22137        // be a different lock in that case.
22138        synchronized (mPackages) {
22139            Log.i(TAG, "Updating external media status from "
22140                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22141                    + (mediaStatus ? "mounted" : "unmounted"));
22142            if (DEBUG_SD_INSTALL)
22143                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22144                        + ", mMediaMounted=" + mMediaMounted);
22145            if (mediaStatus == mMediaMounted) {
22146                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22147                        : 0, -1);
22148                mHandler.sendMessage(msg);
22149                return;
22150            }
22151            mMediaMounted = mediaStatus;
22152        }
22153        // Queue up an async operation since the package installation may take a
22154        // little while.
22155        mHandler.post(new Runnable() {
22156            public void run() {
22157                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22158            }
22159        });
22160    }
22161
22162    /**
22163     * Called by StorageManagerService when the initial ASECs to scan are available.
22164     * Should block until all the ASEC containers are finished being scanned.
22165     */
22166    public void scanAvailableAsecs() {
22167        updateExternalMediaStatusInner(true, false, false);
22168    }
22169
22170    /*
22171     * Collect information of applications on external media, map them against
22172     * existing containers and update information based on current mount status.
22173     * Please note that we always have to report status if reportStatus has been
22174     * set to true especially when unloading packages.
22175     */
22176    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22177            boolean externalStorage) {
22178        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22179        int[] uidArr = EmptyArray.INT;
22180
22181        final String[] list = PackageHelper.getSecureContainerList();
22182        if (ArrayUtils.isEmpty(list)) {
22183            Log.i(TAG, "No secure containers found");
22184        } else {
22185            // Process list of secure containers and categorize them
22186            // as active or stale based on their package internal state.
22187
22188            // reader
22189            synchronized (mPackages) {
22190                for (String cid : list) {
22191                    // Leave stages untouched for now; installer service owns them
22192                    if (PackageInstallerService.isStageName(cid)) continue;
22193
22194                    if (DEBUG_SD_INSTALL)
22195                        Log.i(TAG, "Processing container " + cid);
22196                    String pkgName = getAsecPackageName(cid);
22197                    if (pkgName == null) {
22198                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22199                        continue;
22200                    }
22201                    if (DEBUG_SD_INSTALL)
22202                        Log.i(TAG, "Looking for pkg : " + pkgName);
22203
22204                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22205                    if (ps == null) {
22206                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22207                        continue;
22208                    }
22209
22210                    /*
22211                     * Skip packages that are not external if we're unmounting
22212                     * external storage.
22213                     */
22214                    if (externalStorage && !isMounted && !isExternal(ps)) {
22215                        continue;
22216                    }
22217
22218                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22219                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22220                    // The package status is changed only if the code path
22221                    // matches between settings and the container id.
22222                    if (ps.codePathString != null
22223                            && ps.codePathString.startsWith(args.getCodePath())) {
22224                        if (DEBUG_SD_INSTALL) {
22225                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22226                                    + " at code path: " + ps.codePathString);
22227                        }
22228
22229                        // We do have a valid package installed on sdcard
22230                        processCids.put(args, ps.codePathString);
22231                        final int uid = ps.appId;
22232                        if (uid != -1) {
22233                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22234                        }
22235                    } else {
22236                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22237                                + ps.codePathString);
22238                    }
22239                }
22240            }
22241
22242            Arrays.sort(uidArr);
22243        }
22244
22245        // Process packages with valid entries.
22246        if (isMounted) {
22247            if (DEBUG_SD_INSTALL)
22248                Log.i(TAG, "Loading packages");
22249            loadMediaPackages(processCids, uidArr, externalStorage);
22250            startCleaningPackages();
22251            mInstallerService.onSecureContainersAvailable();
22252        } else {
22253            if (DEBUG_SD_INSTALL)
22254                Log.i(TAG, "Unloading packages");
22255            unloadMediaPackages(processCids, uidArr, reportStatus);
22256        }
22257    }
22258
22259    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22260            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22261        final int size = infos.size();
22262        final String[] packageNames = new String[size];
22263        final int[] packageUids = new int[size];
22264        for (int i = 0; i < size; i++) {
22265            final ApplicationInfo info = infos.get(i);
22266            packageNames[i] = info.packageName;
22267            packageUids[i] = info.uid;
22268        }
22269        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22270                finishedReceiver);
22271    }
22272
22273    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22274            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22275        sendResourcesChangedBroadcast(mediaStatus, replacing,
22276                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22277    }
22278
22279    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22280            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22281        int size = pkgList.length;
22282        if (size > 0) {
22283            // Send broadcasts here
22284            Bundle extras = new Bundle();
22285            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22286            if (uidArr != null) {
22287                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22288            }
22289            if (replacing) {
22290                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22291            }
22292            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22293                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22294            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22295        }
22296    }
22297
22298   /*
22299     * Look at potentially valid container ids from processCids If package
22300     * information doesn't match the one on record or package scanning fails,
22301     * the cid is added to list of removeCids. We currently don't delete stale
22302     * containers.
22303     */
22304    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22305            boolean externalStorage) {
22306        ArrayList<String> pkgList = new ArrayList<String>();
22307        Set<AsecInstallArgs> keys = processCids.keySet();
22308
22309        for (AsecInstallArgs args : keys) {
22310            String codePath = processCids.get(args);
22311            if (DEBUG_SD_INSTALL)
22312                Log.i(TAG, "Loading container : " + args.cid);
22313            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22314            try {
22315                // Make sure there are no container errors first.
22316                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22317                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22318                            + " when installing from sdcard");
22319                    continue;
22320                }
22321                // Check code path here.
22322                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22323                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22324                            + " does not match one in settings " + codePath);
22325                    continue;
22326                }
22327                // Parse package
22328                int parseFlags = mDefParseFlags;
22329                if (args.isExternalAsec()) {
22330                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22331                }
22332                if (args.isFwdLocked()) {
22333                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22334                }
22335
22336                synchronized (mInstallLock) {
22337                    PackageParser.Package pkg = null;
22338                    try {
22339                        // Sadly we don't know the package name yet to freeze it
22340                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22341                                SCAN_IGNORE_FROZEN, 0, null);
22342                    } catch (PackageManagerException e) {
22343                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22344                    }
22345                    // Scan the package
22346                    if (pkg != null) {
22347                        /*
22348                         * TODO why is the lock being held? doPostInstall is
22349                         * called in other places without the lock. This needs
22350                         * to be straightened out.
22351                         */
22352                        // writer
22353                        synchronized (mPackages) {
22354                            retCode = PackageManager.INSTALL_SUCCEEDED;
22355                            pkgList.add(pkg.packageName);
22356                            // Post process args
22357                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22358                                    pkg.applicationInfo.uid);
22359                        }
22360                    } else {
22361                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22362                    }
22363                }
22364
22365            } finally {
22366                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22367                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22368                }
22369            }
22370        }
22371        // writer
22372        synchronized (mPackages) {
22373            // If the platform SDK has changed since the last time we booted,
22374            // we need to re-grant app permission to catch any new ones that
22375            // appear. This is really a hack, and means that apps can in some
22376            // cases get permissions that the user didn't initially explicitly
22377            // allow... it would be nice to have some better way to handle
22378            // this situation.
22379            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22380                    : mSettings.getInternalVersion();
22381            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22382                    : StorageManager.UUID_PRIVATE_INTERNAL;
22383
22384            int updateFlags = UPDATE_PERMISSIONS_ALL;
22385            if (ver.sdkVersion != mSdkVersion) {
22386                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22387                        + mSdkVersion + "; regranting permissions for external");
22388                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22389            }
22390            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22391
22392            // Yay, everything is now upgraded
22393            ver.forceCurrent();
22394
22395            // can downgrade to reader
22396            // Persist settings
22397            mSettings.writeLPr();
22398        }
22399        // Send a broadcast to let everyone know we are done processing
22400        if (pkgList.size() > 0) {
22401            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22402        }
22403    }
22404
22405   /*
22406     * Utility method to unload a list of specified containers
22407     */
22408    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22409        // Just unmount all valid containers.
22410        for (AsecInstallArgs arg : cidArgs) {
22411            synchronized (mInstallLock) {
22412                arg.doPostDeleteLI(false);
22413           }
22414       }
22415   }
22416
22417    /*
22418     * Unload packages mounted on external media. This involves deleting package
22419     * data from internal structures, sending broadcasts about disabled packages,
22420     * gc'ing to free up references, unmounting all secure containers
22421     * corresponding to packages on external media, and posting a
22422     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22423     * that we always have to post this message if status has been requested no
22424     * matter what.
22425     */
22426    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22427            final boolean reportStatus) {
22428        if (DEBUG_SD_INSTALL)
22429            Log.i(TAG, "unloading media packages");
22430        ArrayList<String> pkgList = new ArrayList<String>();
22431        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22432        final Set<AsecInstallArgs> keys = processCids.keySet();
22433        for (AsecInstallArgs args : keys) {
22434            String pkgName = args.getPackageName();
22435            if (DEBUG_SD_INSTALL)
22436                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22437            // Delete package internally
22438            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22439            synchronized (mInstallLock) {
22440                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22441                final boolean res;
22442                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22443                        "unloadMediaPackages")) {
22444                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22445                            null);
22446                }
22447                if (res) {
22448                    pkgList.add(pkgName);
22449                } else {
22450                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22451                    failedList.add(args);
22452                }
22453            }
22454        }
22455
22456        // reader
22457        synchronized (mPackages) {
22458            // We didn't update the settings after removing each package;
22459            // write them now for all packages.
22460            mSettings.writeLPr();
22461        }
22462
22463        // We have to absolutely send UPDATED_MEDIA_STATUS only
22464        // after confirming that all the receivers processed the ordered
22465        // broadcast when packages get disabled, force a gc to clean things up.
22466        // and unload all the containers.
22467        if (pkgList.size() > 0) {
22468            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22469                    new IIntentReceiver.Stub() {
22470                public void performReceive(Intent intent, int resultCode, String data,
22471                        Bundle extras, boolean ordered, boolean sticky,
22472                        int sendingUser) throws RemoteException {
22473                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22474                            reportStatus ? 1 : 0, 1, keys);
22475                    mHandler.sendMessage(msg);
22476                }
22477            });
22478        } else {
22479            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22480                    keys);
22481            mHandler.sendMessage(msg);
22482        }
22483    }
22484
22485    private void loadPrivatePackages(final VolumeInfo vol) {
22486        mHandler.post(new Runnable() {
22487            @Override
22488            public void run() {
22489                loadPrivatePackagesInner(vol);
22490            }
22491        });
22492    }
22493
22494    private void loadPrivatePackagesInner(VolumeInfo vol) {
22495        final String volumeUuid = vol.fsUuid;
22496        if (TextUtils.isEmpty(volumeUuid)) {
22497            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22498            return;
22499        }
22500
22501        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22502        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22503        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22504
22505        final VersionInfo ver;
22506        final List<PackageSetting> packages;
22507        synchronized (mPackages) {
22508            ver = mSettings.findOrCreateVersion(volumeUuid);
22509            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22510        }
22511
22512        for (PackageSetting ps : packages) {
22513            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22514            synchronized (mInstallLock) {
22515                final PackageParser.Package pkg;
22516                try {
22517                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22518                    loaded.add(pkg.applicationInfo);
22519
22520                } catch (PackageManagerException e) {
22521                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22522                }
22523
22524                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22525                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22526                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22527                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22528                }
22529            }
22530        }
22531
22532        // Reconcile app data for all started/unlocked users
22533        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22534        final UserManager um = mContext.getSystemService(UserManager.class);
22535        UserManagerInternal umInternal = getUserManagerInternal();
22536        for (UserInfo user : um.getUsers()) {
22537            final int flags;
22538            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22539                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22540            } else if (umInternal.isUserRunning(user.id)) {
22541                flags = StorageManager.FLAG_STORAGE_DE;
22542            } else {
22543                continue;
22544            }
22545
22546            try {
22547                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22548                synchronized (mInstallLock) {
22549                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22550                }
22551            } catch (IllegalStateException e) {
22552                // Device was probably ejected, and we'll process that event momentarily
22553                Slog.w(TAG, "Failed to prepare storage: " + e);
22554            }
22555        }
22556
22557        synchronized (mPackages) {
22558            int updateFlags = UPDATE_PERMISSIONS_ALL;
22559            if (ver.sdkVersion != mSdkVersion) {
22560                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22561                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22562                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22563            }
22564            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22565
22566            // Yay, everything is now upgraded
22567            ver.forceCurrent();
22568
22569            mSettings.writeLPr();
22570        }
22571
22572        for (PackageFreezer freezer : freezers) {
22573            freezer.close();
22574        }
22575
22576        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22577        sendResourcesChangedBroadcast(true, false, loaded, null);
22578    }
22579
22580    private void unloadPrivatePackages(final VolumeInfo vol) {
22581        mHandler.post(new Runnable() {
22582            @Override
22583            public void run() {
22584                unloadPrivatePackagesInner(vol);
22585            }
22586        });
22587    }
22588
22589    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22590        final String volumeUuid = vol.fsUuid;
22591        if (TextUtils.isEmpty(volumeUuid)) {
22592            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22593            return;
22594        }
22595
22596        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22597        synchronized (mInstallLock) {
22598        synchronized (mPackages) {
22599            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22600            for (PackageSetting ps : packages) {
22601                if (ps.pkg == null) continue;
22602
22603                final ApplicationInfo info = ps.pkg.applicationInfo;
22604                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22605                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22606
22607                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22608                        "unloadPrivatePackagesInner")) {
22609                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22610                            false, null)) {
22611                        unloaded.add(info);
22612                    } else {
22613                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22614                    }
22615                }
22616
22617                // Try very hard to release any references to this package
22618                // so we don't risk the system server being killed due to
22619                // open FDs
22620                AttributeCache.instance().removePackage(ps.name);
22621            }
22622
22623            mSettings.writeLPr();
22624        }
22625        }
22626
22627        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22628        sendResourcesChangedBroadcast(false, false, unloaded, null);
22629
22630        // Try very hard to release any references to this path so we don't risk
22631        // the system server being killed due to open FDs
22632        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22633
22634        for (int i = 0; i < 3; i++) {
22635            System.gc();
22636            System.runFinalization();
22637        }
22638    }
22639
22640    private void assertPackageKnown(String volumeUuid, String packageName)
22641            throws PackageManagerException {
22642        synchronized (mPackages) {
22643            // Normalize package name to handle renamed packages
22644            packageName = normalizePackageNameLPr(packageName);
22645
22646            final PackageSetting ps = mSettings.mPackages.get(packageName);
22647            if (ps == null) {
22648                throw new PackageManagerException("Package " + packageName + " is unknown");
22649            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22650                throw new PackageManagerException(
22651                        "Package " + packageName + " found on unknown volume " + volumeUuid
22652                                + "; expected volume " + ps.volumeUuid);
22653            }
22654        }
22655    }
22656
22657    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22658            throws PackageManagerException {
22659        synchronized (mPackages) {
22660            // Normalize package name to handle renamed packages
22661            packageName = normalizePackageNameLPr(packageName);
22662
22663            final PackageSetting ps = mSettings.mPackages.get(packageName);
22664            if (ps == null) {
22665                throw new PackageManagerException("Package " + packageName + " is unknown");
22666            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22667                throw new PackageManagerException(
22668                        "Package " + packageName + " found on unknown volume " + volumeUuid
22669                                + "; expected volume " + ps.volumeUuid);
22670            } else if (!ps.getInstalled(userId)) {
22671                throw new PackageManagerException(
22672                        "Package " + packageName + " not installed for user " + userId);
22673            }
22674        }
22675    }
22676
22677    private List<String> collectAbsoluteCodePaths() {
22678        synchronized (mPackages) {
22679            List<String> codePaths = new ArrayList<>();
22680            final int packageCount = mSettings.mPackages.size();
22681            for (int i = 0; i < packageCount; i++) {
22682                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22683                codePaths.add(ps.codePath.getAbsolutePath());
22684            }
22685            return codePaths;
22686        }
22687    }
22688
22689    /**
22690     * Examine all apps present on given mounted volume, and destroy apps that
22691     * aren't expected, either due to uninstallation or reinstallation on
22692     * another volume.
22693     */
22694    private void reconcileApps(String volumeUuid) {
22695        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22696        List<File> filesToDelete = null;
22697
22698        final File[] files = FileUtils.listFilesOrEmpty(
22699                Environment.getDataAppDirectory(volumeUuid));
22700        for (File file : files) {
22701            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22702                    && !PackageInstallerService.isStageName(file.getName());
22703            if (!isPackage) {
22704                // Ignore entries which are not packages
22705                continue;
22706            }
22707
22708            String absolutePath = file.getAbsolutePath();
22709
22710            boolean pathValid = false;
22711            final int absoluteCodePathCount = absoluteCodePaths.size();
22712            for (int i = 0; i < absoluteCodePathCount; i++) {
22713                String absoluteCodePath = absoluteCodePaths.get(i);
22714                if (absolutePath.startsWith(absoluteCodePath)) {
22715                    pathValid = true;
22716                    break;
22717                }
22718            }
22719
22720            if (!pathValid) {
22721                if (filesToDelete == null) {
22722                    filesToDelete = new ArrayList<>();
22723                }
22724                filesToDelete.add(file);
22725            }
22726        }
22727
22728        if (filesToDelete != null) {
22729            final int fileToDeleteCount = filesToDelete.size();
22730            for (int i = 0; i < fileToDeleteCount; i++) {
22731                File fileToDelete = filesToDelete.get(i);
22732                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22733                synchronized (mInstallLock) {
22734                    removeCodePathLI(fileToDelete);
22735                }
22736            }
22737        }
22738    }
22739
22740    /**
22741     * Reconcile all app data for the given user.
22742     * <p>
22743     * Verifies that directories exist and that ownership and labeling is
22744     * correct for all installed apps on all mounted volumes.
22745     */
22746    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22747        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22748        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22749            final String volumeUuid = vol.getFsUuid();
22750            synchronized (mInstallLock) {
22751                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22752            }
22753        }
22754    }
22755
22756    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22757            boolean migrateAppData) {
22758        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22759    }
22760
22761    /**
22762     * Reconcile all app data on given mounted volume.
22763     * <p>
22764     * Destroys app data that isn't expected, either due to uninstallation or
22765     * reinstallation on another volume.
22766     * <p>
22767     * Verifies that directories exist and that ownership and labeling is
22768     * correct for all installed apps.
22769     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22770     */
22771    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22772            boolean migrateAppData, boolean onlyCoreApps) {
22773        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22774                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22775        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22776
22777        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22778        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22779
22780        // First look for stale data that doesn't belong, and check if things
22781        // have changed since we did our last restorecon
22782        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22783            if (StorageManager.isFileEncryptedNativeOrEmulated()
22784                    && !StorageManager.isUserKeyUnlocked(userId)) {
22785                throw new RuntimeException(
22786                        "Yikes, someone asked us to reconcile CE storage while " + userId
22787                                + " was still locked; this would have caused massive data loss!");
22788            }
22789
22790            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22791            for (File file : files) {
22792                final String packageName = file.getName();
22793                try {
22794                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22795                } catch (PackageManagerException e) {
22796                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22797                    try {
22798                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22799                                StorageManager.FLAG_STORAGE_CE, 0);
22800                    } catch (InstallerException e2) {
22801                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22802                    }
22803                }
22804            }
22805        }
22806        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22807            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22808            for (File file : files) {
22809                final String packageName = file.getName();
22810                try {
22811                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22812                } catch (PackageManagerException e) {
22813                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22814                    try {
22815                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22816                                StorageManager.FLAG_STORAGE_DE, 0);
22817                    } catch (InstallerException e2) {
22818                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22819                    }
22820                }
22821            }
22822        }
22823
22824        // Ensure that data directories are ready to roll for all packages
22825        // installed for this volume and user
22826        final List<PackageSetting> packages;
22827        synchronized (mPackages) {
22828            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22829        }
22830        int preparedCount = 0;
22831        for (PackageSetting ps : packages) {
22832            final String packageName = ps.name;
22833            if (ps.pkg == null) {
22834                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22835                // TODO: might be due to legacy ASEC apps; we should circle back
22836                // and reconcile again once they're scanned
22837                continue;
22838            }
22839            // Skip non-core apps if requested
22840            if (onlyCoreApps && !ps.pkg.coreApp) {
22841                result.add(packageName);
22842                continue;
22843            }
22844
22845            if (ps.getInstalled(userId)) {
22846                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22847                preparedCount++;
22848            }
22849        }
22850
22851        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22852        return result;
22853    }
22854
22855    /**
22856     * Prepare app data for the given app just after it was installed or
22857     * upgraded. This method carefully only touches users that it's installed
22858     * for, and it forces a restorecon to handle any seinfo changes.
22859     * <p>
22860     * Verifies that directories exist and that ownership and labeling is
22861     * correct for all installed apps. If there is an ownership mismatch, it
22862     * will try recovering system apps by wiping data; third-party app data is
22863     * left intact.
22864     * <p>
22865     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22866     */
22867    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22868        final PackageSetting ps;
22869        synchronized (mPackages) {
22870            ps = mSettings.mPackages.get(pkg.packageName);
22871            mSettings.writeKernelMappingLPr(ps);
22872        }
22873
22874        final UserManager um = mContext.getSystemService(UserManager.class);
22875        UserManagerInternal umInternal = getUserManagerInternal();
22876        for (UserInfo user : um.getUsers()) {
22877            final int flags;
22878            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22879                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22880            } else if (umInternal.isUserRunning(user.id)) {
22881                flags = StorageManager.FLAG_STORAGE_DE;
22882            } else {
22883                continue;
22884            }
22885
22886            if (ps.getInstalled(user.id)) {
22887                // TODO: when user data is locked, mark that we're still dirty
22888                prepareAppDataLIF(pkg, user.id, flags);
22889            }
22890        }
22891    }
22892
22893    /**
22894     * Prepare app data for the given app.
22895     * <p>
22896     * Verifies that directories exist and that ownership and labeling is
22897     * correct for all installed apps. If there is an ownership mismatch, this
22898     * will try recovering system apps by wiping data; third-party app data is
22899     * left intact.
22900     */
22901    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22902        if (pkg == null) {
22903            Slog.wtf(TAG, "Package was null!", new Throwable());
22904            return;
22905        }
22906        prepareAppDataLeafLIF(pkg, userId, flags);
22907        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22908        for (int i = 0; i < childCount; i++) {
22909            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22910        }
22911    }
22912
22913    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22914            boolean maybeMigrateAppData) {
22915        prepareAppDataLIF(pkg, userId, flags);
22916
22917        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22918            // We may have just shuffled around app data directories, so
22919            // prepare them one more time
22920            prepareAppDataLIF(pkg, userId, flags);
22921        }
22922    }
22923
22924    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22925        if (DEBUG_APP_DATA) {
22926            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22927                    + Integer.toHexString(flags));
22928        }
22929
22930        final String volumeUuid = pkg.volumeUuid;
22931        final String packageName = pkg.packageName;
22932        final ApplicationInfo app = pkg.applicationInfo;
22933        final int appId = UserHandle.getAppId(app.uid);
22934
22935        Preconditions.checkNotNull(app.seInfo);
22936
22937        long ceDataInode = -1;
22938        try {
22939            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22940                    appId, app.seInfo, app.targetSdkVersion);
22941        } catch (InstallerException e) {
22942            if (app.isSystemApp()) {
22943                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22944                        + ", but trying to recover: " + e);
22945                destroyAppDataLeafLIF(pkg, userId, flags);
22946                try {
22947                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22948                            appId, app.seInfo, app.targetSdkVersion);
22949                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22950                } catch (InstallerException e2) {
22951                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22952                }
22953            } else {
22954                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22955            }
22956        }
22957
22958        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22959            // TODO: mark this structure as dirty so we persist it!
22960            synchronized (mPackages) {
22961                final PackageSetting ps = mSettings.mPackages.get(packageName);
22962                if (ps != null) {
22963                    ps.setCeDataInode(ceDataInode, userId);
22964                }
22965            }
22966        }
22967
22968        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22969    }
22970
22971    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22972        if (pkg == null) {
22973            Slog.wtf(TAG, "Package was null!", new Throwable());
22974            return;
22975        }
22976        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22977        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22978        for (int i = 0; i < childCount; i++) {
22979            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22980        }
22981    }
22982
22983    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22984        final String volumeUuid = pkg.volumeUuid;
22985        final String packageName = pkg.packageName;
22986        final ApplicationInfo app = pkg.applicationInfo;
22987
22988        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22989            // Create a native library symlink only if we have native libraries
22990            // and if the native libraries are 32 bit libraries. We do not provide
22991            // this symlink for 64 bit libraries.
22992            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22993                final String nativeLibPath = app.nativeLibraryDir;
22994                try {
22995                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22996                            nativeLibPath, userId);
22997                } catch (InstallerException e) {
22998                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22999                }
23000            }
23001        }
23002    }
23003
23004    /**
23005     * For system apps on non-FBE devices, this method migrates any existing
23006     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23007     * requested by the app.
23008     */
23009    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23010        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23011                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23012            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23013                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23014            try {
23015                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23016                        storageTarget);
23017            } catch (InstallerException e) {
23018                logCriticalInfo(Log.WARN,
23019                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23020            }
23021            return true;
23022        } else {
23023            return false;
23024        }
23025    }
23026
23027    public PackageFreezer freezePackage(String packageName, String killReason) {
23028        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23029    }
23030
23031    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23032        return new PackageFreezer(packageName, userId, killReason);
23033    }
23034
23035    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23036            String killReason) {
23037        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23038    }
23039
23040    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23041            String killReason) {
23042        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23043            return new PackageFreezer();
23044        } else {
23045            return freezePackage(packageName, userId, killReason);
23046        }
23047    }
23048
23049    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23050            String killReason) {
23051        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23052    }
23053
23054    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23055            String killReason) {
23056        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23057            return new PackageFreezer();
23058        } else {
23059            return freezePackage(packageName, userId, killReason);
23060        }
23061    }
23062
23063    /**
23064     * Class that freezes and kills the given package upon creation, and
23065     * unfreezes it upon closing. This is typically used when doing surgery on
23066     * app code/data to prevent the app from running while you're working.
23067     */
23068    private class PackageFreezer implements AutoCloseable {
23069        private final String mPackageName;
23070        private final PackageFreezer[] mChildren;
23071
23072        private final boolean mWeFroze;
23073
23074        private final AtomicBoolean mClosed = new AtomicBoolean();
23075        private final CloseGuard mCloseGuard = CloseGuard.get();
23076
23077        /**
23078         * Create and return a stub freezer that doesn't actually do anything,
23079         * typically used when someone requested
23080         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23081         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23082         */
23083        public PackageFreezer() {
23084            mPackageName = null;
23085            mChildren = null;
23086            mWeFroze = false;
23087            mCloseGuard.open("close");
23088        }
23089
23090        public PackageFreezer(String packageName, int userId, String killReason) {
23091            synchronized (mPackages) {
23092                mPackageName = packageName;
23093                mWeFroze = mFrozenPackages.add(mPackageName);
23094
23095                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23096                if (ps != null) {
23097                    killApplication(ps.name, ps.appId, userId, killReason);
23098                }
23099
23100                final PackageParser.Package p = mPackages.get(packageName);
23101                if (p != null && p.childPackages != null) {
23102                    final int N = p.childPackages.size();
23103                    mChildren = new PackageFreezer[N];
23104                    for (int i = 0; i < N; i++) {
23105                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23106                                userId, killReason);
23107                    }
23108                } else {
23109                    mChildren = null;
23110                }
23111            }
23112            mCloseGuard.open("close");
23113        }
23114
23115        @Override
23116        protected void finalize() throws Throwable {
23117            try {
23118                mCloseGuard.warnIfOpen();
23119                close();
23120            } finally {
23121                super.finalize();
23122            }
23123        }
23124
23125        @Override
23126        public void close() {
23127            mCloseGuard.close();
23128            if (mClosed.compareAndSet(false, true)) {
23129                synchronized (mPackages) {
23130                    if (mWeFroze) {
23131                        mFrozenPackages.remove(mPackageName);
23132                    }
23133
23134                    if (mChildren != null) {
23135                        for (PackageFreezer freezer : mChildren) {
23136                            freezer.close();
23137                        }
23138                    }
23139                }
23140            }
23141        }
23142    }
23143
23144    /**
23145     * Verify that given package is currently frozen.
23146     */
23147    private void checkPackageFrozen(String packageName) {
23148        synchronized (mPackages) {
23149            if (!mFrozenPackages.contains(packageName)) {
23150                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23151            }
23152        }
23153    }
23154
23155    @Override
23156    public int movePackage(final String packageName, final String volumeUuid) {
23157        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23158
23159        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
23160        final int moveId = mNextMoveId.getAndIncrement();
23161        mHandler.post(new Runnable() {
23162            @Override
23163            public void run() {
23164                try {
23165                    movePackageInternal(packageName, volumeUuid, moveId, user);
23166                } catch (PackageManagerException e) {
23167                    Slog.w(TAG, "Failed to move " + packageName, e);
23168                    mMoveCallbacks.notifyStatusChanged(moveId,
23169                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23170                }
23171            }
23172        });
23173        return moveId;
23174    }
23175
23176    private void movePackageInternal(final String packageName, final String volumeUuid,
23177            final int moveId, UserHandle user) throws PackageManagerException {
23178        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23179        final PackageManager pm = mContext.getPackageManager();
23180
23181        final boolean currentAsec;
23182        final String currentVolumeUuid;
23183        final File codeFile;
23184        final String installerPackageName;
23185        final String packageAbiOverride;
23186        final int appId;
23187        final String seinfo;
23188        final String label;
23189        final int targetSdkVersion;
23190        final PackageFreezer freezer;
23191        final int[] installedUserIds;
23192
23193        // reader
23194        synchronized (mPackages) {
23195            final PackageParser.Package pkg = mPackages.get(packageName);
23196            final PackageSetting ps = mSettings.mPackages.get(packageName);
23197            if (pkg == null || ps == null) {
23198                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23199            }
23200
23201            if (pkg.applicationInfo.isSystemApp()) {
23202                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23203                        "Cannot move system application");
23204            }
23205
23206            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23207            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23208                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23209            if (isInternalStorage && !allow3rdPartyOnInternal) {
23210                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23211                        "3rd party apps are not allowed on internal storage");
23212            }
23213
23214            if (pkg.applicationInfo.isExternalAsec()) {
23215                currentAsec = true;
23216                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23217            } else if (pkg.applicationInfo.isForwardLocked()) {
23218                currentAsec = true;
23219                currentVolumeUuid = "forward_locked";
23220            } else {
23221                currentAsec = false;
23222                currentVolumeUuid = ps.volumeUuid;
23223
23224                final File probe = new File(pkg.codePath);
23225                final File probeOat = new File(probe, "oat");
23226                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23227                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23228                            "Move only supported for modern cluster style installs");
23229                }
23230            }
23231
23232            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23233                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23234                        "Package already moved to " + volumeUuid);
23235            }
23236            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23237                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23238                        "Device admin cannot be moved");
23239            }
23240
23241            if (mFrozenPackages.contains(packageName)) {
23242                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23243                        "Failed to move already frozen package");
23244            }
23245
23246            codeFile = new File(pkg.codePath);
23247            installerPackageName = ps.installerPackageName;
23248            packageAbiOverride = ps.cpuAbiOverrideString;
23249            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23250            seinfo = pkg.applicationInfo.seInfo;
23251            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23252            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23253            freezer = freezePackage(packageName, "movePackageInternal");
23254            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23255        }
23256
23257        final Bundle extras = new Bundle();
23258        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23259        extras.putString(Intent.EXTRA_TITLE, label);
23260        mMoveCallbacks.notifyCreated(moveId, extras);
23261
23262        int installFlags;
23263        final boolean moveCompleteApp;
23264        final File measurePath;
23265
23266        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23267            installFlags = INSTALL_INTERNAL;
23268            moveCompleteApp = !currentAsec;
23269            measurePath = Environment.getDataAppDirectory(volumeUuid);
23270        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23271            installFlags = INSTALL_EXTERNAL;
23272            moveCompleteApp = false;
23273            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23274        } else {
23275            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23276            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23277                    || !volume.isMountedWritable()) {
23278                freezer.close();
23279                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23280                        "Move location not mounted private volume");
23281            }
23282
23283            Preconditions.checkState(!currentAsec);
23284
23285            installFlags = INSTALL_INTERNAL;
23286            moveCompleteApp = true;
23287            measurePath = Environment.getDataAppDirectory(volumeUuid);
23288        }
23289
23290        final PackageStats stats = new PackageStats(null, -1);
23291        synchronized (mInstaller) {
23292            for (int userId : installedUserIds) {
23293                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23294                    freezer.close();
23295                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23296                            "Failed to measure package size");
23297                }
23298            }
23299        }
23300
23301        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23302                + stats.dataSize);
23303
23304        final long startFreeBytes = measurePath.getUsableSpace();
23305        final long sizeBytes;
23306        if (moveCompleteApp) {
23307            sizeBytes = stats.codeSize + stats.dataSize;
23308        } else {
23309            sizeBytes = stats.codeSize;
23310        }
23311
23312        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23313            freezer.close();
23314            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23315                    "Not enough free space to move");
23316        }
23317
23318        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23319
23320        final CountDownLatch installedLatch = new CountDownLatch(1);
23321        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23322            @Override
23323            public void onUserActionRequired(Intent intent) throws RemoteException {
23324                throw new IllegalStateException();
23325            }
23326
23327            @Override
23328            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23329                    Bundle extras) throws RemoteException {
23330                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23331                        + PackageManager.installStatusToString(returnCode, msg));
23332
23333                installedLatch.countDown();
23334                freezer.close();
23335
23336                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23337                switch (status) {
23338                    case PackageInstaller.STATUS_SUCCESS:
23339                        mMoveCallbacks.notifyStatusChanged(moveId,
23340                                PackageManager.MOVE_SUCCEEDED);
23341                        break;
23342                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23343                        mMoveCallbacks.notifyStatusChanged(moveId,
23344                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23345                        break;
23346                    default:
23347                        mMoveCallbacks.notifyStatusChanged(moveId,
23348                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23349                        break;
23350                }
23351            }
23352        };
23353
23354        final MoveInfo move;
23355        if (moveCompleteApp) {
23356            // Kick off a thread to report progress estimates
23357            new Thread() {
23358                @Override
23359                public void run() {
23360                    while (true) {
23361                        try {
23362                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23363                                break;
23364                            }
23365                        } catch (InterruptedException ignored) {
23366                        }
23367
23368                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23369                        final int progress = 10 + (int) MathUtils.constrain(
23370                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23371                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23372                    }
23373                }
23374            }.start();
23375
23376            final String dataAppName = codeFile.getName();
23377            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23378                    dataAppName, appId, seinfo, targetSdkVersion);
23379        } else {
23380            move = null;
23381        }
23382
23383        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23384
23385        final Message msg = mHandler.obtainMessage(INIT_COPY);
23386        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23387        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23388                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23389                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23390                PackageManager.INSTALL_REASON_UNKNOWN);
23391        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23392        msg.obj = params;
23393
23394        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23395                System.identityHashCode(msg.obj));
23396        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23397                System.identityHashCode(msg.obj));
23398
23399        mHandler.sendMessage(msg);
23400    }
23401
23402    @Override
23403    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23404        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23405
23406        final int realMoveId = mNextMoveId.getAndIncrement();
23407        final Bundle extras = new Bundle();
23408        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23409        mMoveCallbacks.notifyCreated(realMoveId, extras);
23410
23411        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23412            @Override
23413            public void onCreated(int moveId, Bundle extras) {
23414                // Ignored
23415            }
23416
23417            @Override
23418            public void onStatusChanged(int moveId, int status, long estMillis) {
23419                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23420            }
23421        };
23422
23423        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23424        storage.setPrimaryStorageUuid(volumeUuid, callback);
23425        return realMoveId;
23426    }
23427
23428    @Override
23429    public int getMoveStatus(int moveId) {
23430        mContext.enforceCallingOrSelfPermission(
23431                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23432        return mMoveCallbacks.mLastStatus.get(moveId);
23433    }
23434
23435    @Override
23436    public void registerMoveCallback(IPackageMoveObserver callback) {
23437        mContext.enforceCallingOrSelfPermission(
23438                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23439        mMoveCallbacks.register(callback);
23440    }
23441
23442    @Override
23443    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23444        mContext.enforceCallingOrSelfPermission(
23445                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23446        mMoveCallbacks.unregister(callback);
23447    }
23448
23449    @Override
23450    public boolean setInstallLocation(int loc) {
23451        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23452                null);
23453        if (getInstallLocation() == loc) {
23454            return true;
23455        }
23456        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23457                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23458            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23459                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23460            return true;
23461        }
23462        return false;
23463   }
23464
23465    @Override
23466    public int getInstallLocation() {
23467        // allow instant app access
23468        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23469                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23470                PackageHelper.APP_INSTALL_AUTO);
23471    }
23472
23473    /** Called by UserManagerService */
23474    void cleanUpUser(UserManagerService userManager, int userHandle) {
23475        synchronized (mPackages) {
23476            mDirtyUsers.remove(userHandle);
23477            mUserNeedsBadging.delete(userHandle);
23478            mSettings.removeUserLPw(userHandle);
23479            mPendingBroadcasts.remove(userHandle);
23480            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23481            removeUnusedPackagesLPw(userManager, userHandle);
23482        }
23483    }
23484
23485    /**
23486     * We're removing userHandle and would like to remove any downloaded packages
23487     * that are no longer in use by any other user.
23488     * @param userHandle the user being removed
23489     */
23490    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23491        final boolean DEBUG_CLEAN_APKS = false;
23492        int [] users = userManager.getUserIds();
23493        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23494        while (psit.hasNext()) {
23495            PackageSetting ps = psit.next();
23496            if (ps.pkg == null) {
23497                continue;
23498            }
23499            final String packageName = ps.pkg.packageName;
23500            // Skip over if system app
23501            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23502                continue;
23503            }
23504            if (DEBUG_CLEAN_APKS) {
23505                Slog.i(TAG, "Checking package " + packageName);
23506            }
23507            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23508            if (keep) {
23509                if (DEBUG_CLEAN_APKS) {
23510                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23511                }
23512            } else {
23513                for (int i = 0; i < users.length; i++) {
23514                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23515                        keep = true;
23516                        if (DEBUG_CLEAN_APKS) {
23517                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23518                                    + users[i]);
23519                        }
23520                        break;
23521                    }
23522                }
23523            }
23524            if (!keep) {
23525                if (DEBUG_CLEAN_APKS) {
23526                    Slog.i(TAG, "  Removing package " + packageName);
23527                }
23528                mHandler.post(new Runnable() {
23529                    public void run() {
23530                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23531                                userHandle, 0);
23532                    } //end run
23533                });
23534            }
23535        }
23536    }
23537
23538    /** Called by UserManagerService */
23539    void createNewUser(int userId, String[] disallowedPackages) {
23540        synchronized (mInstallLock) {
23541            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23542        }
23543        synchronized (mPackages) {
23544            scheduleWritePackageRestrictionsLocked(userId);
23545            scheduleWritePackageListLocked(userId);
23546            applyFactoryDefaultBrowserLPw(userId);
23547            primeDomainVerificationsLPw(userId);
23548        }
23549    }
23550
23551    void onNewUserCreated(final int userId) {
23552        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23553        // If permission review for legacy apps is required, we represent
23554        // dagerous permissions for such apps as always granted runtime
23555        // permissions to keep per user flag state whether review is needed.
23556        // Hence, if a new user is added we have to propagate dangerous
23557        // permission grants for these legacy apps.
23558        if (mPermissionReviewRequired) {
23559            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23560                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23561        }
23562    }
23563
23564    @Override
23565    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23566        mContext.enforceCallingOrSelfPermission(
23567                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23568                "Only package verification agents can read the verifier device identity");
23569
23570        synchronized (mPackages) {
23571            return mSettings.getVerifierDeviceIdentityLPw();
23572        }
23573    }
23574
23575    @Override
23576    public void setPermissionEnforced(String permission, boolean enforced) {
23577        // TODO: Now that we no longer change GID for storage, this should to away.
23578        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23579                "setPermissionEnforced");
23580        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23581            synchronized (mPackages) {
23582                if (mSettings.mReadExternalStorageEnforced == null
23583                        || mSettings.mReadExternalStorageEnforced != enforced) {
23584                    mSettings.mReadExternalStorageEnforced = enforced;
23585                    mSettings.writeLPr();
23586                }
23587            }
23588            // kill any non-foreground processes so we restart them and
23589            // grant/revoke the GID.
23590            final IActivityManager am = ActivityManager.getService();
23591            if (am != null) {
23592                final long token = Binder.clearCallingIdentity();
23593                try {
23594                    am.killProcessesBelowForeground("setPermissionEnforcement");
23595                } catch (RemoteException e) {
23596                } finally {
23597                    Binder.restoreCallingIdentity(token);
23598                }
23599            }
23600        } else {
23601            throw new IllegalArgumentException("No selective enforcement for " + permission);
23602        }
23603    }
23604
23605    @Override
23606    @Deprecated
23607    public boolean isPermissionEnforced(String permission) {
23608        // allow instant applications
23609        return true;
23610    }
23611
23612    @Override
23613    public boolean isStorageLow() {
23614        // allow instant applications
23615        final long token = Binder.clearCallingIdentity();
23616        try {
23617            final DeviceStorageMonitorInternal
23618                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23619            if (dsm != null) {
23620                return dsm.isMemoryLow();
23621            } else {
23622                return false;
23623            }
23624        } finally {
23625            Binder.restoreCallingIdentity(token);
23626        }
23627    }
23628
23629    @Override
23630    public IPackageInstaller getPackageInstaller() {
23631        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23632            return null;
23633        }
23634        return mInstallerService;
23635    }
23636
23637    private boolean userNeedsBadging(int userId) {
23638        int index = mUserNeedsBadging.indexOfKey(userId);
23639        if (index < 0) {
23640            final UserInfo userInfo;
23641            final long token = Binder.clearCallingIdentity();
23642            try {
23643                userInfo = sUserManager.getUserInfo(userId);
23644            } finally {
23645                Binder.restoreCallingIdentity(token);
23646            }
23647            final boolean b;
23648            if (userInfo != null && userInfo.isManagedProfile()) {
23649                b = true;
23650            } else {
23651                b = false;
23652            }
23653            mUserNeedsBadging.put(userId, b);
23654            return b;
23655        }
23656        return mUserNeedsBadging.valueAt(index);
23657    }
23658
23659    @Override
23660    public KeySet getKeySetByAlias(String packageName, String alias) {
23661        if (packageName == null || alias == null) {
23662            return null;
23663        }
23664        synchronized(mPackages) {
23665            final PackageParser.Package pkg = mPackages.get(packageName);
23666            if (pkg == null) {
23667                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23668                throw new IllegalArgumentException("Unknown package: " + packageName);
23669            }
23670            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23671            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23672        }
23673    }
23674
23675    @Override
23676    public KeySet getSigningKeySet(String packageName) {
23677        if (packageName == null) {
23678            return null;
23679        }
23680        synchronized(mPackages) {
23681            final int callingUid = Binder.getCallingUid();
23682            final int callingUserId = UserHandle.getUserId(callingUid);
23683            final PackageParser.Package pkg = mPackages.get(packageName);
23684            if (pkg == null) {
23685                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23686                throw new IllegalArgumentException("Unknown package: " + packageName);
23687            }
23688            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23689            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23690                // filter and pretend the package doesn't exist
23691                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23692                        + ", uid:" + callingUid);
23693                throw new IllegalArgumentException("Unknown package: " + packageName);
23694            }
23695            if (pkg.applicationInfo.uid != callingUid
23696                    && Process.SYSTEM_UID != callingUid) {
23697                throw new SecurityException("May not access signing KeySet of other apps.");
23698            }
23699            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23700            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23701        }
23702    }
23703
23704    @Override
23705    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23706        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23707            return false;
23708        }
23709        if (packageName == null || ks == null) {
23710            return false;
23711        }
23712        synchronized(mPackages) {
23713            final PackageParser.Package pkg = mPackages.get(packageName);
23714            if (pkg == null) {
23715                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23716                throw new IllegalArgumentException("Unknown package: " + packageName);
23717            }
23718            IBinder ksh = ks.getToken();
23719            if (ksh instanceof KeySetHandle) {
23720                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23721                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23722            }
23723            return false;
23724        }
23725    }
23726
23727    @Override
23728    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23729        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23730            return false;
23731        }
23732        if (packageName == null || ks == null) {
23733            return false;
23734        }
23735        synchronized(mPackages) {
23736            final PackageParser.Package pkg = mPackages.get(packageName);
23737            if (pkg == null) {
23738                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23739                throw new IllegalArgumentException("Unknown package: " + packageName);
23740            }
23741            IBinder ksh = ks.getToken();
23742            if (ksh instanceof KeySetHandle) {
23743                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23744                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23745            }
23746            return false;
23747        }
23748    }
23749
23750    private void deletePackageIfUnusedLPr(final String packageName) {
23751        PackageSetting ps = mSettings.mPackages.get(packageName);
23752        if (ps == null) {
23753            return;
23754        }
23755        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23756            // TODO Implement atomic delete if package is unused
23757            // It is currently possible that the package will be deleted even if it is installed
23758            // after this method returns.
23759            mHandler.post(new Runnable() {
23760                public void run() {
23761                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23762                            0, PackageManager.DELETE_ALL_USERS);
23763                }
23764            });
23765        }
23766    }
23767
23768    /**
23769     * Check and throw if the given before/after packages would be considered a
23770     * downgrade.
23771     */
23772    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23773            throws PackageManagerException {
23774        if (after.versionCode < before.mVersionCode) {
23775            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23776                    "Update version code " + after.versionCode + " is older than current "
23777                    + before.mVersionCode);
23778        } else if (after.versionCode == before.mVersionCode) {
23779            if (after.baseRevisionCode < before.baseRevisionCode) {
23780                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23781                        "Update base revision code " + after.baseRevisionCode
23782                        + " is older than current " + before.baseRevisionCode);
23783            }
23784
23785            if (!ArrayUtils.isEmpty(after.splitNames)) {
23786                for (int i = 0; i < after.splitNames.length; i++) {
23787                    final String splitName = after.splitNames[i];
23788                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23789                    if (j != -1) {
23790                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23791                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23792                                    "Update split " + splitName + " revision code "
23793                                    + after.splitRevisionCodes[i] + " is older than current "
23794                                    + before.splitRevisionCodes[j]);
23795                        }
23796                    }
23797                }
23798            }
23799        }
23800    }
23801
23802    private static class MoveCallbacks extends Handler {
23803        private static final int MSG_CREATED = 1;
23804        private static final int MSG_STATUS_CHANGED = 2;
23805
23806        private final RemoteCallbackList<IPackageMoveObserver>
23807                mCallbacks = new RemoteCallbackList<>();
23808
23809        private final SparseIntArray mLastStatus = new SparseIntArray();
23810
23811        public MoveCallbacks(Looper looper) {
23812            super(looper);
23813        }
23814
23815        public void register(IPackageMoveObserver callback) {
23816            mCallbacks.register(callback);
23817        }
23818
23819        public void unregister(IPackageMoveObserver callback) {
23820            mCallbacks.unregister(callback);
23821        }
23822
23823        @Override
23824        public void handleMessage(Message msg) {
23825            final SomeArgs args = (SomeArgs) msg.obj;
23826            final int n = mCallbacks.beginBroadcast();
23827            for (int i = 0; i < n; i++) {
23828                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23829                try {
23830                    invokeCallback(callback, msg.what, args);
23831                } catch (RemoteException ignored) {
23832                }
23833            }
23834            mCallbacks.finishBroadcast();
23835            args.recycle();
23836        }
23837
23838        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23839                throws RemoteException {
23840            switch (what) {
23841                case MSG_CREATED: {
23842                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23843                    break;
23844                }
23845                case MSG_STATUS_CHANGED: {
23846                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23847                    break;
23848                }
23849            }
23850        }
23851
23852        private void notifyCreated(int moveId, Bundle extras) {
23853            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23854
23855            final SomeArgs args = SomeArgs.obtain();
23856            args.argi1 = moveId;
23857            args.arg2 = extras;
23858            obtainMessage(MSG_CREATED, args).sendToTarget();
23859        }
23860
23861        private void notifyStatusChanged(int moveId, int status) {
23862            notifyStatusChanged(moveId, status, -1);
23863        }
23864
23865        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23866            Slog.v(TAG, "Move " + moveId + " status " + status);
23867
23868            final SomeArgs args = SomeArgs.obtain();
23869            args.argi1 = moveId;
23870            args.argi2 = status;
23871            args.arg3 = estMillis;
23872            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23873
23874            synchronized (mLastStatus) {
23875                mLastStatus.put(moveId, status);
23876            }
23877        }
23878    }
23879
23880    private final static class OnPermissionChangeListeners extends Handler {
23881        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23882
23883        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23884                new RemoteCallbackList<>();
23885
23886        public OnPermissionChangeListeners(Looper looper) {
23887            super(looper);
23888        }
23889
23890        @Override
23891        public void handleMessage(Message msg) {
23892            switch (msg.what) {
23893                case MSG_ON_PERMISSIONS_CHANGED: {
23894                    final int uid = msg.arg1;
23895                    handleOnPermissionsChanged(uid);
23896                } break;
23897            }
23898        }
23899
23900        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23901            mPermissionListeners.register(listener);
23902
23903        }
23904
23905        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23906            mPermissionListeners.unregister(listener);
23907        }
23908
23909        public void onPermissionsChanged(int uid) {
23910            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23911                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23912            }
23913        }
23914
23915        private void handleOnPermissionsChanged(int uid) {
23916            final int count = mPermissionListeners.beginBroadcast();
23917            try {
23918                for (int i = 0; i < count; i++) {
23919                    IOnPermissionsChangeListener callback = mPermissionListeners
23920                            .getBroadcastItem(i);
23921                    try {
23922                        callback.onPermissionsChanged(uid);
23923                    } catch (RemoteException e) {
23924                        Log.e(TAG, "Permission listener is dead", e);
23925                    }
23926                }
23927            } finally {
23928                mPermissionListeners.finishBroadcast();
23929            }
23930        }
23931    }
23932
23933    private class PackageManagerInternalImpl extends PackageManagerInternal {
23934        @Override
23935        public void setLocationPackagesProvider(PackagesProvider provider) {
23936            synchronized (mPackages) {
23937                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
23938            }
23939        }
23940
23941        @Override
23942        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23943            synchronized (mPackages) {
23944                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
23945            }
23946        }
23947
23948        @Override
23949        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23950            synchronized (mPackages) {
23951                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
23952            }
23953        }
23954
23955        @Override
23956        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23957            synchronized (mPackages) {
23958                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
23959            }
23960        }
23961
23962        @Override
23963        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23964            synchronized (mPackages) {
23965                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
23966            }
23967        }
23968
23969        @Override
23970        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23971            synchronized (mPackages) {
23972                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
23973            }
23974        }
23975
23976        @Override
23977        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23978            synchronized (mPackages) {
23979                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
23980                        packageName, userId);
23981            }
23982        }
23983
23984        @Override
23985        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23986            synchronized (mPackages) {
23987                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23988                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
23989                        packageName, userId);
23990            }
23991        }
23992
23993        @Override
23994        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23995            synchronized (mPackages) {
23996                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
23997                        packageName, userId);
23998            }
23999        }
24000
24001        @Override
24002        public void setKeepUninstalledPackages(final List<String> packageList) {
24003            Preconditions.checkNotNull(packageList);
24004            List<String> removedFromList = null;
24005            synchronized (mPackages) {
24006                if (mKeepUninstalledPackages != null) {
24007                    final int packagesCount = mKeepUninstalledPackages.size();
24008                    for (int i = 0; i < packagesCount; i++) {
24009                        String oldPackage = mKeepUninstalledPackages.get(i);
24010                        if (packageList != null && packageList.contains(oldPackage)) {
24011                            continue;
24012                        }
24013                        if (removedFromList == null) {
24014                            removedFromList = new ArrayList<>();
24015                        }
24016                        removedFromList.add(oldPackage);
24017                    }
24018                }
24019                mKeepUninstalledPackages = new ArrayList<>(packageList);
24020                if (removedFromList != null) {
24021                    final int removedCount = removedFromList.size();
24022                    for (int i = 0; i < removedCount; i++) {
24023                        deletePackageIfUnusedLPr(removedFromList.get(i));
24024                    }
24025                }
24026            }
24027        }
24028
24029        @Override
24030        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24031            synchronized (mPackages) {
24032                // If we do not support permission review, done.
24033                if (!mPermissionReviewRequired) {
24034                    return false;
24035                }
24036
24037                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24038                if (packageSetting == null) {
24039                    return false;
24040                }
24041
24042                // Permission review applies only to apps not supporting the new permission model.
24043                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24044                    return false;
24045                }
24046
24047                // Legacy apps have the permission and get user consent on launch.
24048                PermissionsState permissionsState = packageSetting.getPermissionsState();
24049                return permissionsState.isPermissionReviewRequired(userId);
24050            }
24051        }
24052
24053        @Override
24054        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
24055            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
24056        }
24057
24058        @Override
24059        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24060                int userId) {
24061            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24062        }
24063
24064        @Override
24065        public void setDeviceAndProfileOwnerPackages(
24066                int deviceOwnerUserId, String deviceOwnerPackage,
24067                SparseArray<String> profileOwnerPackages) {
24068            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24069                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24070        }
24071
24072        @Override
24073        public boolean isPackageDataProtected(int userId, String packageName) {
24074            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24075        }
24076
24077        @Override
24078        public boolean isPackageEphemeral(int userId, String packageName) {
24079            synchronized (mPackages) {
24080                final PackageSetting ps = mSettings.mPackages.get(packageName);
24081                return ps != null ? ps.getInstantApp(userId) : false;
24082            }
24083        }
24084
24085        @Override
24086        public boolean wasPackageEverLaunched(String packageName, int userId) {
24087            synchronized (mPackages) {
24088                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24089            }
24090        }
24091
24092        @Override
24093        public void grantRuntimePermission(String packageName, String name, int userId,
24094                boolean overridePolicy) {
24095            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24096                    overridePolicy);
24097        }
24098
24099        @Override
24100        public void revokeRuntimePermission(String packageName, String name, int userId,
24101                boolean overridePolicy) {
24102            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24103                    overridePolicy);
24104        }
24105
24106        @Override
24107        public String getNameForUid(int uid) {
24108            return PackageManagerService.this.getNameForUid(uid);
24109        }
24110
24111        @Override
24112        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24113                Intent origIntent, String resolvedType, String callingPackage,
24114                Bundle verificationBundle, int userId) {
24115            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24116                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24117                    userId);
24118        }
24119
24120        @Override
24121        public void grantEphemeralAccess(int userId, Intent intent,
24122                int targetAppId, int ephemeralAppId) {
24123            synchronized (mPackages) {
24124                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24125                        targetAppId, ephemeralAppId);
24126            }
24127        }
24128
24129        @Override
24130        public boolean isInstantAppInstallerComponent(ComponentName component) {
24131            synchronized (mPackages) {
24132                return mInstantAppInstallerActivity != null
24133                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24134            }
24135        }
24136
24137        @Override
24138        public void pruneInstantApps() {
24139            synchronized (mPackages) {
24140                mInstantAppRegistry.pruneInstantAppsLPw();
24141            }
24142        }
24143
24144        @Override
24145        public String getSetupWizardPackageName() {
24146            return mSetupWizardPackage;
24147        }
24148
24149        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24150            if (policy != null) {
24151                mExternalSourcesPolicy = policy;
24152            }
24153        }
24154
24155        @Override
24156        public boolean isPackagePersistent(String packageName) {
24157            synchronized (mPackages) {
24158                PackageParser.Package pkg = mPackages.get(packageName);
24159                return pkg != null
24160                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24161                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24162                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24163                        : false;
24164            }
24165        }
24166
24167        @Override
24168        public List<PackageInfo> getOverlayPackages(int userId) {
24169            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24170            synchronized (mPackages) {
24171                for (PackageParser.Package p : mPackages.values()) {
24172                    if (p.mOverlayTarget != null) {
24173                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24174                        if (pkg != null) {
24175                            overlayPackages.add(pkg);
24176                        }
24177                    }
24178                }
24179            }
24180            return overlayPackages;
24181        }
24182
24183        @Override
24184        public List<String> getTargetPackageNames(int userId) {
24185            List<String> targetPackages = new ArrayList<>();
24186            synchronized (mPackages) {
24187                for (PackageParser.Package p : mPackages.values()) {
24188                    if (p.mOverlayTarget == null) {
24189                        targetPackages.add(p.packageName);
24190                    }
24191                }
24192            }
24193            return targetPackages;
24194        }
24195
24196        @Override
24197        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24198                @Nullable List<String> overlayPackageNames) {
24199            synchronized (mPackages) {
24200                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24201                    Slog.e(TAG, "failed to find package " + targetPackageName);
24202                    return false;
24203                }
24204
24205                ArrayList<String> paths = null;
24206                if (overlayPackageNames != null) {
24207                    final int N = overlayPackageNames.size();
24208                    paths = new ArrayList<>(N);
24209                    for (int i = 0; i < N; i++) {
24210                        final String packageName = overlayPackageNames.get(i);
24211                        final PackageParser.Package pkg = mPackages.get(packageName);
24212                        if (pkg == null) {
24213                            Slog.e(TAG, "failed to find package " + packageName);
24214                            return false;
24215                        }
24216                        paths.add(pkg.baseCodePath);
24217                    }
24218                }
24219
24220                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
24221                    mEnabledOverlayPaths.get(userId);
24222                if (userSpecificOverlays == null) {
24223                    userSpecificOverlays = new ArrayMap<>();
24224                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
24225                }
24226
24227                if (paths != null && paths.size() > 0) {
24228                    userSpecificOverlays.put(targetPackageName, paths);
24229                } else {
24230                    userSpecificOverlays.remove(targetPackageName);
24231                }
24232                return true;
24233            }
24234        }
24235
24236        @Override
24237        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24238                int flags, int userId) {
24239            return resolveIntentInternal(
24240                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24241        }
24242
24243        @Override
24244        public ResolveInfo resolveService(Intent intent, String resolvedType,
24245                int flags, int userId, int callingUid) {
24246            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24247        }
24248
24249        @Override
24250        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24251            synchronized (mPackages) {
24252                mIsolatedOwners.put(isolatedUid, ownerUid);
24253            }
24254        }
24255
24256        @Override
24257        public void removeIsolatedUid(int isolatedUid) {
24258            synchronized (mPackages) {
24259                mIsolatedOwners.delete(isolatedUid);
24260            }
24261        }
24262
24263        @Override
24264        public int getUidTargetSdkVersion(int uid) {
24265            synchronized (mPackages) {
24266                return getUidTargetSdkVersionLockedLPr(uid);
24267            }
24268        }
24269
24270        @Override
24271        public boolean canAccessInstantApps(int callingUid) {
24272            return PackageManagerService.this.canAccessInstantApps(callingUid);
24273        }
24274    }
24275
24276    @Override
24277    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24278        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24279        synchronized (mPackages) {
24280            final long identity = Binder.clearCallingIdentity();
24281            try {
24282                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24283                        packageNames, userId);
24284            } finally {
24285                Binder.restoreCallingIdentity(identity);
24286            }
24287        }
24288    }
24289
24290    @Override
24291    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24292        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24293        synchronized (mPackages) {
24294            final long identity = Binder.clearCallingIdentity();
24295            try {
24296                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24297                        packageNames, userId);
24298            } finally {
24299                Binder.restoreCallingIdentity(identity);
24300            }
24301        }
24302    }
24303
24304    private static void enforceSystemOrPhoneCaller(String tag) {
24305        int callingUid = Binder.getCallingUid();
24306        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24307            throw new SecurityException(
24308                    "Cannot call " + tag + " from UID " + callingUid);
24309        }
24310    }
24311
24312    boolean isHistoricalPackageUsageAvailable() {
24313        return mPackageUsage.isHistoricalPackageUsageAvailable();
24314    }
24315
24316    /**
24317     * Return a <b>copy</b> of the collection of packages known to the package manager.
24318     * @return A copy of the values of mPackages.
24319     */
24320    Collection<PackageParser.Package> getPackages() {
24321        synchronized (mPackages) {
24322            return new ArrayList<>(mPackages.values());
24323        }
24324    }
24325
24326    /**
24327     * Logs process start information (including base APK hash) to the security log.
24328     * @hide
24329     */
24330    @Override
24331    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24332            String apkFile, int pid) {
24333        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24334            return;
24335        }
24336        if (!SecurityLog.isLoggingEnabled()) {
24337            return;
24338        }
24339        Bundle data = new Bundle();
24340        data.putLong("startTimestamp", System.currentTimeMillis());
24341        data.putString("processName", processName);
24342        data.putInt("uid", uid);
24343        data.putString("seinfo", seinfo);
24344        data.putString("apkFile", apkFile);
24345        data.putInt("pid", pid);
24346        Message msg = mProcessLoggingHandler.obtainMessage(
24347                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24348        msg.setData(data);
24349        mProcessLoggingHandler.sendMessage(msg);
24350    }
24351
24352    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24353        return mCompilerStats.getPackageStats(pkgName);
24354    }
24355
24356    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24357        return getOrCreateCompilerPackageStats(pkg.packageName);
24358    }
24359
24360    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24361        return mCompilerStats.getOrCreatePackageStats(pkgName);
24362    }
24363
24364    public void deleteCompilerPackageStats(String pkgName) {
24365        mCompilerStats.deletePackageStats(pkgName);
24366    }
24367
24368    @Override
24369    public int getInstallReason(String packageName, int userId) {
24370        final int callingUid = Binder.getCallingUid();
24371        enforceCrossUserPermission(callingUid, userId,
24372                true /* requireFullPermission */, false /* checkShell */,
24373                "get install reason");
24374        synchronized (mPackages) {
24375            final PackageSetting ps = mSettings.mPackages.get(packageName);
24376            if (filterAppAccessLPr(ps, callingUid, userId)) {
24377                return PackageManager.INSTALL_REASON_UNKNOWN;
24378            }
24379            if (ps != null) {
24380                return ps.getInstallReason(userId);
24381            }
24382        }
24383        return PackageManager.INSTALL_REASON_UNKNOWN;
24384    }
24385
24386    @Override
24387    public boolean canRequestPackageInstalls(String packageName, int userId) {
24388        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24389            return false;
24390        }
24391        return canRequestPackageInstallsInternal(packageName, 0, userId,
24392                true /* throwIfPermNotDeclared*/);
24393    }
24394
24395    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24396            boolean throwIfPermNotDeclared) {
24397        int callingUid = Binder.getCallingUid();
24398        int uid = getPackageUid(packageName, 0, userId);
24399        if (callingUid != uid && callingUid != Process.ROOT_UID
24400                && callingUid != Process.SYSTEM_UID) {
24401            throw new SecurityException(
24402                    "Caller uid " + callingUid + " does not own package " + packageName);
24403        }
24404        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24405        if (info == null) {
24406            return false;
24407        }
24408        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24409            return false;
24410        }
24411        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24412        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24413        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24414            if (throwIfPermNotDeclared) {
24415                throw new SecurityException("Need to declare " + appOpPermission
24416                        + " to call this api");
24417            } else {
24418                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24419                return false;
24420            }
24421        }
24422        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24423            return false;
24424        }
24425        if (mExternalSourcesPolicy != null) {
24426            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24427            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24428                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24429            }
24430        }
24431        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24432    }
24433
24434    @Override
24435    public ComponentName getInstantAppResolverSettingsComponent() {
24436        return mInstantAppResolverSettingsComponent;
24437    }
24438
24439    @Override
24440    public ComponentName getInstantAppInstallerComponent() {
24441        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24442            return null;
24443        }
24444        return mInstantAppInstallerActivity == null
24445                ? null : mInstantAppInstallerActivity.getComponentName();
24446    }
24447
24448    @Override
24449    public String getInstantAppAndroidId(String packageName, int userId) {
24450        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24451                "getInstantAppAndroidId");
24452        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24453                true /* requireFullPermission */, false /* checkShell */,
24454                "getInstantAppAndroidId");
24455        // Make sure the target is an Instant App.
24456        if (!isInstantApp(packageName, userId)) {
24457            return null;
24458        }
24459        synchronized (mPackages) {
24460            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24461        }
24462    }
24463}
24464
24465interface PackageSender {
24466    void sendPackageBroadcast(final String action, final String pkg,
24467        final Bundle extras, final int flags, final String targetPkg,
24468        final IIntentReceiver finishedReceiver, final int[] userIds);
24469    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
24470        int appId, int... userIds);
24471}
24472