PackageManagerService.java revision b0fea8a7d2e5ff7fc61378134d9282777a7aeaa9
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.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
81import static android.content.pm.PackageManager.PERMISSION_DENIED;
82import static android.content.pm.PackageManager.PERMISSION_GRANTED;
83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.system.OsConstants.O_CREAT;
87import static android.system.OsConstants.O_RDWR;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
92import static com.android.internal.util.ArrayUtils.appendInt;
93import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
96import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
97import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
103import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
104
105import android.Manifest;
106import android.annotation.IntDef;
107import android.annotation.NonNull;
108import android.annotation.Nullable;
109import android.app.ActivityManager;
110import android.app.AppOpsManager;
111import android.app.IActivityManager;
112import android.app.ResourcesManager;
113import android.app.admin.IDevicePolicyManager;
114import android.app.admin.SecurityLog;
115import android.app.backup.IBackupManager;
116import android.content.BroadcastReceiver;
117import android.content.ComponentName;
118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.IIntentReceiver;
121import android.content.Intent;
122import android.content.IntentFilter;
123import android.content.IntentSender;
124import android.content.IntentSender.SendIntentException;
125import android.content.ServiceConnection;
126import android.content.pm.ActivityInfo;
127import android.content.pm.ApplicationInfo;
128import android.content.pm.AppsQueryHelper;
129import android.content.pm.AuxiliaryResolveInfo;
130import android.content.pm.ChangedPackages;
131import android.content.pm.FallbackCategoryProvider;
132import android.content.pm.FeatureInfo;
133import android.content.pm.IDexModuleRegisterCallback;
134import android.content.pm.IOnPermissionsChangeListener;
135import android.content.pm.IPackageDataObserver;
136import android.content.pm.IPackageDeleteObserver;
137import android.content.pm.IPackageDeleteObserver2;
138import android.content.pm.IPackageInstallObserver2;
139import android.content.pm.IPackageInstaller;
140import android.content.pm.IPackageManager;
141import android.content.pm.IPackageMoveObserver;
142import android.content.pm.IPackageStatsObserver;
143import android.content.pm.InstantAppInfo;
144import android.content.pm.InstantAppRequest;
145import android.content.pm.InstantAppResolveInfo;
146import android.content.pm.InstrumentationInfo;
147import android.content.pm.IntentFilterVerificationInfo;
148import android.content.pm.KeySet;
149import android.content.pm.PackageCleanItem;
150import android.content.pm.PackageInfo;
151import android.content.pm.PackageInfoLite;
152import android.content.pm.PackageInstaller;
153import android.content.pm.PackageManager;
154import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155import android.content.pm.PackageManagerInternal;
156import android.content.pm.PackageParser;
157import android.content.pm.PackageParser.ActivityIntentInfo;
158import android.content.pm.PackageParser.PackageLite;
159import android.content.pm.PackageParser.PackageParserException;
160import android.content.pm.PackageStats;
161import android.content.pm.PackageUserState;
162import android.content.pm.ParceledListSlice;
163import android.content.pm.PermissionGroupInfo;
164import android.content.pm.PermissionInfo;
165import android.content.pm.ProviderInfo;
166import android.content.pm.ResolveInfo;
167import android.content.pm.ServiceInfo;
168import android.content.pm.SharedLibraryInfo;
169import android.content.pm.Signature;
170import android.content.pm.UserInfo;
171import android.content.pm.VerifierDeviceIdentity;
172import android.content.pm.VerifierInfo;
173import android.content.pm.VersionedPackage;
174import android.content.res.Resources;
175import android.database.ContentObserver;
176import android.graphics.Bitmap;
177import android.hardware.display.DisplayManager;
178import android.net.Uri;
179import android.os.Binder;
180import android.os.Build;
181import android.os.Bundle;
182import android.os.Debug;
183import android.os.Environment;
184import android.os.Environment.UserEnvironment;
185import android.os.FileUtils;
186import android.os.Handler;
187import android.os.IBinder;
188import android.os.Looper;
189import android.os.Message;
190import android.os.Parcel;
191import android.os.ParcelFileDescriptor;
192import android.os.PatternMatcher;
193import android.os.Process;
194import android.os.RemoteCallbackList;
195import android.os.RemoteException;
196import android.os.ResultReceiver;
197import android.os.SELinux;
198import android.os.ServiceManager;
199import android.os.ShellCallback;
200import android.os.SystemClock;
201import android.os.SystemProperties;
202import android.os.Trace;
203import android.os.UserHandle;
204import android.os.UserManager;
205import android.os.UserManagerInternal;
206import android.os.storage.IStorageManager;
207import android.os.storage.StorageEventListener;
208import android.os.storage.StorageManager;
209import android.os.storage.StorageManagerInternal;
210import android.os.storage.VolumeInfo;
211import android.os.storage.VolumeRecord;
212import android.provider.Settings.Global;
213import android.provider.Settings.Secure;
214import android.security.KeyStore;
215import android.security.SystemKeyStore;
216import android.service.pm.PackageServiceDumpProto;
217import android.system.ErrnoException;
218import android.system.Os;
219import android.text.TextUtils;
220import android.text.format.DateUtils;
221import android.util.ArrayMap;
222import android.util.ArraySet;
223import android.util.Base64;
224import android.util.BootTimingsTraceLog;
225import android.util.DisplayMetrics;
226import android.util.EventLog;
227import android.util.ExceptionUtils;
228import android.util.Log;
229import android.util.LogPrinter;
230import android.util.MathUtils;
231import android.util.PackageUtils;
232import android.util.Pair;
233import android.util.PrintStreamPrinter;
234import android.util.Slog;
235import android.util.SparseArray;
236import android.util.SparseBooleanArray;
237import android.util.SparseIntArray;
238import android.util.Xml;
239import android.util.jar.StrictJarFile;
240import android.util.proto.ProtoOutputStream;
241import android.view.Display;
242
243import com.android.internal.R;
244import com.android.internal.annotations.GuardedBy;
245import com.android.internal.app.IMediaContainerService;
246import com.android.internal.app.ResolverActivity;
247import com.android.internal.content.NativeLibraryHelper;
248import com.android.internal.content.PackageHelper;
249import com.android.internal.logging.MetricsLogger;
250import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
251import com.android.internal.os.IParcelFileDescriptorFactory;
252import com.android.internal.os.RoSystemProperties;
253import com.android.internal.os.SomeArgs;
254import com.android.internal.os.Zygote;
255import com.android.internal.telephony.CarrierAppUtils;
256import com.android.internal.util.ArrayUtils;
257import com.android.internal.util.ConcurrentUtils;
258import com.android.internal.util.DumpUtils;
259import com.android.internal.util.FastPrintWriter;
260import com.android.internal.util.FastXmlSerializer;
261import com.android.internal.util.IndentingPrintWriter;
262import com.android.internal.util.Preconditions;
263import com.android.internal.util.XmlUtils;
264import com.android.server.AttributeCache;
265import com.android.server.DeviceIdleController;
266import com.android.server.EventLogTags;
267import com.android.server.FgThread;
268import com.android.server.IntentResolver;
269import com.android.server.LocalServices;
270import com.android.server.LockGuard;
271import com.android.server.ServiceThread;
272import com.android.server.SystemConfig;
273import com.android.server.SystemServerInitThreadPool;
274import com.android.server.Watchdog;
275import com.android.server.net.NetworkPolicyManagerInternal;
276import com.android.server.pm.Installer.InstallerException;
277import com.android.server.pm.PermissionsState.PermissionState;
278import com.android.server.pm.Settings.DatabaseVersion;
279import com.android.server.pm.Settings.VersionInfo;
280import com.android.server.pm.dex.DexManager;
281import com.android.server.storage.DeviceStorageMonitorInternal;
282
283import dalvik.system.CloseGuard;
284import dalvik.system.DexFile;
285import dalvik.system.VMRuntime;
286
287import libcore.io.IoUtils;
288import libcore.util.EmptyArray;
289
290import org.xmlpull.v1.XmlPullParser;
291import org.xmlpull.v1.XmlPullParserException;
292import org.xmlpull.v1.XmlSerializer;
293
294import java.io.BufferedOutputStream;
295import java.io.BufferedReader;
296import java.io.ByteArrayInputStream;
297import java.io.ByteArrayOutputStream;
298import java.io.File;
299import java.io.FileDescriptor;
300import java.io.FileInputStream;
301import java.io.FileOutputStream;
302import java.io.FileReader;
303import java.io.FilenameFilter;
304import java.io.IOException;
305import java.io.PrintWriter;
306import java.lang.annotation.Retention;
307import java.lang.annotation.RetentionPolicy;
308import java.nio.charset.StandardCharsets;
309import java.security.DigestInputStream;
310import java.security.MessageDigest;
311import java.security.NoSuchAlgorithmException;
312import java.security.PublicKey;
313import java.security.SecureRandom;
314import java.security.cert.Certificate;
315import java.security.cert.CertificateEncodingException;
316import java.security.cert.CertificateException;
317import java.text.SimpleDateFormat;
318import java.util.ArrayList;
319import java.util.Arrays;
320import java.util.Collection;
321import java.util.Collections;
322import java.util.Comparator;
323import java.util.Date;
324import java.util.HashMap;
325import java.util.HashSet;
326import java.util.Iterator;
327import java.util.List;
328import java.util.Map;
329import java.util.Objects;
330import java.util.Set;
331import java.util.concurrent.CountDownLatch;
332import java.util.concurrent.Future;
333import java.util.concurrent.TimeUnit;
334import java.util.concurrent.atomic.AtomicBoolean;
335import java.util.concurrent.atomic.AtomicInteger;
336
337/**
338 * Keep track of all those APKs everywhere.
339 * <p>
340 * Internally there are two important locks:
341 * <ul>
342 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
343 * and other related state. It is a fine-grained lock that should only be held
344 * momentarily, as it's one of the most contended locks in the system.
345 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
346 * operations typically involve heavy lifting of application data on disk. Since
347 * {@code installd} is single-threaded, and it's operations can often be slow,
348 * this lock should never be acquired while already holding {@link #mPackages}.
349 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
350 * holding {@link #mInstallLock}.
351 * </ul>
352 * Many internal methods rely on the caller to hold the appropriate locks, and
353 * this contract is expressed through method name suffixes:
354 * <ul>
355 * <li>fooLI(): the caller must hold {@link #mInstallLock}
356 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
357 * being modified must be frozen
358 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
359 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
360 * </ul>
361 * <p>
362 * Because this class is very central to the platform's security; please run all
363 * CTS and unit tests whenever making modifications:
364 *
365 * <pre>
366 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
367 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
368 * </pre>
369 */
370public class PackageManagerService extends IPackageManager.Stub
371        implements PackageSender {
372    static final String TAG = "PackageManager";
373    static final boolean DEBUG_SETTINGS = false;
374    static final boolean DEBUG_PREFERRED = false;
375    static final boolean DEBUG_UPGRADE = false;
376    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
377    private static final boolean DEBUG_BACKUP = false;
378    private static final boolean DEBUG_INSTALL = false;
379    private static final boolean DEBUG_REMOVE = false;
380    private static final boolean DEBUG_BROADCASTS = false;
381    private static final boolean DEBUG_SHOW_INFO = false;
382    private static final boolean DEBUG_PACKAGE_INFO = false;
383    private static final boolean DEBUG_INTENT_MATCHING = false;
384    private static final boolean DEBUG_PACKAGE_SCANNING = false;
385    private static final boolean DEBUG_VERIFY = false;
386    private static final boolean DEBUG_FILTERS = false;
387    private static final boolean DEBUG_PERMISSIONS = false;
388    private static final boolean DEBUG_SHARED_LIBRARIES = false;
389
390    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
391    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
392    // user, but by default initialize to this.
393    public static final boolean DEBUG_DEXOPT = false;
394
395    private static final boolean DEBUG_ABI_SELECTION = false;
396    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
397    private static final boolean DEBUG_TRIAGED_MISSING = false;
398    private static final boolean DEBUG_APP_DATA = false;
399
400    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
401    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
402
403    private static final boolean HIDE_EPHEMERAL_APIS = false;
404
405    private static final boolean ENABLE_FREE_CACHE_V2 =
406            SystemProperties.getBoolean("fw.free_cache_v2", true);
407
408    private static final int RADIO_UID = Process.PHONE_UID;
409    private static final int LOG_UID = Process.LOG_UID;
410    private static final int NFC_UID = Process.NFC_UID;
411    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
412    private static final int SHELL_UID = Process.SHELL_UID;
413
414    // Cap the size of permission trees that 3rd party apps can define
415    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
416
417    // Suffix used during package installation when copying/moving
418    // package apks to install directory.
419    private static final String INSTALL_PACKAGE_SUFFIX = "-";
420
421    static final int SCAN_NO_DEX = 1<<1;
422    static final int SCAN_FORCE_DEX = 1<<2;
423    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
424    static final int SCAN_NEW_INSTALL = 1<<4;
425    static final int SCAN_UPDATE_TIME = 1<<5;
426    static final int SCAN_BOOTING = 1<<6;
427    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
428    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
429    static final int SCAN_REPLACING = 1<<9;
430    static final int SCAN_REQUIRE_KNOWN = 1<<10;
431    static final int SCAN_MOVE = 1<<11;
432    static final int SCAN_INITIAL = 1<<12;
433    static final int SCAN_CHECK_ONLY = 1<<13;
434    static final int SCAN_DONT_KILL_APP = 1<<14;
435    static final int SCAN_IGNORE_FROZEN = 1<<15;
436    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
437    static final int SCAN_AS_INSTANT_APP = 1<<17;
438    static final int SCAN_AS_FULL_APP = 1<<18;
439    /** Should not be with the scan flags */
440    static final int FLAGS_REMOVE_CHATTY = 1<<31;
441
442    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
443
444    private static final int[] EMPTY_INT_ARRAY = new int[0];
445
446    private static final int TYPE_UNKNOWN = 0;
447    private static final int TYPE_ACTIVITY = 1;
448    private static final int TYPE_RECEIVER = 2;
449    private static final int TYPE_SERVICE = 3;
450    private static final int TYPE_PROVIDER = 4;
451    @IntDef(prefix = { "TYPE_" }, value = {
452            TYPE_UNKNOWN,
453            TYPE_ACTIVITY,
454            TYPE_RECEIVER,
455            TYPE_SERVICE,
456            TYPE_PROVIDER,
457    })
458    @Retention(RetentionPolicy.SOURCE)
459    public @interface ComponentType {}
460
461    /**
462     * Timeout (in milliseconds) after which the watchdog should declare that
463     * our handler thread is wedged.  The usual default for such things is one
464     * minute but we sometimes do very lengthy I/O operations on this thread,
465     * such as installing multi-gigabyte applications, so ours needs to be longer.
466     */
467    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
468
469    /**
470     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
471     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
472     * settings entry if available, otherwise we use the hardcoded default.  If it's been
473     * more than this long since the last fstrim, we force one during the boot sequence.
474     *
475     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
476     * one gets run at the next available charging+idle time.  This final mandatory
477     * no-fstrim check kicks in only of the other scheduling criteria is never met.
478     */
479    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
480
481    /**
482     * Whether verification is enabled by default.
483     */
484    private static final boolean DEFAULT_VERIFY_ENABLE = true;
485
486    /**
487     * The default maximum time to wait for the verification agent to return in
488     * milliseconds.
489     */
490    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
491
492    /**
493     * The default response for package verification timeout.
494     *
495     * This can be either PackageManager.VERIFICATION_ALLOW or
496     * PackageManager.VERIFICATION_REJECT.
497     */
498    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
499
500    static final String PLATFORM_PACKAGE_NAME = "android";
501
502    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
503
504    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
505            DEFAULT_CONTAINER_PACKAGE,
506            "com.android.defcontainer.DefaultContainerService");
507
508    private static final String KILL_APP_REASON_GIDS_CHANGED =
509            "permission grant or revoke changed gids";
510
511    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
512            "permissions revoked";
513
514    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
515
516    private static final String PACKAGE_SCHEME = "package";
517
518    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
519
520    /** Permission grant: not grant the permission. */
521    private static final int GRANT_DENIED = 1;
522
523    /** Permission grant: grant the permission as an install permission. */
524    private static final int GRANT_INSTALL = 2;
525
526    /** Permission grant: grant the permission as a runtime one. */
527    private static final int GRANT_RUNTIME = 3;
528
529    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
530    private static final int GRANT_UPGRADE = 4;
531
532    /** Canonical intent used to identify what counts as a "web browser" app */
533    private static final Intent sBrowserIntent;
534    static {
535        sBrowserIntent = new Intent();
536        sBrowserIntent.setAction(Intent.ACTION_VIEW);
537        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
538        sBrowserIntent.setData(Uri.parse("http:"));
539    }
540
541    /**
542     * The set of all protected actions [i.e. those actions for which a high priority
543     * intent filter is disallowed].
544     */
545    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
546    static {
547        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
548        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
549        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
550        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
551    }
552
553    // Compilation reasons.
554    public static final int REASON_FIRST_BOOT = 0;
555    public static final int REASON_BOOT = 1;
556    public static final int REASON_INSTALL = 2;
557    public static final int REASON_BACKGROUND_DEXOPT = 3;
558    public static final int REASON_AB_OTA = 4;
559
560    public static final int REASON_LAST = REASON_AB_OTA;
561
562    /** All dangerous permission names in the same order as the events in MetricsEvent */
563    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
564            Manifest.permission.READ_CALENDAR,
565            Manifest.permission.WRITE_CALENDAR,
566            Manifest.permission.CAMERA,
567            Manifest.permission.READ_CONTACTS,
568            Manifest.permission.WRITE_CONTACTS,
569            Manifest.permission.GET_ACCOUNTS,
570            Manifest.permission.ACCESS_FINE_LOCATION,
571            Manifest.permission.ACCESS_COARSE_LOCATION,
572            Manifest.permission.RECORD_AUDIO,
573            Manifest.permission.READ_PHONE_STATE,
574            Manifest.permission.CALL_PHONE,
575            Manifest.permission.READ_CALL_LOG,
576            Manifest.permission.WRITE_CALL_LOG,
577            Manifest.permission.ADD_VOICEMAIL,
578            Manifest.permission.USE_SIP,
579            Manifest.permission.PROCESS_OUTGOING_CALLS,
580            Manifest.permission.READ_CELL_BROADCASTS,
581            Manifest.permission.BODY_SENSORS,
582            Manifest.permission.SEND_SMS,
583            Manifest.permission.RECEIVE_SMS,
584            Manifest.permission.READ_SMS,
585            Manifest.permission.RECEIVE_WAP_PUSH,
586            Manifest.permission.RECEIVE_MMS,
587            Manifest.permission.READ_EXTERNAL_STORAGE,
588            Manifest.permission.WRITE_EXTERNAL_STORAGE,
589            Manifest.permission.READ_PHONE_NUMBERS,
590            Manifest.permission.ANSWER_PHONE_CALLS);
591
592
593    /**
594     * Version number for the package parser cache. Increment this whenever the format or
595     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
596     */
597    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
598
599    /**
600     * Whether the package parser cache is enabled.
601     */
602    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
603
604    final ServiceThread mHandlerThread;
605
606    final PackageHandler mHandler;
607
608    private final ProcessLoggingHandler mProcessLoggingHandler;
609
610    /**
611     * Messages for {@link #mHandler} that need to wait for system ready before
612     * being dispatched.
613     */
614    private ArrayList<Message> mPostSystemReadyMessages;
615
616    final int mSdkVersion = Build.VERSION.SDK_INT;
617
618    final Context mContext;
619    final boolean mFactoryTest;
620    final boolean mOnlyCore;
621    final DisplayMetrics mMetrics;
622    final int mDefParseFlags;
623    final String[] mSeparateProcesses;
624    final boolean mIsUpgrade;
625    final boolean mIsPreNUpgrade;
626    final boolean mIsPreNMR1Upgrade;
627
628    // Have we told the Activity Manager to whitelist the default container service by uid yet?
629    @GuardedBy("mPackages")
630    boolean mDefaultContainerWhitelisted = false;
631
632    @GuardedBy("mPackages")
633    private boolean mDexOptDialogShown;
634
635    /** The location for ASEC container files on internal storage. */
636    final String mAsecInternalPath;
637
638    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
639    // LOCK HELD.  Can be called with mInstallLock held.
640    @GuardedBy("mInstallLock")
641    final Installer mInstaller;
642
643    /** Directory where installed third-party apps stored */
644    final File mAppInstallDir;
645
646    /**
647     * Directory to which applications installed internally have their
648     * 32 bit native libraries copied.
649     */
650    private File mAppLib32InstallDir;
651
652    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
653    // apps.
654    final File mDrmAppPrivateInstallDir;
655
656    // ----------------------------------------------------------------
657
658    // Lock for state used when installing and doing other long running
659    // operations.  Methods that must be called with this lock held have
660    // the suffix "LI".
661    final Object mInstallLock = new Object();
662
663    // ----------------------------------------------------------------
664
665    // Keys are String (package name), values are Package.  This also serves
666    // as the lock for the global state.  Methods that must be called with
667    // this lock held have the prefix "LP".
668    @GuardedBy("mPackages")
669    final ArrayMap<String, PackageParser.Package> mPackages =
670            new ArrayMap<String, PackageParser.Package>();
671
672    final ArrayMap<String, Set<String>> mKnownCodebase =
673            new ArrayMap<String, Set<String>>();
674
675    // Keys are isolated uids and values are the uid of the application
676    // that created the isolated proccess.
677    @GuardedBy("mPackages")
678    final SparseIntArray mIsolatedOwners = new SparseIntArray();
679
680    // List of APK paths to load for each user and package. This data is never
681    // persisted by the package manager. Instead, the overlay manager will
682    // ensure the data is up-to-date in runtime.
683    @GuardedBy("mPackages")
684    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
685        new SparseArray<ArrayMap<String, ArrayList<String>>>();
686
687    /**
688     * Tracks new system packages [received in an OTA] that we expect to
689     * find updated user-installed versions. Keys are package name, values
690     * are package location.
691     */
692    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
693    /**
694     * Tracks high priority intent filters for protected actions. During boot, certain
695     * filter actions are protected and should never be allowed to have a high priority
696     * intent filter for them. However, there is one, and only one exception -- the
697     * setup wizard. It must be able to define a high priority intent filter for these
698     * actions to ensure there are no escapes from the wizard. We need to delay processing
699     * of these during boot as we need to look at all of the system packages in order
700     * to know which component is the setup wizard.
701     */
702    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
703    /**
704     * Whether or not processing protected filters should be deferred.
705     */
706    private boolean mDeferProtectedFilters = true;
707
708    /**
709     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
710     */
711    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
712    /**
713     * Whether or not system app permissions should be promoted from install to runtime.
714     */
715    boolean mPromoteSystemApps;
716
717    @GuardedBy("mPackages")
718    final Settings mSettings;
719
720    /**
721     * Set of package names that are currently "frozen", which means active
722     * surgery is being done on the code/data for that package. The platform
723     * will refuse to launch frozen packages to avoid race conditions.
724     *
725     * @see PackageFreezer
726     */
727    @GuardedBy("mPackages")
728    final ArraySet<String> mFrozenPackages = new ArraySet<>();
729
730    final ProtectedPackages mProtectedPackages;
731
732    boolean mFirstBoot;
733
734    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
735
736    // System configuration read by SystemConfig.
737    final int[] mGlobalGids;
738    final SparseArray<ArraySet<String>> mSystemPermissions;
739    @GuardedBy("mAvailableFeatures")
740    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
741
742    // If mac_permissions.xml was found for seinfo labeling.
743    boolean mFoundPolicyFile;
744
745    private final InstantAppRegistry mInstantAppRegistry;
746
747    @GuardedBy("mPackages")
748    int mChangedPackagesSequenceNumber;
749    /**
750     * List of changed [installed, removed or updated] packages.
751     * mapping from user id -> sequence number -> package name
752     */
753    @GuardedBy("mPackages")
754    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
755    /**
756     * The sequence number of the last change to a package.
757     * mapping from user id -> package name -> sequence number
758     */
759    @GuardedBy("mPackages")
760    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
761
762    class PackageParserCallback implements PackageParser.Callback {
763        @Override public final boolean hasFeature(String feature) {
764            return PackageManagerService.this.hasSystemFeature(feature, 0);
765        }
766
767        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
768                Collection<PackageParser.Package> allPackages, String targetPackageName) {
769            List<PackageParser.Package> overlayPackages = null;
770            for (PackageParser.Package p : allPackages) {
771                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
772                    if (overlayPackages == null) {
773                        overlayPackages = new ArrayList<PackageParser.Package>();
774                    }
775                    overlayPackages.add(p);
776                }
777            }
778            if (overlayPackages != null) {
779                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
780                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
781                        return p1.mOverlayPriority - p2.mOverlayPriority;
782                    }
783                };
784                Collections.sort(overlayPackages, cmp);
785            }
786            return overlayPackages;
787        }
788
789        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
790                String targetPackageName, String targetPath) {
791            if ("android".equals(targetPackageName)) {
792                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
793                // native AssetManager.
794                return null;
795            }
796            List<PackageParser.Package> overlayPackages =
797                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
798            if (overlayPackages == null || overlayPackages.isEmpty()) {
799                return null;
800            }
801            List<String> overlayPathList = null;
802            for (PackageParser.Package overlayPackage : overlayPackages) {
803                if (targetPath == null) {
804                    if (overlayPathList == null) {
805                        overlayPathList = new ArrayList<String>();
806                    }
807                    overlayPathList.add(overlayPackage.baseCodePath);
808                    continue;
809                }
810
811                try {
812                    // Creates idmaps for system to parse correctly the Android manifest of the
813                    // target package.
814                    //
815                    // OverlayManagerService will update each of them with a correct gid from its
816                    // target package app id.
817                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
818                            UserHandle.getSharedAppGid(
819                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
820                    if (overlayPathList == null) {
821                        overlayPathList = new ArrayList<String>();
822                    }
823                    overlayPathList.add(overlayPackage.baseCodePath);
824                } catch (InstallerException e) {
825                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
826                            overlayPackage.baseCodePath);
827                }
828            }
829            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
830        }
831
832        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
833            synchronized (mPackages) {
834                return getStaticOverlayPathsLocked(
835                        mPackages.values(), targetPackageName, targetPath);
836            }
837        }
838
839        @Override public final String[] getOverlayApks(String targetPackageName) {
840            return getStaticOverlayPaths(targetPackageName, null);
841        }
842
843        @Override public final String[] getOverlayPaths(String targetPackageName,
844                String targetPath) {
845            return getStaticOverlayPaths(targetPackageName, targetPath);
846        }
847    };
848
849    class ParallelPackageParserCallback extends PackageParserCallback {
850        List<PackageParser.Package> mOverlayPackages = null;
851
852        void findStaticOverlayPackages() {
853            synchronized (mPackages) {
854                for (PackageParser.Package p : mPackages.values()) {
855                    if (p.mIsStaticOverlay) {
856                        if (mOverlayPackages == null) {
857                            mOverlayPackages = new ArrayList<PackageParser.Package>();
858                        }
859                        mOverlayPackages.add(p);
860                    }
861                }
862            }
863        }
864
865        @Override
866        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
867            // We can trust mOverlayPackages without holding mPackages because package uninstall
868            // can't happen while running parallel parsing.
869            // Moreover holding mPackages on each parsing thread causes dead-lock.
870            return mOverlayPackages == null ? null :
871                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
872        }
873    }
874
875    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
876    final ParallelPackageParserCallback mParallelPackageParserCallback =
877            new ParallelPackageParserCallback();
878
879    public static final class SharedLibraryEntry {
880        public final @Nullable String path;
881        public final @Nullable String apk;
882        public final @NonNull SharedLibraryInfo info;
883
884        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
885                String declaringPackageName, int declaringPackageVersionCode) {
886            path = _path;
887            apk = _apk;
888            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
889                    declaringPackageName, declaringPackageVersionCode), null);
890        }
891    }
892
893    // Currently known shared libraries.
894    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
895    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
896            new ArrayMap<>();
897
898    // All available activities, for your resolving pleasure.
899    final ActivityIntentResolver mActivities =
900            new ActivityIntentResolver();
901
902    // All available receivers, for your resolving pleasure.
903    final ActivityIntentResolver mReceivers =
904            new ActivityIntentResolver();
905
906    // All available services, for your resolving pleasure.
907    final ServiceIntentResolver mServices = new ServiceIntentResolver();
908
909    // All available providers, for your resolving pleasure.
910    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
911
912    // Mapping from provider base names (first directory in content URI codePath)
913    // to the provider information.
914    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
915            new ArrayMap<String, PackageParser.Provider>();
916
917    // Mapping from instrumentation class names to info about them.
918    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
919            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
920
921    // Mapping from permission names to info about them.
922    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
923            new ArrayMap<String, PackageParser.PermissionGroup>();
924
925    // Packages whose data we have transfered into another package, thus
926    // should no longer exist.
927    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
928
929    // Broadcast actions that are only available to the system.
930    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
931
932    /** List of packages waiting for verification. */
933    final SparseArray<PackageVerificationState> mPendingVerification
934            = new SparseArray<PackageVerificationState>();
935
936    /** Set of packages associated with each app op permission. */
937    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
938
939    final PackageInstallerService mInstallerService;
940
941    private final PackageDexOptimizer mPackageDexOptimizer;
942    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
943    // is used by other apps).
944    private final DexManager mDexManager;
945
946    private AtomicInteger mNextMoveId = new AtomicInteger();
947    private final MoveCallbacks mMoveCallbacks;
948
949    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
950
951    // Cache of users who need badging.
952    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
953
954    /** Token for keys in mPendingVerification. */
955    private int mPendingVerificationToken = 0;
956
957    volatile boolean mSystemReady;
958    volatile boolean mSafeMode;
959    volatile boolean mHasSystemUidErrors;
960    private volatile boolean mEphemeralAppsDisabled;
961
962    ApplicationInfo mAndroidApplication;
963    final ActivityInfo mResolveActivity = new ActivityInfo();
964    final ResolveInfo mResolveInfo = new ResolveInfo();
965    ComponentName mResolveComponentName;
966    PackageParser.Package mPlatformPackage;
967    ComponentName mCustomResolverComponentName;
968
969    boolean mResolverReplaced = false;
970
971    private final @Nullable ComponentName mIntentFilterVerifierComponent;
972    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
973
974    private int mIntentFilterVerificationToken = 0;
975
976    /** The service connection to the ephemeral resolver */
977    final EphemeralResolverConnection mInstantAppResolverConnection;
978    /** Component used to show resolver settings for Instant Apps */
979    final ComponentName mInstantAppResolverSettingsComponent;
980
981    /** Activity used to install instant applications */
982    ActivityInfo mInstantAppInstallerActivity;
983    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
984
985    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
986            = new SparseArray<IntentFilterVerificationState>();
987
988    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
989
990    // List of packages names to keep cached, even if they are uninstalled for all users
991    private List<String> mKeepUninstalledPackages;
992
993    private UserManagerInternal mUserManagerInternal;
994
995    private DeviceIdleController.LocalService mDeviceIdleController;
996
997    private File mCacheDir;
998
999    private ArraySet<String> mPrivappPermissionsViolations;
1000
1001    private Future<?> mPrepareAppDataFuture;
1002
1003    private static class IFVerificationParams {
1004        PackageParser.Package pkg;
1005        boolean replacing;
1006        int userId;
1007        int verifierUid;
1008
1009        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1010                int _userId, int _verifierUid) {
1011            pkg = _pkg;
1012            replacing = _replacing;
1013            userId = _userId;
1014            replacing = _replacing;
1015            verifierUid = _verifierUid;
1016        }
1017    }
1018
1019    private interface IntentFilterVerifier<T extends IntentFilter> {
1020        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1021                                               T filter, String packageName);
1022        void startVerifications(int userId);
1023        void receiveVerificationResponse(int verificationId);
1024    }
1025
1026    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1027        private Context mContext;
1028        private ComponentName mIntentFilterVerifierComponent;
1029        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1030
1031        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1032            mContext = context;
1033            mIntentFilterVerifierComponent = verifierComponent;
1034        }
1035
1036        private String getDefaultScheme() {
1037            return IntentFilter.SCHEME_HTTPS;
1038        }
1039
1040        @Override
1041        public void startVerifications(int userId) {
1042            // Launch verifications requests
1043            int count = mCurrentIntentFilterVerifications.size();
1044            for (int n=0; n<count; n++) {
1045                int verificationId = mCurrentIntentFilterVerifications.get(n);
1046                final IntentFilterVerificationState ivs =
1047                        mIntentFilterVerificationStates.get(verificationId);
1048
1049                String packageName = ivs.getPackageName();
1050
1051                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1052                final int filterCount = filters.size();
1053                ArraySet<String> domainsSet = new ArraySet<>();
1054                for (int m=0; m<filterCount; m++) {
1055                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1056                    domainsSet.addAll(filter.getHostsList());
1057                }
1058                synchronized (mPackages) {
1059                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1060                            packageName, domainsSet) != null) {
1061                        scheduleWriteSettingsLocked();
1062                    }
1063                }
1064                sendVerificationRequest(userId, verificationId, ivs);
1065            }
1066            mCurrentIntentFilterVerifications.clear();
1067        }
1068
1069        private void sendVerificationRequest(int userId, int verificationId,
1070                IntentFilterVerificationState ivs) {
1071
1072            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1073            verificationIntent.putExtra(
1074                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1075                    verificationId);
1076            verificationIntent.putExtra(
1077                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1078                    getDefaultScheme());
1079            verificationIntent.putExtra(
1080                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1081                    ivs.getHostsString());
1082            verificationIntent.putExtra(
1083                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1084                    ivs.getPackageName());
1085            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1086            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1087
1088            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1089            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1090                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1091                    userId, false, "intent filter verifier");
1092
1093            UserHandle user = new UserHandle(userId);
1094            mContext.sendBroadcastAsUser(verificationIntent, user);
1095            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1096                    "Sending IntentFilter verification broadcast");
1097        }
1098
1099        public void receiveVerificationResponse(int verificationId) {
1100            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1101
1102            final boolean verified = ivs.isVerified();
1103
1104            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1105            final int count = filters.size();
1106            if (DEBUG_DOMAIN_VERIFICATION) {
1107                Slog.i(TAG, "Received verification response " + verificationId
1108                        + " for " + count + " filters, verified=" + verified);
1109            }
1110            for (int n=0; n<count; n++) {
1111                PackageParser.ActivityIntentInfo filter = filters.get(n);
1112                filter.setVerified(verified);
1113
1114                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1115                        + " verified with result:" + verified + " and hosts:"
1116                        + ivs.getHostsString());
1117            }
1118
1119            mIntentFilterVerificationStates.remove(verificationId);
1120
1121            final String packageName = ivs.getPackageName();
1122            IntentFilterVerificationInfo ivi = null;
1123
1124            synchronized (mPackages) {
1125                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1126            }
1127            if (ivi == null) {
1128                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1129                        + verificationId + " packageName:" + packageName);
1130                return;
1131            }
1132            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1133                    "Updating IntentFilterVerificationInfo for package " + packageName
1134                            +" verificationId:" + verificationId);
1135
1136            synchronized (mPackages) {
1137                if (verified) {
1138                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1139                } else {
1140                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1141                }
1142                scheduleWriteSettingsLocked();
1143
1144                final int userId = ivs.getUserId();
1145                if (userId != UserHandle.USER_ALL) {
1146                    final int userStatus =
1147                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1148
1149                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1150                    boolean needUpdate = false;
1151
1152                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1153                    // already been set by the User thru the Disambiguation dialog
1154                    switch (userStatus) {
1155                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1156                            if (verified) {
1157                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1158                            } else {
1159                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1160                            }
1161                            needUpdate = true;
1162                            break;
1163
1164                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1165                            if (verified) {
1166                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1167                                needUpdate = true;
1168                            }
1169                            break;
1170
1171                        default:
1172                            // Nothing to do
1173                    }
1174
1175                    if (needUpdate) {
1176                        mSettings.updateIntentFilterVerificationStatusLPw(
1177                                packageName, updatedStatus, userId);
1178                        scheduleWritePackageRestrictionsLocked(userId);
1179                    }
1180                }
1181            }
1182        }
1183
1184        @Override
1185        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1186                    ActivityIntentInfo filter, String packageName) {
1187            if (!hasValidDomains(filter)) {
1188                return false;
1189            }
1190            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1191            if (ivs == null) {
1192                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1193                        packageName);
1194            }
1195            if (DEBUG_DOMAIN_VERIFICATION) {
1196                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1197            }
1198            ivs.addFilter(filter);
1199            return true;
1200        }
1201
1202        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1203                int userId, int verificationId, String packageName) {
1204            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1205                    verifierUid, userId, packageName);
1206            ivs.setPendingState();
1207            synchronized (mPackages) {
1208                mIntentFilterVerificationStates.append(verificationId, ivs);
1209                mCurrentIntentFilterVerifications.add(verificationId);
1210            }
1211            return ivs;
1212        }
1213    }
1214
1215    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1216        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1217                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1218                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1219    }
1220
1221    // Set of pending broadcasts for aggregating enable/disable of components.
1222    static class PendingPackageBroadcasts {
1223        // for each user id, a map of <package name -> components within that package>
1224        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1225
1226        public PendingPackageBroadcasts() {
1227            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1228        }
1229
1230        public ArrayList<String> get(int userId, String packageName) {
1231            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1232            return packages.get(packageName);
1233        }
1234
1235        public void put(int userId, String packageName, ArrayList<String> components) {
1236            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1237            packages.put(packageName, components);
1238        }
1239
1240        public void remove(int userId, String packageName) {
1241            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1242            if (packages != null) {
1243                packages.remove(packageName);
1244            }
1245        }
1246
1247        public void remove(int userId) {
1248            mUidMap.remove(userId);
1249        }
1250
1251        public int userIdCount() {
1252            return mUidMap.size();
1253        }
1254
1255        public int userIdAt(int n) {
1256            return mUidMap.keyAt(n);
1257        }
1258
1259        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1260            return mUidMap.get(userId);
1261        }
1262
1263        public int size() {
1264            // total number of pending broadcast entries across all userIds
1265            int num = 0;
1266            for (int i = 0; i< mUidMap.size(); i++) {
1267                num += mUidMap.valueAt(i).size();
1268            }
1269            return num;
1270        }
1271
1272        public void clear() {
1273            mUidMap.clear();
1274        }
1275
1276        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1277            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1278            if (map == null) {
1279                map = new ArrayMap<String, ArrayList<String>>();
1280                mUidMap.put(userId, map);
1281            }
1282            return map;
1283        }
1284    }
1285    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1286
1287    // Service Connection to remote media container service to copy
1288    // package uri's from external media onto secure containers
1289    // or internal storage.
1290    private IMediaContainerService mContainerService = null;
1291
1292    static final int SEND_PENDING_BROADCAST = 1;
1293    static final int MCS_BOUND = 3;
1294    static final int END_COPY = 4;
1295    static final int INIT_COPY = 5;
1296    static final int MCS_UNBIND = 6;
1297    static final int START_CLEANING_PACKAGE = 7;
1298    static final int FIND_INSTALL_LOC = 8;
1299    static final int POST_INSTALL = 9;
1300    static final int MCS_RECONNECT = 10;
1301    static final int MCS_GIVE_UP = 11;
1302    static final int UPDATED_MEDIA_STATUS = 12;
1303    static final int WRITE_SETTINGS = 13;
1304    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1305    static final int PACKAGE_VERIFIED = 15;
1306    static final int CHECK_PENDING_VERIFICATION = 16;
1307    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1308    static final int INTENT_FILTER_VERIFIED = 18;
1309    static final int WRITE_PACKAGE_LIST = 19;
1310    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1311
1312    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1313
1314    // Delay time in millisecs
1315    static final int BROADCAST_DELAY = 10 * 1000;
1316
1317    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1318            2 * 60 * 60 * 1000L; /* two hours */
1319
1320    static UserManagerService sUserManager;
1321
1322    // Stores a list of users whose package restrictions file needs to be updated
1323    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1324
1325    final private DefaultContainerConnection mDefContainerConn =
1326            new DefaultContainerConnection();
1327    class DefaultContainerConnection implements ServiceConnection {
1328        public void onServiceConnected(ComponentName name, IBinder service) {
1329            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1330            final IMediaContainerService imcs = IMediaContainerService.Stub
1331                    .asInterface(Binder.allowBlocking(service));
1332            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1333        }
1334
1335        public void onServiceDisconnected(ComponentName name) {
1336            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1337        }
1338    }
1339
1340    // Recordkeeping of restore-after-install operations that are currently in flight
1341    // between the Package Manager and the Backup Manager
1342    static class PostInstallData {
1343        public InstallArgs args;
1344        public PackageInstalledInfo res;
1345
1346        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1347            args = _a;
1348            res = _r;
1349        }
1350    }
1351
1352    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1353    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1354
1355    // XML tags for backup/restore of various bits of state
1356    private static final String TAG_PREFERRED_BACKUP = "pa";
1357    private static final String TAG_DEFAULT_APPS = "da";
1358    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1359
1360    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1361    private static final String TAG_ALL_GRANTS = "rt-grants";
1362    private static final String TAG_GRANT = "grant";
1363    private static final String ATTR_PACKAGE_NAME = "pkg";
1364
1365    private static final String TAG_PERMISSION = "perm";
1366    private static final String ATTR_PERMISSION_NAME = "name";
1367    private static final String ATTR_IS_GRANTED = "g";
1368    private static final String ATTR_USER_SET = "set";
1369    private static final String ATTR_USER_FIXED = "fixed";
1370    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1371
1372    // System/policy permission grants are not backed up
1373    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1374            FLAG_PERMISSION_POLICY_FIXED
1375            | FLAG_PERMISSION_SYSTEM_FIXED
1376            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1377
1378    // And we back up these user-adjusted states
1379    private static final int USER_RUNTIME_GRANT_MASK =
1380            FLAG_PERMISSION_USER_SET
1381            | FLAG_PERMISSION_USER_FIXED
1382            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1383
1384    final @Nullable String mRequiredVerifierPackage;
1385    final @NonNull String mRequiredInstallerPackage;
1386    final @NonNull String mRequiredUninstallerPackage;
1387    final @Nullable String mSetupWizardPackage;
1388    final @Nullable String mStorageManagerPackage;
1389    final @NonNull String mServicesSystemSharedLibraryPackageName;
1390    final @NonNull String mSharedSystemSharedLibraryPackageName;
1391
1392    final boolean mPermissionReviewRequired;
1393
1394    private final PackageUsage mPackageUsage = new PackageUsage();
1395    private final CompilerStats mCompilerStats = new CompilerStats();
1396
1397    class PackageHandler extends Handler {
1398        private boolean mBound = false;
1399        final ArrayList<HandlerParams> mPendingInstalls =
1400            new ArrayList<HandlerParams>();
1401
1402        private boolean connectToService() {
1403            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1404                    " DefaultContainerService");
1405            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1406            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1407            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1408                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1409                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1410                mBound = true;
1411                return true;
1412            }
1413            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1414            return false;
1415        }
1416
1417        private void disconnectService() {
1418            mContainerService = null;
1419            mBound = false;
1420            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1421            mContext.unbindService(mDefContainerConn);
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1423        }
1424
1425        PackageHandler(Looper looper) {
1426            super(looper);
1427        }
1428
1429        public void handleMessage(Message msg) {
1430            try {
1431                doHandleMessage(msg);
1432            } finally {
1433                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1434            }
1435        }
1436
1437        void doHandleMessage(Message msg) {
1438            switch (msg.what) {
1439                case INIT_COPY: {
1440                    HandlerParams params = (HandlerParams) msg.obj;
1441                    int idx = mPendingInstalls.size();
1442                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1443                    // If a bind was already initiated we dont really
1444                    // need to do anything. The pending install
1445                    // will be processed later on.
1446                    if (!mBound) {
1447                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1448                                System.identityHashCode(mHandler));
1449                        // If this is the only one pending we might
1450                        // have to bind to the service again.
1451                        if (!connectToService()) {
1452                            Slog.e(TAG, "Failed to bind to media container service");
1453                            params.serviceError();
1454                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1455                                    System.identityHashCode(mHandler));
1456                            if (params.traceMethod != null) {
1457                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1458                                        params.traceCookie);
1459                            }
1460                            return;
1461                        } else {
1462                            // Once we bind to the service, the first
1463                            // pending request will be processed.
1464                            mPendingInstalls.add(idx, params);
1465                        }
1466                    } else {
1467                        mPendingInstalls.add(idx, params);
1468                        // Already bound to the service. Just make
1469                        // sure we trigger off processing the first request.
1470                        if (idx == 0) {
1471                            mHandler.sendEmptyMessage(MCS_BOUND);
1472                        }
1473                    }
1474                    break;
1475                }
1476                case MCS_BOUND: {
1477                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1478                    if (msg.obj != null) {
1479                        mContainerService = (IMediaContainerService) msg.obj;
1480                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1481                                System.identityHashCode(mHandler));
1482                    }
1483                    if (mContainerService == null) {
1484                        if (!mBound) {
1485                            // Something seriously wrong since we are not bound and we are not
1486                            // waiting for connection. Bail out.
1487                            Slog.e(TAG, "Cannot bind to media container service");
1488                            for (HandlerParams params : mPendingInstalls) {
1489                                // Indicate service bind error
1490                                params.serviceError();
1491                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1492                                        System.identityHashCode(params));
1493                                if (params.traceMethod != null) {
1494                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1495                                            params.traceMethod, params.traceCookie);
1496                                }
1497                                return;
1498                            }
1499                            mPendingInstalls.clear();
1500                        } else {
1501                            Slog.w(TAG, "Waiting to connect to media container service");
1502                        }
1503                    } else if (mPendingInstalls.size() > 0) {
1504                        HandlerParams params = mPendingInstalls.get(0);
1505                        if (params != null) {
1506                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1507                                    System.identityHashCode(params));
1508                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1509                            if (params.startCopy()) {
1510                                // We are done...  look for more work or to
1511                                // go idle.
1512                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1513                                        "Checking for more work or unbind...");
1514                                // Delete pending install
1515                                if (mPendingInstalls.size() > 0) {
1516                                    mPendingInstalls.remove(0);
1517                                }
1518                                if (mPendingInstalls.size() == 0) {
1519                                    if (mBound) {
1520                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1521                                                "Posting delayed MCS_UNBIND");
1522                                        removeMessages(MCS_UNBIND);
1523                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1524                                        // Unbind after a little delay, to avoid
1525                                        // continual thrashing.
1526                                        sendMessageDelayed(ubmsg, 10000);
1527                                    }
1528                                } else {
1529                                    // There are more pending requests in queue.
1530                                    // Just post MCS_BOUND message to trigger processing
1531                                    // of next pending install.
1532                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1533                                            "Posting MCS_BOUND for next work");
1534                                    mHandler.sendEmptyMessage(MCS_BOUND);
1535                                }
1536                            }
1537                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1538                        }
1539                    } else {
1540                        // Should never happen ideally.
1541                        Slog.w(TAG, "Empty queue");
1542                    }
1543                    break;
1544                }
1545                case MCS_RECONNECT: {
1546                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1547                    if (mPendingInstalls.size() > 0) {
1548                        if (mBound) {
1549                            disconnectService();
1550                        }
1551                        if (!connectToService()) {
1552                            Slog.e(TAG, "Failed to bind to media container service");
1553                            for (HandlerParams params : mPendingInstalls) {
1554                                // Indicate service bind error
1555                                params.serviceError();
1556                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1557                                        System.identityHashCode(params));
1558                            }
1559                            mPendingInstalls.clear();
1560                        }
1561                    }
1562                    break;
1563                }
1564                case MCS_UNBIND: {
1565                    // If there is no actual work left, then time to unbind.
1566                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1567
1568                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1569                        if (mBound) {
1570                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1571
1572                            disconnectService();
1573                        }
1574                    } else if (mPendingInstalls.size() > 0) {
1575                        // There are more pending requests in queue.
1576                        // Just post MCS_BOUND message to trigger processing
1577                        // of next pending install.
1578                        mHandler.sendEmptyMessage(MCS_BOUND);
1579                    }
1580
1581                    break;
1582                }
1583                case MCS_GIVE_UP: {
1584                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1585                    HandlerParams params = mPendingInstalls.remove(0);
1586                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1587                            System.identityHashCode(params));
1588                    break;
1589                }
1590                case SEND_PENDING_BROADCAST: {
1591                    String packages[];
1592                    ArrayList<String> components[];
1593                    int size = 0;
1594                    int uids[];
1595                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1596                    synchronized (mPackages) {
1597                        if (mPendingBroadcasts == null) {
1598                            return;
1599                        }
1600                        size = mPendingBroadcasts.size();
1601                        if (size <= 0) {
1602                            // Nothing to be done. Just return
1603                            return;
1604                        }
1605                        packages = new String[size];
1606                        components = new ArrayList[size];
1607                        uids = new int[size];
1608                        int i = 0;  // filling out the above arrays
1609
1610                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1611                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1612                            Iterator<Map.Entry<String, ArrayList<String>>> it
1613                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1614                                            .entrySet().iterator();
1615                            while (it.hasNext() && i < size) {
1616                                Map.Entry<String, ArrayList<String>> ent = it.next();
1617                                packages[i] = ent.getKey();
1618                                components[i] = ent.getValue();
1619                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1620                                uids[i] = (ps != null)
1621                                        ? UserHandle.getUid(packageUserId, ps.appId)
1622                                        : -1;
1623                                i++;
1624                            }
1625                        }
1626                        size = i;
1627                        mPendingBroadcasts.clear();
1628                    }
1629                    // Send broadcasts
1630                    for (int i = 0; i < size; i++) {
1631                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1632                    }
1633                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1634                    break;
1635                }
1636                case START_CLEANING_PACKAGE: {
1637                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1638                    final String packageName = (String)msg.obj;
1639                    final int userId = msg.arg1;
1640                    final boolean andCode = msg.arg2 != 0;
1641                    synchronized (mPackages) {
1642                        if (userId == UserHandle.USER_ALL) {
1643                            int[] users = sUserManager.getUserIds();
1644                            for (int user : users) {
1645                                mSettings.addPackageToCleanLPw(
1646                                        new PackageCleanItem(user, packageName, andCode));
1647                            }
1648                        } else {
1649                            mSettings.addPackageToCleanLPw(
1650                                    new PackageCleanItem(userId, packageName, andCode));
1651                        }
1652                    }
1653                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1654                    startCleaningPackages();
1655                } break;
1656                case POST_INSTALL: {
1657                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1658
1659                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1660                    final boolean didRestore = (msg.arg2 != 0);
1661                    mRunningInstalls.delete(msg.arg1);
1662
1663                    if (data != null) {
1664                        InstallArgs args = data.args;
1665                        PackageInstalledInfo parentRes = data.res;
1666
1667                        final boolean grantPermissions = (args.installFlags
1668                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1669                        final boolean killApp = (args.installFlags
1670                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1671                        final String[] grantedPermissions = args.installGrantPermissions;
1672
1673                        // Handle the parent package
1674                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1675                                grantedPermissions, didRestore, args.installerPackageName,
1676                                args.observer);
1677
1678                        // Handle the child packages
1679                        final int childCount = (parentRes.addedChildPackages != null)
1680                                ? parentRes.addedChildPackages.size() : 0;
1681                        for (int i = 0; i < childCount; i++) {
1682                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1683                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1684                                    grantedPermissions, false, args.installerPackageName,
1685                                    args.observer);
1686                        }
1687
1688                        // Log tracing if needed
1689                        if (args.traceMethod != null) {
1690                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1691                                    args.traceCookie);
1692                        }
1693                    } else {
1694                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1695                    }
1696
1697                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1698                } break;
1699                case UPDATED_MEDIA_STATUS: {
1700                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1701                    boolean reportStatus = msg.arg1 == 1;
1702                    boolean doGc = msg.arg2 == 1;
1703                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1704                    if (doGc) {
1705                        // Force a gc to clear up stale containers.
1706                        Runtime.getRuntime().gc();
1707                    }
1708                    if (msg.obj != null) {
1709                        @SuppressWarnings("unchecked")
1710                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1711                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1712                        // Unload containers
1713                        unloadAllContainers(args);
1714                    }
1715                    if (reportStatus) {
1716                        try {
1717                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1718                                    "Invoking StorageManagerService call back");
1719                            PackageHelper.getStorageManager().finishMediaUpdate();
1720                        } catch (RemoteException e) {
1721                            Log.e(TAG, "StorageManagerService not running?");
1722                        }
1723                    }
1724                } break;
1725                case WRITE_SETTINGS: {
1726                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1727                    synchronized (mPackages) {
1728                        removeMessages(WRITE_SETTINGS);
1729                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1730                        mSettings.writeLPr();
1731                        mDirtyUsers.clear();
1732                    }
1733                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1734                } break;
1735                case WRITE_PACKAGE_RESTRICTIONS: {
1736                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1737                    synchronized (mPackages) {
1738                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1739                        for (int userId : mDirtyUsers) {
1740                            mSettings.writePackageRestrictionsLPr(userId);
1741                        }
1742                        mDirtyUsers.clear();
1743                    }
1744                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1745                } break;
1746                case WRITE_PACKAGE_LIST: {
1747                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1748                    synchronized (mPackages) {
1749                        removeMessages(WRITE_PACKAGE_LIST);
1750                        mSettings.writePackageListLPr(msg.arg1);
1751                    }
1752                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1753                } break;
1754                case CHECK_PENDING_VERIFICATION: {
1755                    final int verificationId = msg.arg1;
1756                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1757
1758                    if ((state != null) && !state.timeoutExtended()) {
1759                        final InstallArgs args = state.getInstallArgs();
1760                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1761
1762                        Slog.i(TAG, "Verification timed out for " + originUri);
1763                        mPendingVerification.remove(verificationId);
1764
1765                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1766
1767                        final UserHandle user = args.getUser();
1768                        if (getDefaultVerificationResponse(user)
1769                                == PackageManager.VERIFICATION_ALLOW) {
1770                            Slog.i(TAG, "Continuing with installation of " + originUri);
1771                            state.setVerifierResponse(Binder.getCallingUid(),
1772                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1773                            broadcastPackageVerified(verificationId, originUri,
1774                                    PackageManager.VERIFICATION_ALLOW, user);
1775                            try {
1776                                ret = args.copyApk(mContainerService, true);
1777                            } catch (RemoteException e) {
1778                                Slog.e(TAG, "Could not contact the ContainerService");
1779                            }
1780                        } else {
1781                            broadcastPackageVerified(verificationId, originUri,
1782                                    PackageManager.VERIFICATION_REJECT, user);
1783                        }
1784
1785                        Trace.asyncTraceEnd(
1786                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1787
1788                        processPendingInstall(args, ret);
1789                        mHandler.sendEmptyMessage(MCS_UNBIND);
1790                    }
1791                    break;
1792                }
1793                case PACKAGE_VERIFIED: {
1794                    final int verificationId = msg.arg1;
1795
1796                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1797                    if (state == null) {
1798                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1799                        break;
1800                    }
1801
1802                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1803
1804                    state.setVerifierResponse(response.callerUid, response.code);
1805
1806                    if (state.isVerificationComplete()) {
1807                        mPendingVerification.remove(verificationId);
1808
1809                        final InstallArgs args = state.getInstallArgs();
1810                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1811
1812                        int ret;
1813                        if (state.isInstallAllowed()) {
1814                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1815                            broadcastPackageVerified(verificationId, originUri,
1816                                    response.code, state.getInstallArgs().getUser());
1817                            try {
1818                                ret = args.copyApk(mContainerService, true);
1819                            } catch (RemoteException e) {
1820                                Slog.e(TAG, "Could not contact the ContainerService");
1821                            }
1822                        } else {
1823                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1824                        }
1825
1826                        Trace.asyncTraceEnd(
1827                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1828
1829                        processPendingInstall(args, ret);
1830                        mHandler.sendEmptyMessage(MCS_UNBIND);
1831                    }
1832
1833                    break;
1834                }
1835                case START_INTENT_FILTER_VERIFICATIONS: {
1836                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1837                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1838                            params.replacing, params.pkg);
1839                    break;
1840                }
1841                case INTENT_FILTER_VERIFIED: {
1842                    final int verificationId = msg.arg1;
1843
1844                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1845                            verificationId);
1846                    if (state == null) {
1847                        Slog.w(TAG, "Invalid IntentFilter verification token "
1848                                + verificationId + " received");
1849                        break;
1850                    }
1851
1852                    final int userId = state.getUserId();
1853
1854                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1855                            "Processing IntentFilter verification with token:"
1856                            + verificationId + " and userId:" + userId);
1857
1858                    final IntentFilterVerificationResponse response =
1859                            (IntentFilterVerificationResponse) msg.obj;
1860
1861                    state.setVerifierResponse(response.callerUid, response.code);
1862
1863                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1864                            "IntentFilter verification with token:" + verificationId
1865                            + " and userId:" + userId
1866                            + " is settings verifier response with response code:"
1867                            + response.code);
1868
1869                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1870                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1871                                + response.getFailedDomainsString());
1872                    }
1873
1874                    if (state.isVerificationComplete()) {
1875                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1876                    } else {
1877                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1878                                "IntentFilter verification with token:" + verificationId
1879                                + " was not said to be complete");
1880                    }
1881
1882                    break;
1883                }
1884                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1885                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1886                            mInstantAppResolverConnection,
1887                            (InstantAppRequest) msg.obj,
1888                            mInstantAppInstallerActivity,
1889                            mHandler);
1890                }
1891            }
1892        }
1893    }
1894
1895    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1896            boolean killApp, String[] grantedPermissions,
1897            boolean launchedForRestore, String installerPackage,
1898            IPackageInstallObserver2 installObserver) {
1899        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1900            // Send the removed broadcasts
1901            if (res.removedInfo != null) {
1902                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1903            }
1904
1905            // Now that we successfully installed the package, grant runtime
1906            // permissions if requested before broadcasting the install. Also
1907            // for legacy apps in permission review mode we clear the permission
1908            // review flag which is used to emulate runtime permissions for
1909            // legacy apps.
1910            if (grantPermissions) {
1911                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1912            }
1913
1914            final boolean update = res.removedInfo != null
1915                    && res.removedInfo.removedPackage != null;
1916            final String origInstallerPackageName = res.removedInfo != null
1917                    ? res.removedInfo.installerPackageName : null;
1918
1919            // If this is the first time we have child packages for a disabled privileged
1920            // app that had no children, we grant requested runtime permissions to the new
1921            // children if the parent on the system image had them already granted.
1922            if (res.pkg.parentPackage != null) {
1923                synchronized (mPackages) {
1924                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1925                }
1926            }
1927
1928            synchronized (mPackages) {
1929                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1930            }
1931
1932            final String packageName = res.pkg.applicationInfo.packageName;
1933
1934            // Determine the set of users who are adding this package for
1935            // the first time vs. those who are seeing an update.
1936            int[] firstUsers = EMPTY_INT_ARRAY;
1937            int[] updateUsers = EMPTY_INT_ARRAY;
1938            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1939            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1940            for (int newUser : res.newUsers) {
1941                if (ps.getInstantApp(newUser)) {
1942                    continue;
1943                }
1944                if (allNewUsers) {
1945                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1946                    continue;
1947                }
1948                boolean isNew = true;
1949                for (int origUser : res.origUsers) {
1950                    if (origUser == newUser) {
1951                        isNew = false;
1952                        break;
1953                    }
1954                }
1955                if (isNew) {
1956                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1957                } else {
1958                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1959                }
1960            }
1961
1962            // Send installed broadcasts if the package is not a static shared lib.
1963            if (res.pkg.staticSharedLibName == null) {
1964                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1965
1966                // Send added for users that see the package for the first time
1967                // sendPackageAddedForNewUsers also deals with system apps
1968                int appId = UserHandle.getAppId(res.uid);
1969                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1970                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1971
1972                // Send added for users that don't see the package for the first time
1973                Bundle extras = new Bundle(1);
1974                extras.putInt(Intent.EXTRA_UID, res.uid);
1975                if (update) {
1976                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1977                }
1978                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1979                        extras, 0 /*flags*/,
1980                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1981                if (origInstallerPackageName != null) {
1982                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1983                            extras, 0 /*flags*/,
1984                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1985                }
1986
1987                // Send replaced for users that don't see the package for the first time
1988                if (update) {
1989                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1990                            packageName, extras, 0 /*flags*/,
1991                            null /*targetPackage*/, null /*finishedReceiver*/,
1992                            updateUsers);
1993                    if (origInstallerPackageName != null) {
1994                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1995                                extras, 0 /*flags*/,
1996                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1997                    }
1998                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1999                            null /*package*/, null /*extras*/, 0 /*flags*/,
2000                            packageName /*targetPackage*/,
2001                            null /*finishedReceiver*/, updateUsers);
2002                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2003                    // First-install and we did a restore, so we're responsible for the
2004                    // first-launch broadcast.
2005                    if (DEBUG_BACKUP) {
2006                        Slog.i(TAG, "Post-restore of " + packageName
2007                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2008                    }
2009                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2010                }
2011
2012                // Send broadcast package appeared if forward locked/external for all users
2013                // treat asec-hosted packages like removable media on upgrade
2014                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2015                    if (DEBUG_INSTALL) {
2016                        Slog.i(TAG, "upgrading pkg " + res.pkg
2017                                + " is ASEC-hosted -> AVAILABLE");
2018                    }
2019                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2020                    ArrayList<String> pkgList = new ArrayList<>(1);
2021                    pkgList.add(packageName);
2022                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2023                }
2024            }
2025
2026            // Work that needs to happen on first install within each user
2027            if (firstUsers != null && firstUsers.length > 0) {
2028                synchronized (mPackages) {
2029                    for (int userId : firstUsers) {
2030                        // If this app is a browser and it's newly-installed for some
2031                        // users, clear any default-browser state in those users. The
2032                        // app's nature doesn't depend on the user, so we can just check
2033                        // its browser nature in any user and generalize.
2034                        if (packageIsBrowser(packageName, userId)) {
2035                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2036                        }
2037
2038                        // We may also need to apply pending (restored) runtime
2039                        // permission grants within these users.
2040                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2041                    }
2042                }
2043            }
2044
2045            // Log current value of "unknown sources" setting
2046            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2047                    getUnknownSourcesSettings());
2048
2049            // Remove the replaced package's older resources safely now
2050            // We delete after a gc for applications  on sdcard.
2051            if (res.removedInfo != null && res.removedInfo.args != null) {
2052                Runtime.getRuntime().gc();
2053                synchronized (mInstallLock) {
2054                    res.removedInfo.args.doPostDeleteLI(true);
2055                }
2056            } else {
2057                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2058                // and not block here.
2059                VMRuntime.getRuntime().requestConcurrentGC();
2060            }
2061
2062            // Notify DexManager that the package was installed for new users.
2063            // The updated users should already be indexed and the package code paths
2064            // should not change.
2065            // Don't notify the manager for ephemeral apps as they are not expected to
2066            // survive long enough to benefit of background optimizations.
2067            for (int userId : firstUsers) {
2068                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2069                // There's a race currently where some install events may interleave with an uninstall.
2070                // This can lead to package info being null (b/36642664).
2071                if (info != null) {
2072                    mDexManager.notifyPackageInstalled(info, userId);
2073                }
2074            }
2075        }
2076
2077        // If someone is watching installs - notify them
2078        if (installObserver != null) {
2079            try {
2080                Bundle extras = extrasForInstallResult(res);
2081                installObserver.onPackageInstalled(res.name, res.returnCode,
2082                        res.returnMsg, extras);
2083            } catch (RemoteException e) {
2084                Slog.i(TAG, "Observer no longer exists.");
2085            }
2086        }
2087    }
2088
2089    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2090            PackageParser.Package pkg) {
2091        if (pkg.parentPackage == null) {
2092            return;
2093        }
2094        if (pkg.requestedPermissions == null) {
2095            return;
2096        }
2097        final PackageSetting disabledSysParentPs = mSettings
2098                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2099        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2100                || !disabledSysParentPs.isPrivileged()
2101                || (disabledSysParentPs.childPackageNames != null
2102                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2103            return;
2104        }
2105        final int[] allUserIds = sUserManager.getUserIds();
2106        final int permCount = pkg.requestedPermissions.size();
2107        for (int i = 0; i < permCount; i++) {
2108            String permission = pkg.requestedPermissions.get(i);
2109            BasePermission bp = mSettings.mPermissions.get(permission);
2110            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2111                continue;
2112            }
2113            for (int userId : allUserIds) {
2114                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2115                        permission, userId)) {
2116                    grantRuntimePermission(pkg.packageName, permission, userId);
2117                }
2118            }
2119        }
2120    }
2121
2122    private StorageEventListener mStorageListener = new StorageEventListener() {
2123        @Override
2124        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2125            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2126                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2127                    final String volumeUuid = vol.getFsUuid();
2128
2129                    // Clean up any users or apps that were removed or recreated
2130                    // while this volume was missing
2131                    sUserManager.reconcileUsers(volumeUuid);
2132                    reconcileApps(volumeUuid);
2133
2134                    // Clean up any install sessions that expired or were
2135                    // cancelled while this volume was missing
2136                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2137
2138                    loadPrivatePackages(vol);
2139
2140                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2141                    unloadPrivatePackages(vol);
2142                }
2143            }
2144
2145            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2146                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2147                    updateExternalMediaStatus(true, false);
2148                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2149                    updateExternalMediaStatus(false, false);
2150                }
2151            }
2152        }
2153
2154        @Override
2155        public void onVolumeForgotten(String fsUuid) {
2156            if (TextUtils.isEmpty(fsUuid)) {
2157                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2158                return;
2159            }
2160
2161            // Remove any apps installed on the forgotten volume
2162            synchronized (mPackages) {
2163                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2164                for (PackageSetting ps : packages) {
2165                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2166                    deletePackageVersioned(new VersionedPackage(ps.name,
2167                            PackageManager.VERSION_CODE_HIGHEST),
2168                            new LegacyPackageDeleteObserver(null).getBinder(),
2169                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2170                    // Try very hard to release any references to this package
2171                    // so we don't risk the system server being killed due to
2172                    // open FDs
2173                    AttributeCache.instance().removePackage(ps.name);
2174                }
2175
2176                mSettings.onVolumeForgotten(fsUuid);
2177                mSettings.writeLPr();
2178            }
2179        }
2180    };
2181
2182    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2183            String[] grantedPermissions) {
2184        for (int userId : userIds) {
2185            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2186        }
2187    }
2188
2189    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2190            String[] grantedPermissions) {
2191        PackageSetting ps = (PackageSetting) pkg.mExtras;
2192        if (ps == null) {
2193            return;
2194        }
2195
2196        PermissionsState permissionsState = ps.getPermissionsState();
2197
2198        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2199                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2200
2201        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2202                >= Build.VERSION_CODES.M;
2203
2204        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2205
2206        for (String permission : pkg.requestedPermissions) {
2207            final BasePermission bp;
2208            synchronized (mPackages) {
2209                bp = mSettings.mPermissions.get(permission);
2210            }
2211            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2212                    && (!instantApp || bp.isInstant())
2213                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2214                    && (grantedPermissions == null
2215                           || ArrayUtils.contains(grantedPermissions, permission))) {
2216                final int flags = permissionsState.getPermissionFlags(permission, userId);
2217                if (supportsRuntimePermissions) {
2218                    // Installer cannot change immutable permissions.
2219                    if ((flags & immutableFlags) == 0) {
2220                        grantRuntimePermission(pkg.packageName, permission, userId);
2221                    }
2222                } else if (mPermissionReviewRequired) {
2223                    // In permission review mode we clear the review flag when we
2224                    // are asked to install the app with all permissions granted.
2225                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2226                        updatePermissionFlags(permission, pkg.packageName,
2227                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2228                    }
2229                }
2230            }
2231        }
2232    }
2233
2234    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2235        Bundle extras = null;
2236        switch (res.returnCode) {
2237            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2238                extras = new Bundle();
2239                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2240                        res.origPermission);
2241                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2242                        res.origPackage);
2243                break;
2244            }
2245            case PackageManager.INSTALL_SUCCEEDED: {
2246                extras = new Bundle();
2247                extras.putBoolean(Intent.EXTRA_REPLACING,
2248                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2249                break;
2250            }
2251        }
2252        return extras;
2253    }
2254
2255    void scheduleWriteSettingsLocked() {
2256        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2257            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2258        }
2259    }
2260
2261    void scheduleWritePackageListLocked(int userId) {
2262        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2263            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2264            msg.arg1 = userId;
2265            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2266        }
2267    }
2268
2269    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2270        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2271        scheduleWritePackageRestrictionsLocked(userId);
2272    }
2273
2274    void scheduleWritePackageRestrictionsLocked(int userId) {
2275        final int[] userIds = (userId == UserHandle.USER_ALL)
2276                ? sUserManager.getUserIds() : new int[]{userId};
2277        for (int nextUserId : userIds) {
2278            if (!sUserManager.exists(nextUserId)) return;
2279            mDirtyUsers.add(nextUserId);
2280            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2281                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2282            }
2283        }
2284    }
2285
2286    public static PackageManagerService main(Context context, Installer installer,
2287            boolean factoryTest, boolean onlyCore) {
2288        // Self-check for initial settings.
2289        PackageManagerServiceCompilerMapping.checkProperties();
2290
2291        PackageManagerService m = new PackageManagerService(context, installer,
2292                factoryTest, onlyCore);
2293        m.enableSystemUserPackages();
2294        ServiceManager.addService("package", m);
2295        return m;
2296    }
2297
2298    private void enableSystemUserPackages() {
2299        if (!UserManager.isSplitSystemUser()) {
2300            return;
2301        }
2302        // For system user, enable apps based on the following conditions:
2303        // - app is whitelisted or belong to one of these groups:
2304        //   -- system app which has no launcher icons
2305        //   -- system app which has INTERACT_ACROSS_USERS permission
2306        //   -- system IME app
2307        // - app is not in the blacklist
2308        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2309        Set<String> enableApps = new ArraySet<>();
2310        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2311                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2312                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2313        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2314        enableApps.addAll(wlApps);
2315        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2316                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2317        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2318        enableApps.removeAll(blApps);
2319        Log.i(TAG, "Applications installed for system user: " + enableApps);
2320        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2321                UserHandle.SYSTEM);
2322        final int allAppsSize = allAps.size();
2323        synchronized (mPackages) {
2324            for (int i = 0; i < allAppsSize; i++) {
2325                String pName = allAps.get(i);
2326                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2327                // Should not happen, but we shouldn't be failing if it does
2328                if (pkgSetting == null) {
2329                    continue;
2330                }
2331                boolean install = enableApps.contains(pName);
2332                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2333                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2334                            + " for system user");
2335                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2336                }
2337            }
2338            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2339        }
2340    }
2341
2342    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2343        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2344                Context.DISPLAY_SERVICE);
2345        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2346    }
2347
2348    /**
2349     * Requests that files preopted on a secondary system partition be copied to the data partition
2350     * if possible.  Note that the actual copying of the files is accomplished by init for security
2351     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2352     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2353     */
2354    private static void requestCopyPreoptedFiles() {
2355        final int WAIT_TIME_MS = 100;
2356        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2357        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2358            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2359            // We will wait for up to 100 seconds.
2360            final long timeStart = SystemClock.uptimeMillis();
2361            final long timeEnd = timeStart + 100 * 1000;
2362            long timeNow = timeStart;
2363            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2364                try {
2365                    Thread.sleep(WAIT_TIME_MS);
2366                } catch (InterruptedException e) {
2367                    // Do nothing
2368                }
2369                timeNow = SystemClock.uptimeMillis();
2370                if (timeNow > timeEnd) {
2371                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2372                    Slog.wtf(TAG, "cppreopt did not finish!");
2373                    break;
2374                }
2375            }
2376
2377            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2378        }
2379    }
2380
2381    public PackageManagerService(Context context, Installer installer,
2382            boolean factoryTest, boolean onlyCore) {
2383        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2384        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2385        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2386                SystemClock.uptimeMillis());
2387
2388        if (mSdkVersion <= 0) {
2389            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2390        }
2391
2392        mContext = context;
2393
2394        mPermissionReviewRequired = context.getResources().getBoolean(
2395                R.bool.config_permissionReviewRequired);
2396
2397        mFactoryTest = factoryTest;
2398        mOnlyCore = onlyCore;
2399        mMetrics = new DisplayMetrics();
2400        mSettings = new Settings(mPackages);
2401        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2402                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2408                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2409        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2410                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2411        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2412                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2413
2414        String separateProcesses = SystemProperties.get("debug.separate_processes");
2415        if (separateProcesses != null && separateProcesses.length() > 0) {
2416            if ("*".equals(separateProcesses)) {
2417                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2418                mSeparateProcesses = null;
2419                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2420            } else {
2421                mDefParseFlags = 0;
2422                mSeparateProcesses = separateProcesses.split(",");
2423                Slog.w(TAG, "Running with debug.separate_processes: "
2424                        + separateProcesses);
2425            }
2426        } else {
2427            mDefParseFlags = 0;
2428            mSeparateProcesses = null;
2429        }
2430
2431        mInstaller = installer;
2432        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2433                "*dexopt*");
2434        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2435        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2436
2437        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2438                FgThread.get().getLooper());
2439
2440        getDefaultDisplayMetrics(context, mMetrics);
2441
2442        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2443        SystemConfig systemConfig = SystemConfig.getInstance();
2444        mGlobalGids = systemConfig.getGlobalGids();
2445        mSystemPermissions = systemConfig.getSystemPermissions();
2446        mAvailableFeatures = systemConfig.getAvailableFeatures();
2447        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2448
2449        mProtectedPackages = new ProtectedPackages(mContext);
2450
2451        synchronized (mInstallLock) {
2452        // writer
2453        synchronized (mPackages) {
2454            mHandlerThread = new ServiceThread(TAG,
2455                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2456            mHandlerThread.start();
2457            mHandler = new PackageHandler(mHandlerThread.getLooper());
2458            mProcessLoggingHandler = new ProcessLoggingHandler();
2459            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2460
2461            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2462            mInstantAppRegistry = new InstantAppRegistry(this);
2463
2464            File dataDir = Environment.getDataDirectory();
2465            mAppInstallDir = new File(dataDir, "app");
2466            mAppLib32InstallDir = new File(dataDir, "app-lib");
2467            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2468            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2469            sUserManager = new UserManagerService(context, this,
2470                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2471
2472            // Propagate permission configuration in to package manager.
2473            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2474                    = systemConfig.getPermissions();
2475            for (int i=0; i<permConfig.size(); i++) {
2476                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2477                BasePermission bp = mSettings.mPermissions.get(perm.name);
2478                if (bp == null) {
2479                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2480                    mSettings.mPermissions.put(perm.name, bp);
2481                }
2482                if (perm.gids != null) {
2483                    bp.setGids(perm.gids, perm.perUser);
2484                }
2485            }
2486
2487            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2488            final int builtInLibCount = libConfig.size();
2489            for (int i = 0; i < builtInLibCount; i++) {
2490                String name = libConfig.keyAt(i);
2491                String path = libConfig.valueAt(i);
2492                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2493                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2494            }
2495
2496            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2497
2498            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2499            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2500            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2501
2502            // Clean up orphaned packages for which the code path doesn't exist
2503            // and they are an update to a system app - caused by bug/32321269
2504            final int packageSettingCount = mSettings.mPackages.size();
2505            for (int i = packageSettingCount - 1; i >= 0; i--) {
2506                PackageSetting ps = mSettings.mPackages.valueAt(i);
2507                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2508                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2509                    mSettings.mPackages.removeAt(i);
2510                    mSettings.enableSystemPackageLPw(ps.name);
2511                }
2512            }
2513
2514            if (mFirstBoot) {
2515                requestCopyPreoptedFiles();
2516            }
2517
2518            String customResolverActivity = Resources.getSystem().getString(
2519                    R.string.config_customResolverActivity);
2520            if (TextUtils.isEmpty(customResolverActivity)) {
2521                customResolverActivity = null;
2522            } else {
2523                mCustomResolverComponentName = ComponentName.unflattenFromString(
2524                        customResolverActivity);
2525            }
2526
2527            long startTime = SystemClock.uptimeMillis();
2528
2529            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2530                    startTime);
2531
2532            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2533            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2534
2535            if (bootClassPath == null) {
2536                Slog.w(TAG, "No BOOTCLASSPATH found!");
2537            }
2538
2539            if (systemServerClassPath == null) {
2540                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2541            }
2542
2543            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2544
2545            final VersionInfo ver = mSettings.getInternalVersion();
2546            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2547            if (mIsUpgrade) {
2548                logCriticalInfo(Log.INFO,
2549                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2550            }
2551
2552            // when upgrading from pre-M, promote system app permissions from install to runtime
2553            mPromoteSystemApps =
2554                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2555
2556            // When upgrading from pre-N, we need to handle package extraction like first boot,
2557            // as there is no profiling data available.
2558            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2559
2560            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2561
2562            // save off the names of pre-existing system packages prior to scanning; we don't
2563            // want to automatically grant runtime permissions for new system apps
2564            if (mPromoteSystemApps) {
2565                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2566                while (pkgSettingIter.hasNext()) {
2567                    PackageSetting ps = pkgSettingIter.next();
2568                    if (isSystemApp(ps)) {
2569                        mExistingSystemPackages.add(ps.name);
2570                    }
2571                }
2572            }
2573
2574            mCacheDir = preparePackageParserCache(mIsUpgrade);
2575
2576            // Set flag to monitor and not change apk file paths when
2577            // scanning install directories.
2578            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2579
2580            if (mIsUpgrade || mFirstBoot) {
2581                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2582            }
2583
2584            // Collect vendor overlay packages. (Do this before scanning any apps.)
2585            // For security and version matching reason, only consider
2586            // overlay packages if they reside in the right directory.
2587            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2588                    | PackageParser.PARSE_IS_SYSTEM
2589                    | PackageParser.PARSE_IS_SYSTEM_DIR
2590                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2591
2592            mParallelPackageParserCallback.findStaticOverlayPackages();
2593
2594            // Find base frameworks (resource packages without code).
2595            scanDirTracedLI(frameworkDir, mDefParseFlags
2596                    | PackageParser.PARSE_IS_SYSTEM
2597                    | PackageParser.PARSE_IS_SYSTEM_DIR
2598                    | PackageParser.PARSE_IS_PRIVILEGED,
2599                    scanFlags | SCAN_NO_DEX, 0);
2600
2601            // Collected privileged system packages.
2602            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2603            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2604                    | PackageParser.PARSE_IS_SYSTEM
2605                    | PackageParser.PARSE_IS_SYSTEM_DIR
2606                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2607
2608            // Collect ordinary system packages.
2609            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2610            scanDirTracedLI(systemAppDir, mDefParseFlags
2611                    | PackageParser.PARSE_IS_SYSTEM
2612                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2613
2614            // Collect all vendor packages.
2615            File vendorAppDir = new File("/vendor/app");
2616            try {
2617                vendorAppDir = vendorAppDir.getCanonicalFile();
2618            } catch (IOException e) {
2619                // failed to look up canonical path, continue with original one
2620            }
2621            scanDirTracedLI(vendorAppDir, mDefParseFlags
2622                    | PackageParser.PARSE_IS_SYSTEM
2623                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2624
2625            // Collect all OEM packages.
2626            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2627            scanDirTracedLI(oemAppDir, mDefParseFlags
2628                    | PackageParser.PARSE_IS_SYSTEM
2629                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2630
2631            // Prune any system packages that no longer exist.
2632            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2633            if (!mOnlyCore) {
2634                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2635                while (psit.hasNext()) {
2636                    PackageSetting ps = psit.next();
2637
2638                    /*
2639                     * If this is not a system app, it can't be a
2640                     * disable system app.
2641                     */
2642                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2643                        continue;
2644                    }
2645
2646                    /*
2647                     * If the package is scanned, it's not erased.
2648                     */
2649                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2650                    if (scannedPkg != null) {
2651                        /*
2652                         * If the system app is both scanned and in the
2653                         * disabled packages list, then it must have been
2654                         * added via OTA. Remove it from the currently
2655                         * scanned package so the previously user-installed
2656                         * application can be scanned.
2657                         */
2658                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2659                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2660                                    + ps.name + "; removing system app.  Last known codePath="
2661                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2662                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2663                                    + scannedPkg.mVersionCode);
2664                            removePackageLI(scannedPkg, true);
2665                            mExpectingBetter.put(ps.name, ps.codePath);
2666                        }
2667
2668                        continue;
2669                    }
2670
2671                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2672                        psit.remove();
2673                        logCriticalInfo(Log.WARN, "System package " + ps.name
2674                                + " no longer exists; it's data will be wiped");
2675                        // Actual deletion of code and data will be handled by later
2676                        // reconciliation step
2677                    } else {
2678                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2679                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2680                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2681                        }
2682                    }
2683                }
2684            }
2685
2686            //look for any incomplete package installations
2687            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2688            for (int i = 0; i < deletePkgsList.size(); i++) {
2689                // Actual deletion of code and data will be handled by later
2690                // reconciliation step
2691                final String packageName = deletePkgsList.get(i).name;
2692                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2693                synchronized (mPackages) {
2694                    mSettings.removePackageLPw(packageName);
2695                }
2696            }
2697
2698            //delete tmp files
2699            deleteTempPackageFiles();
2700
2701            // Remove any shared userIDs that have no associated packages
2702            mSettings.pruneSharedUsersLPw();
2703
2704            if (!mOnlyCore) {
2705                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2706                        SystemClock.uptimeMillis());
2707                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2708
2709                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2710                        | PackageParser.PARSE_FORWARD_LOCK,
2711                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2712
2713                /**
2714                 * Remove disable package settings for any updated system
2715                 * apps that were removed via an OTA. If they're not a
2716                 * previously-updated app, remove them completely.
2717                 * Otherwise, just revoke their system-level permissions.
2718                 */
2719                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2720                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2721                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2722
2723                    String msg;
2724                    if (deletedPkg == null) {
2725                        msg = "Updated system package " + deletedAppName
2726                                + " no longer exists; it's data will be wiped";
2727                        // Actual deletion of code and data will be handled by later
2728                        // reconciliation step
2729                    } else {
2730                        msg = "Updated system app + " + deletedAppName
2731                                + " no longer present; removing system privileges for "
2732                                + deletedAppName;
2733
2734                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2735
2736                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2737                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2738                    }
2739                    logCriticalInfo(Log.WARN, msg);
2740                }
2741
2742                /**
2743                 * Make sure all system apps that we expected to appear on
2744                 * the userdata partition actually showed up. If they never
2745                 * appeared, crawl back and revive the system version.
2746                 */
2747                for (int i = 0; i < mExpectingBetter.size(); i++) {
2748                    final String packageName = mExpectingBetter.keyAt(i);
2749                    if (!mPackages.containsKey(packageName)) {
2750                        final File scanFile = mExpectingBetter.valueAt(i);
2751
2752                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2753                                + " but never showed up; reverting to system");
2754
2755                        int reparseFlags = mDefParseFlags;
2756                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2757                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2758                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2759                                    | PackageParser.PARSE_IS_PRIVILEGED;
2760                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2761                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2762                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2763                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2764                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2765                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2766                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2767                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2768                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2769                        } else {
2770                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2771                            continue;
2772                        }
2773
2774                        mSettings.enableSystemPackageLPw(packageName);
2775
2776                        try {
2777                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2778                        } catch (PackageManagerException e) {
2779                            Slog.e(TAG, "Failed to parse original system package: "
2780                                    + e.getMessage());
2781                        }
2782                    }
2783                }
2784            }
2785            mExpectingBetter.clear();
2786
2787            // Resolve the storage manager.
2788            mStorageManagerPackage = getStorageManagerPackageName();
2789
2790            // Resolve protected action filters. Only the setup wizard is allowed to
2791            // have a high priority filter for these actions.
2792            mSetupWizardPackage = getSetupWizardPackageName();
2793            if (mProtectedFilters.size() > 0) {
2794                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2795                    Slog.i(TAG, "No setup wizard;"
2796                        + " All protected intents capped to priority 0");
2797                }
2798                for (ActivityIntentInfo filter : mProtectedFilters) {
2799                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2800                        if (DEBUG_FILTERS) {
2801                            Slog.i(TAG, "Found setup wizard;"
2802                                + " allow priority " + filter.getPriority() + ";"
2803                                + " package: " + filter.activity.info.packageName
2804                                + " activity: " + filter.activity.className
2805                                + " priority: " + filter.getPriority());
2806                        }
2807                        // skip setup wizard; allow it to keep the high priority filter
2808                        continue;
2809                    }
2810                    if (DEBUG_FILTERS) {
2811                        Slog.i(TAG, "Protected action; cap priority to 0;"
2812                                + " package: " + filter.activity.info.packageName
2813                                + " activity: " + filter.activity.className
2814                                + " origPrio: " + filter.getPriority());
2815                    }
2816                    filter.setPriority(0);
2817                }
2818            }
2819            mDeferProtectedFilters = false;
2820            mProtectedFilters.clear();
2821
2822            // Now that we know all of the shared libraries, update all clients to have
2823            // the correct library paths.
2824            updateAllSharedLibrariesLPw(null);
2825
2826            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2827                // NOTE: We ignore potential failures here during a system scan (like
2828                // the rest of the commands above) because there's precious little we
2829                // can do about it. A settings error is reported, though.
2830                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2831            }
2832
2833            // Now that we know all the packages we are keeping,
2834            // read and update their last usage times.
2835            mPackageUsage.read(mPackages);
2836            mCompilerStats.read();
2837
2838            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2839                    SystemClock.uptimeMillis());
2840            Slog.i(TAG, "Time to scan packages: "
2841                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2842                    + " seconds");
2843
2844            // If the platform SDK has changed since the last time we booted,
2845            // we need to re-grant app permission to catch any new ones that
2846            // appear.  This is really a hack, and means that apps can in some
2847            // cases get permissions that the user didn't initially explicitly
2848            // allow...  it would be nice to have some better way to handle
2849            // this situation.
2850            int updateFlags = UPDATE_PERMISSIONS_ALL;
2851            if (ver.sdkVersion != mSdkVersion) {
2852                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2853                        + mSdkVersion + "; regranting permissions for internal storage");
2854                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2855            }
2856            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2857            ver.sdkVersion = mSdkVersion;
2858
2859            // If this is the first boot or an update from pre-M, and it is a normal
2860            // boot, then we need to initialize the default preferred apps across
2861            // all defined users.
2862            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2863                for (UserInfo user : sUserManager.getUsers(true)) {
2864                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2865                    applyFactoryDefaultBrowserLPw(user.id);
2866                    primeDomainVerificationsLPw(user.id);
2867                }
2868            }
2869
2870            // Prepare storage for system user really early during boot,
2871            // since core system apps like SettingsProvider and SystemUI
2872            // can't wait for user to start
2873            final int storageFlags;
2874            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2875                storageFlags = StorageManager.FLAG_STORAGE_DE;
2876            } else {
2877                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2878            }
2879            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2880                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2881                    true /* onlyCoreApps */);
2882            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2883                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2884                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2885                traceLog.traceBegin("AppDataFixup");
2886                try {
2887                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2888                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2889                } catch (InstallerException e) {
2890                    Slog.w(TAG, "Trouble fixing GIDs", e);
2891                }
2892                traceLog.traceEnd();
2893
2894                traceLog.traceBegin("AppDataPrepare");
2895                if (deferPackages == null || deferPackages.isEmpty()) {
2896                    return;
2897                }
2898                int count = 0;
2899                for (String pkgName : deferPackages) {
2900                    PackageParser.Package pkg = null;
2901                    synchronized (mPackages) {
2902                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2903                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2904                            pkg = ps.pkg;
2905                        }
2906                    }
2907                    if (pkg != null) {
2908                        synchronized (mInstallLock) {
2909                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2910                                    true /* maybeMigrateAppData */);
2911                        }
2912                        count++;
2913                    }
2914                }
2915                traceLog.traceEnd();
2916                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2917            }, "prepareAppData");
2918
2919            // If this is first boot after an OTA, and a normal boot, then
2920            // we need to clear code cache directories.
2921            // Note that we do *not* clear the application profiles. These remain valid
2922            // across OTAs and are used to drive profile verification (post OTA) and
2923            // profile compilation (without waiting to collect a fresh set of profiles).
2924            if (mIsUpgrade && !onlyCore) {
2925                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2926                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2927                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2928                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2929                        // No apps are running this early, so no need to freeze
2930                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2931                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2932                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2933                    }
2934                }
2935                ver.fingerprint = Build.FINGERPRINT;
2936            }
2937
2938            checkDefaultBrowser();
2939
2940            // clear only after permissions and other defaults have been updated
2941            mExistingSystemPackages.clear();
2942            mPromoteSystemApps = false;
2943
2944            // All the changes are done during package scanning.
2945            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2946
2947            // can downgrade to reader
2948            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2949            mSettings.writeLPr();
2950            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2951            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2952                    SystemClock.uptimeMillis());
2953
2954            if (!mOnlyCore) {
2955                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2956                mRequiredInstallerPackage = getRequiredInstallerLPr();
2957                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2958                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2959                if (mIntentFilterVerifierComponent != null) {
2960                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2961                            mIntentFilterVerifierComponent);
2962                } else {
2963                    mIntentFilterVerifier = null;
2964                }
2965                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2966                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2967                        SharedLibraryInfo.VERSION_UNDEFINED);
2968                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2969                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2970                        SharedLibraryInfo.VERSION_UNDEFINED);
2971            } else {
2972                mRequiredVerifierPackage = null;
2973                mRequiredInstallerPackage = null;
2974                mRequiredUninstallerPackage = null;
2975                mIntentFilterVerifierComponent = null;
2976                mIntentFilterVerifier = null;
2977                mServicesSystemSharedLibraryPackageName = null;
2978                mSharedSystemSharedLibraryPackageName = null;
2979            }
2980
2981            mInstallerService = new PackageInstallerService(context, this);
2982            final Pair<ComponentName, String> instantAppResolverComponent =
2983                    getInstantAppResolverLPr();
2984            if (instantAppResolverComponent != null) {
2985                if (DEBUG_EPHEMERAL) {
2986                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2987                }
2988                mInstantAppResolverConnection = new EphemeralResolverConnection(
2989                        mContext, instantAppResolverComponent.first,
2990                        instantAppResolverComponent.second);
2991                mInstantAppResolverSettingsComponent =
2992                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2993            } else {
2994                mInstantAppResolverConnection = null;
2995                mInstantAppResolverSettingsComponent = null;
2996            }
2997            updateInstantAppInstallerLocked(null);
2998
2999            // Read and update the usage of dex files.
3000            // Do this at the end of PM init so that all the packages have their
3001            // data directory reconciled.
3002            // At this point we know the code paths of the packages, so we can validate
3003            // the disk file and build the internal cache.
3004            // The usage file is expected to be small so loading and verifying it
3005            // should take a fairly small time compare to the other activities (e.g. package
3006            // scanning).
3007            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3008            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3009            for (int userId : currentUserIds) {
3010                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3011            }
3012            mDexManager.load(userPackages);
3013        } // synchronized (mPackages)
3014        } // synchronized (mInstallLock)
3015
3016        // Now after opening every single application zip, make sure they
3017        // are all flushed.  Not really needed, but keeps things nice and
3018        // tidy.
3019        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3020        Runtime.getRuntime().gc();
3021        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3022
3023        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3024        FallbackCategoryProvider.loadFallbacks();
3025        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3026
3027        // The initial scanning above does many calls into installd while
3028        // holding the mPackages lock, but we're mostly interested in yelling
3029        // once we have a booted system.
3030        mInstaller.setWarnIfHeld(mPackages);
3031
3032        // Expose private service for system components to use.
3033        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3034        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3035    }
3036
3037    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3038        // we're only interested in updating the installer appliction when 1) it's not
3039        // already set or 2) the modified package is the installer
3040        if (mInstantAppInstallerActivity != null
3041                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3042                        .equals(modifiedPackage)) {
3043            return;
3044        }
3045        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3046    }
3047
3048    private static File preparePackageParserCache(boolean isUpgrade) {
3049        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3050            return null;
3051        }
3052
3053        // Disable package parsing on eng builds to allow for faster incremental development.
3054        if ("eng".equals(Build.TYPE)) {
3055            return null;
3056        }
3057
3058        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3059            Slog.i(TAG, "Disabling package parser cache due to system property.");
3060            return null;
3061        }
3062
3063        // The base directory for the package parser cache lives under /data/system/.
3064        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3065                "package_cache");
3066        if (cacheBaseDir == null) {
3067            return null;
3068        }
3069
3070        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3071        // This also serves to "GC" unused entries when the package cache version changes (which
3072        // can only happen during upgrades).
3073        if (isUpgrade) {
3074            FileUtils.deleteContents(cacheBaseDir);
3075        }
3076
3077
3078        // Return the versioned package cache directory. This is something like
3079        // "/data/system/package_cache/1"
3080        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3081
3082        // The following is a workaround to aid development on non-numbered userdebug
3083        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3084        // the system partition is newer.
3085        //
3086        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3087        // that starts with "eng." to signify that this is an engineering build and not
3088        // destined for release.
3089        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3090            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3091
3092            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3093            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3094            // in general and should not be used for production changes. In this specific case,
3095            // we know that they will work.
3096            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3097            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3098                FileUtils.deleteContents(cacheBaseDir);
3099                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3100            }
3101        }
3102
3103        return cacheDir;
3104    }
3105
3106    @Override
3107    public boolean isFirstBoot() {
3108        // allow instant applications
3109        return mFirstBoot;
3110    }
3111
3112    @Override
3113    public boolean isOnlyCoreApps() {
3114        // allow instant applications
3115        return mOnlyCore;
3116    }
3117
3118    @Override
3119    public boolean isUpgrade() {
3120        // allow instant applications
3121        return mIsUpgrade;
3122    }
3123
3124    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3125        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3126
3127        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3128                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3129                UserHandle.USER_SYSTEM);
3130        if (matches.size() == 1) {
3131            return matches.get(0).getComponentInfo().packageName;
3132        } else if (matches.size() == 0) {
3133            Log.e(TAG, "There should probably be a verifier, but, none were found");
3134            return null;
3135        }
3136        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3137    }
3138
3139    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3140        synchronized (mPackages) {
3141            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3142            if (libraryEntry == null) {
3143                throw new IllegalStateException("Missing required shared library:" + name);
3144            }
3145            return libraryEntry.apk;
3146        }
3147    }
3148
3149    private @NonNull String getRequiredInstallerLPr() {
3150        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3151        intent.addCategory(Intent.CATEGORY_DEFAULT);
3152        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3153
3154        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3155                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3156                UserHandle.USER_SYSTEM);
3157        if (matches.size() == 1) {
3158            ResolveInfo resolveInfo = matches.get(0);
3159            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3160                throw new RuntimeException("The installer must be a privileged app");
3161            }
3162            return matches.get(0).getComponentInfo().packageName;
3163        } else {
3164            throw new RuntimeException("There must be exactly one installer; found " + matches);
3165        }
3166    }
3167
3168    private @NonNull String getRequiredUninstallerLPr() {
3169        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3170        intent.addCategory(Intent.CATEGORY_DEFAULT);
3171        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3172
3173        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3174                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3175                UserHandle.USER_SYSTEM);
3176        if (resolveInfo == null ||
3177                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3178            throw new RuntimeException("There must be exactly one uninstaller; found "
3179                    + resolveInfo);
3180        }
3181        return resolveInfo.getComponentInfo().packageName;
3182    }
3183
3184    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3185        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3186
3187        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3188                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3189                UserHandle.USER_SYSTEM);
3190        ResolveInfo best = null;
3191        final int N = matches.size();
3192        for (int i = 0; i < N; i++) {
3193            final ResolveInfo cur = matches.get(i);
3194            final String packageName = cur.getComponentInfo().packageName;
3195            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3196                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3197                continue;
3198            }
3199
3200            if (best == null || cur.priority > best.priority) {
3201                best = cur;
3202            }
3203        }
3204
3205        if (best != null) {
3206            return best.getComponentInfo().getComponentName();
3207        }
3208        Slog.w(TAG, "Intent filter verifier not found");
3209        return null;
3210    }
3211
3212    @Override
3213    public @Nullable ComponentName getInstantAppResolverComponent() {
3214        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3215            return null;
3216        }
3217        synchronized (mPackages) {
3218            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3219            if (instantAppResolver == null) {
3220                return null;
3221            }
3222            return instantAppResolver.first;
3223        }
3224    }
3225
3226    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3227        final String[] packageArray =
3228                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3229        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3230            if (DEBUG_EPHEMERAL) {
3231                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3232            }
3233            return null;
3234        }
3235
3236        final int callingUid = Binder.getCallingUid();
3237        final int resolveFlags =
3238                MATCH_DIRECT_BOOT_AWARE
3239                | MATCH_DIRECT_BOOT_UNAWARE
3240                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3241        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3242        final Intent resolverIntent = new Intent(actionName);
3243        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3244                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3245        // temporarily look for the old action
3246        if (resolvers.size() == 0) {
3247            if (DEBUG_EPHEMERAL) {
3248                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3249            }
3250            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3251            resolverIntent.setAction(actionName);
3252            resolvers = queryIntentServicesInternal(resolverIntent, null,
3253                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3254        }
3255        final int N = resolvers.size();
3256        if (N == 0) {
3257            if (DEBUG_EPHEMERAL) {
3258                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3259            }
3260            return null;
3261        }
3262
3263        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3264        for (int i = 0; i < N; i++) {
3265            final ResolveInfo info = resolvers.get(i);
3266
3267            if (info.serviceInfo == null) {
3268                continue;
3269            }
3270
3271            final String packageName = info.serviceInfo.packageName;
3272            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3273                if (DEBUG_EPHEMERAL) {
3274                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3275                            + " pkg: " + packageName + ", info:" + info);
3276                }
3277                continue;
3278            }
3279
3280            if (DEBUG_EPHEMERAL) {
3281                Slog.v(TAG, "Ephemeral resolver found;"
3282                        + " pkg: " + packageName + ", info:" + info);
3283            }
3284            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3285        }
3286        if (DEBUG_EPHEMERAL) {
3287            Slog.v(TAG, "Ephemeral resolver NOT found");
3288        }
3289        return null;
3290    }
3291
3292    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3293        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3294        intent.addCategory(Intent.CATEGORY_DEFAULT);
3295        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3296
3297        final int resolveFlags =
3298                MATCH_DIRECT_BOOT_AWARE
3299                | MATCH_DIRECT_BOOT_UNAWARE
3300                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3301        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3302                resolveFlags, UserHandle.USER_SYSTEM);
3303        // temporarily look for the old action
3304        if (matches.isEmpty()) {
3305            if (DEBUG_EPHEMERAL) {
3306                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3307            }
3308            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3309            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3310                    resolveFlags, UserHandle.USER_SYSTEM);
3311        }
3312        Iterator<ResolveInfo> iter = matches.iterator();
3313        while (iter.hasNext()) {
3314            final ResolveInfo rInfo = iter.next();
3315            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3316            if (ps != null) {
3317                final PermissionsState permissionsState = ps.getPermissionsState();
3318                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3319                    continue;
3320                }
3321            }
3322            iter.remove();
3323        }
3324        if (matches.size() == 0) {
3325            return null;
3326        } else if (matches.size() == 1) {
3327            return (ActivityInfo) matches.get(0).getComponentInfo();
3328        } else {
3329            throw new RuntimeException(
3330                    "There must be at most one ephemeral installer; found " + matches);
3331        }
3332    }
3333
3334    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3335            @NonNull ComponentName resolver) {
3336        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3337                .addCategory(Intent.CATEGORY_DEFAULT)
3338                .setPackage(resolver.getPackageName());
3339        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3340        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3341                UserHandle.USER_SYSTEM);
3342        // temporarily look for the old action
3343        if (matches.isEmpty()) {
3344            if (DEBUG_EPHEMERAL) {
3345                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3346            }
3347            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3348            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3349                    UserHandle.USER_SYSTEM);
3350        }
3351        if (matches.isEmpty()) {
3352            return null;
3353        }
3354        return matches.get(0).getComponentInfo().getComponentName();
3355    }
3356
3357    private void primeDomainVerificationsLPw(int userId) {
3358        if (DEBUG_DOMAIN_VERIFICATION) {
3359            Slog.d(TAG, "Priming domain verifications in user " + userId);
3360        }
3361
3362        SystemConfig systemConfig = SystemConfig.getInstance();
3363        ArraySet<String> packages = systemConfig.getLinkedApps();
3364
3365        for (String packageName : packages) {
3366            PackageParser.Package pkg = mPackages.get(packageName);
3367            if (pkg != null) {
3368                if (!pkg.isSystemApp()) {
3369                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3370                    continue;
3371                }
3372
3373                ArraySet<String> domains = null;
3374                for (PackageParser.Activity a : pkg.activities) {
3375                    for (ActivityIntentInfo filter : a.intents) {
3376                        if (hasValidDomains(filter)) {
3377                            if (domains == null) {
3378                                domains = new ArraySet<String>();
3379                            }
3380                            domains.addAll(filter.getHostsList());
3381                        }
3382                    }
3383                }
3384
3385                if (domains != null && domains.size() > 0) {
3386                    if (DEBUG_DOMAIN_VERIFICATION) {
3387                        Slog.v(TAG, "      + " + packageName);
3388                    }
3389                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3390                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3391                    // and then 'always' in the per-user state actually used for intent resolution.
3392                    final IntentFilterVerificationInfo ivi;
3393                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3394                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3395                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3396                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3397                } else {
3398                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3399                            + "' does not handle web links");
3400                }
3401            } else {
3402                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3403            }
3404        }
3405
3406        scheduleWritePackageRestrictionsLocked(userId);
3407        scheduleWriteSettingsLocked();
3408    }
3409
3410    private void applyFactoryDefaultBrowserLPw(int userId) {
3411        // The default browser app's package name is stored in a string resource,
3412        // with a product-specific overlay used for vendor customization.
3413        String browserPkg = mContext.getResources().getString(
3414                com.android.internal.R.string.default_browser);
3415        if (!TextUtils.isEmpty(browserPkg)) {
3416            // non-empty string => required to be a known package
3417            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3418            if (ps == null) {
3419                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3420                browserPkg = null;
3421            } else {
3422                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3423            }
3424        }
3425
3426        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3427        // default.  If there's more than one, just leave everything alone.
3428        if (browserPkg == null) {
3429            calculateDefaultBrowserLPw(userId);
3430        }
3431    }
3432
3433    private void calculateDefaultBrowserLPw(int userId) {
3434        List<String> allBrowsers = resolveAllBrowserApps(userId);
3435        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3436        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3437    }
3438
3439    private List<String> resolveAllBrowserApps(int userId) {
3440        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3441        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3442                PackageManager.MATCH_ALL, userId);
3443
3444        final int count = list.size();
3445        List<String> result = new ArrayList<String>(count);
3446        for (int i=0; i<count; i++) {
3447            ResolveInfo info = list.get(i);
3448            if (info.activityInfo == null
3449                    || !info.handleAllWebDataURI
3450                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3451                    || result.contains(info.activityInfo.packageName)) {
3452                continue;
3453            }
3454            result.add(info.activityInfo.packageName);
3455        }
3456
3457        return result;
3458    }
3459
3460    private boolean packageIsBrowser(String packageName, int userId) {
3461        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3462                PackageManager.MATCH_ALL, userId);
3463        final int N = list.size();
3464        for (int i = 0; i < N; i++) {
3465            ResolveInfo info = list.get(i);
3466            if (packageName.equals(info.activityInfo.packageName)) {
3467                return true;
3468            }
3469        }
3470        return false;
3471    }
3472
3473    private void checkDefaultBrowser() {
3474        final int myUserId = UserHandle.myUserId();
3475        final String packageName = getDefaultBrowserPackageName(myUserId);
3476        if (packageName != null) {
3477            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3478            if (info == null) {
3479                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3480                synchronized (mPackages) {
3481                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3482                }
3483            }
3484        }
3485    }
3486
3487    @Override
3488    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3489            throws RemoteException {
3490        try {
3491            return super.onTransact(code, data, reply, flags);
3492        } catch (RuntimeException e) {
3493            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3494                Slog.wtf(TAG, "Package Manager Crash", e);
3495            }
3496            throw e;
3497        }
3498    }
3499
3500    static int[] appendInts(int[] cur, int[] add) {
3501        if (add == null) return cur;
3502        if (cur == null) return add;
3503        final int N = add.length;
3504        for (int i=0; i<N; i++) {
3505            cur = appendInt(cur, add[i]);
3506        }
3507        return cur;
3508    }
3509
3510    /**
3511     * Returns whether or not a full application can see an instant application.
3512     * <p>
3513     * Currently, there are three cases in which this can occur:
3514     * <ol>
3515     * <li>The calling application is a "special" process. The special
3516     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3517     *     and {@code 0}</li>
3518     * <li>The calling application has the permission
3519     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3520     * <li>The calling application is the default launcher on the
3521     *     system partition.</li>
3522     * </ol>
3523     */
3524    private boolean canViewInstantApps(int callingUid, int userId) {
3525        if (callingUid == Process.SYSTEM_UID
3526                || callingUid == Process.SHELL_UID
3527                || callingUid == Process.ROOT_UID) {
3528            return true;
3529        }
3530        if (mContext.checkCallingOrSelfPermission(
3531                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3532            return true;
3533        }
3534        if (mContext.checkCallingOrSelfPermission(
3535                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3536            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3537            if (homeComponent != null
3538                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3539                return true;
3540            }
3541        }
3542        return false;
3543    }
3544
3545    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3546        if (!sUserManager.exists(userId)) return null;
3547        if (ps == null) {
3548            return null;
3549        }
3550        PackageParser.Package p = ps.pkg;
3551        if (p == null) {
3552            return null;
3553        }
3554        final int callingUid = Binder.getCallingUid();
3555        // Filter out ephemeral app metadata:
3556        //   * The system/shell/root can see metadata for any app
3557        //   * An installed app can see metadata for 1) other installed apps
3558        //     and 2) ephemeral apps that have explicitly interacted with it
3559        //   * Ephemeral apps can only see their own data and exposed installed apps
3560        //   * Holding a signature permission allows seeing instant apps
3561        if (filterAppAccessLPr(ps, callingUid, userId)) {
3562            return null;
3563        }
3564
3565        final PermissionsState permissionsState = ps.getPermissionsState();
3566
3567        // Compute GIDs only if requested
3568        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3569                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3570        // Compute granted permissions only if package has requested permissions
3571        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3572                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3573        final PackageUserState state = ps.readUserState(userId);
3574
3575        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3576                && ps.isSystem()) {
3577            flags |= MATCH_ANY_USER;
3578        }
3579
3580        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3581                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3582
3583        if (packageInfo == null) {
3584            return null;
3585        }
3586
3587        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3588
3589        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3590                resolveExternalPackageNameLPr(p);
3591
3592        return packageInfo;
3593    }
3594
3595    @Override
3596    public void checkPackageStartable(String packageName, int userId) {
3597        final int callingUid = Binder.getCallingUid();
3598        if (getInstantAppPackageName(callingUid) != null) {
3599            throw new SecurityException("Instant applications don't have access to this method");
3600        }
3601        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3602        synchronized (mPackages) {
3603            final PackageSetting ps = mSettings.mPackages.get(packageName);
3604            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3605                throw new SecurityException("Package " + packageName + " was not found!");
3606            }
3607
3608            if (!ps.getInstalled(userId)) {
3609                throw new SecurityException(
3610                        "Package " + packageName + " was not installed for user " + userId + "!");
3611            }
3612
3613            if (mSafeMode && !ps.isSystem()) {
3614                throw new SecurityException("Package " + packageName + " not a system app!");
3615            }
3616
3617            if (mFrozenPackages.contains(packageName)) {
3618                throw new SecurityException("Package " + packageName + " is currently frozen!");
3619            }
3620
3621            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3622                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3623                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3624            }
3625        }
3626    }
3627
3628    @Override
3629    public boolean isPackageAvailable(String packageName, int userId) {
3630        if (!sUserManager.exists(userId)) return false;
3631        final int callingUid = Binder.getCallingUid();
3632        enforceCrossUserPermission(callingUid, userId,
3633                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3634        synchronized (mPackages) {
3635            PackageParser.Package p = mPackages.get(packageName);
3636            if (p != null) {
3637                final PackageSetting ps = (PackageSetting) p.mExtras;
3638                if (filterAppAccessLPr(ps, callingUid, userId)) {
3639                    return false;
3640                }
3641                if (ps != null) {
3642                    final PackageUserState state = ps.readUserState(userId);
3643                    if (state != null) {
3644                        return PackageParser.isAvailable(state);
3645                    }
3646                }
3647            }
3648        }
3649        return false;
3650    }
3651
3652    @Override
3653    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3654        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3655                flags, Binder.getCallingUid(), userId);
3656    }
3657
3658    @Override
3659    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3660            int flags, int userId) {
3661        return getPackageInfoInternal(versionedPackage.getPackageName(),
3662                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3663    }
3664
3665    /**
3666     * Important: The provided filterCallingUid is used exclusively to filter out packages
3667     * that can be seen based on user state. It's typically the original caller uid prior
3668     * to clearing. Because it can only be provided by trusted code, it's value can be
3669     * trusted and will be used as-is; unlike userId which will be validated by this method.
3670     */
3671    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3672            int flags, int filterCallingUid, int userId) {
3673        if (!sUserManager.exists(userId)) return null;
3674        flags = updateFlagsForPackage(flags, userId, packageName);
3675        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3676                false /* requireFullPermission */, false /* checkShell */, "get package info");
3677
3678        // reader
3679        synchronized (mPackages) {
3680            // Normalize package name to handle renamed packages and static libs
3681            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3682
3683            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3684            if (matchFactoryOnly) {
3685                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3686                if (ps != null) {
3687                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3688                        return null;
3689                    }
3690                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3691                        return null;
3692                    }
3693                    return generatePackageInfo(ps, flags, userId);
3694                }
3695            }
3696
3697            PackageParser.Package p = mPackages.get(packageName);
3698            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3699                return null;
3700            }
3701            if (DEBUG_PACKAGE_INFO)
3702                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3703            if (p != null) {
3704                final PackageSetting ps = (PackageSetting) p.mExtras;
3705                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3706                    return null;
3707                }
3708                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3709                    return null;
3710                }
3711                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3712            }
3713            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3714                final PackageSetting ps = mSettings.mPackages.get(packageName);
3715                if (ps == null) return null;
3716                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3717                    return null;
3718                }
3719                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3720                    return null;
3721                }
3722                return generatePackageInfo(ps, flags, userId);
3723            }
3724        }
3725        return null;
3726    }
3727
3728    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3729        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3730            return true;
3731        }
3732        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3733            return true;
3734        }
3735        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3736            return true;
3737        }
3738        return false;
3739    }
3740
3741    private boolean isComponentVisibleToInstantApp(
3742            @Nullable ComponentName component, @ComponentType int type) {
3743        if (type == TYPE_ACTIVITY) {
3744            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3745            return activity != null
3746                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3747                    : false;
3748        } else if (type == TYPE_RECEIVER) {
3749            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3750            return activity != null
3751                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3752                    : false;
3753        } else if (type == TYPE_SERVICE) {
3754            final PackageParser.Service service = mServices.mServices.get(component);
3755            return service != null
3756                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3757                    : false;
3758        } else if (type == TYPE_PROVIDER) {
3759            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3760            return provider != null
3761                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3762                    : false;
3763        } else if (type == TYPE_UNKNOWN) {
3764            return isComponentVisibleToInstantApp(component);
3765        }
3766        return false;
3767    }
3768
3769    /**
3770     * Returns whether or not access to the application should be filtered.
3771     * <p>
3772     * Access may be limited based upon whether the calling or target applications
3773     * are instant applications.
3774     *
3775     * @see #canAccessInstantApps(int)
3776     */
3777    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3778            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3779        // if we're in an isolated process, get the real calling UID
3780        if (Process.isIsolated(callingUid)) {
3781            callingUid = mIsolatedOwners.get(callingUid);
3782        }
3783        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3784        final boolean callerIsInstantApp = instantAppPkgName != null;
3785        if (ps == null) {
3786            if (callerIsInstantApp) {
3787                // pretend the application exists, but, needs to be filtered
3788                return true;
3789            }
3790            return false;
3791        }
3792        // if the target and caller are the same application, don't filter
3793        if (isCallerSameApp(ps.name, callingUid)) {
3794            return false;
3795        }
3796        if (callerIsInstantApp) {
3797            // request for a specific component; if it hasn't been explicitly exposed, filter
3798            if (component != null) {
3799                return !isComponentVisibleToInstantApp(component, componentType);
3800            }
3801            // request for application; if no components have been explicitly exposed, filter
3802            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3803        }
3804        if (ps.getInstantApp(userId)) {
3805            // caller can see all components of all instant applications, don't filter
3806            if (canViewInstantApps(callingUid, userId)) {
3807                return false;
3808            }
3809            // request for a specific instant application component, filter
3810            if (component != null) {
3811                return true;
3812            }
3813            // request for an instant application; if the caller hasn't been granted access, filter
3814            return !mInstantAppRegistry.isInstantAccessGranted(
3815                    userId, UserHandle.getAppId(callingUid), ps.appId);
3816        }
3817        return false;
3818    }
3819
3820    /**
3821     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3822     */
3823    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3824        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3825    }
3826
3827    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3828            int flags) {
3829        // Callers can access only the libs they depend on, otherwise they need to explicitly
3830        // ask for the shared libraries given the caller is allowed to access all static libs.
3831        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3832            // System/shell/root get to see all static libs
3833            final int appId = UserHandle.getAppId(uid);
3834            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3835                    || appId == Process.ROOT_UID) {
3836                return false;
3837            }
3838        }
3839
3840        // No package means no static lib as it is always on internal storage
3841        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3842            return false;
3843        }
3844
3845        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3846                ps.pkg.staticSharedLibVersion);
3847        if (libEntry == null) {
3848            return false;
3849        }
3850
3851        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3852        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3853        if (uidPackageNames == null) {
3854            return true;
3855        }
3856
3857        for (String uidPackageName : uidPackageNames) {
3858            if (ps.name.equals(uidPackageName)) {
3859                return false;
3860            }
3861            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3862            if (uidPs != null) {
3863                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3864                        libEntry.info.getName());
3865                if (index < 0) {
3866                    continue;
3867                }
3868                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3869                    return false;
3870                }
3871            }
3872        }
3873        return true;
3874    }
3875
3876    @Override
3877    public String[] currentToCanonicalPackageNames(String[] names) {
3878        final int callingUid = Binder.getCallingUid();
3879        if (getInstantAppPackageName(callingUid) != null) {
3880            return names;
3881        }
3882        final String[] out = new String[names.length];
3883        // reader
3884        synchronized (mPackages) {
3885            final int callingUserId = UserHandle.getUserId(callingUid);
3886            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3887            for (int i=names.length-1; i>=0; i--) {
3888                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3889                boolean translateName = false;
3890                if (ps != null && ps.realName != null) {
3891                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3892                    translateName = !targetIsInstantApp
3893                            || canViewInstantApps
3894                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3895                                    UserHandle.getAppId(callingUid), ps.appId);
3896                }
3897                out[i] = translateName ? ps.realName : names[i];
3898            }
3899        }
3900        return out;
3901    }
3902
3903    @Override
3904    public String[] canonicalToCurrentPackageNames(String[] names) {
3905        final int callingUid = Binder.getCallingUid();
3906        if (getInstantAppPackageName(callingUid) != null) {
3907            return names;
3908        }
3909        final String[] out = new String[names.length];
3910        // reader
3911        synchronized (mPackages) {
3912            final int callingUserId = UserHandle.getUserId(callingUid);
3913            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3914            for (int i=names.length-1; i>=0; i--) {
3915                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3916                boolean translateName = false;
3917                if (cur != null) {
3918                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3919                    final boolean targetIsInstantApp =
3920                            ps != null && ps.getInstantApp(callingUserId);
3921                    translateName = !targetIsInstantApp
3922                            || canViewInstantApps
3923                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3924                                    UserHandle.getAppId(callingUid), ps.appId);
3925                }
3926                out[i] = translateName ? cur : names[i];
3927            }
3928        }
3929        return out;
3930    }
3931
3932    @Override
3933    public int getPackageUid(String packageName, int flags, int userId) {
3934        if (!sUserManager.exists(userId)) return -1;
3935        final int callingUid = Binder.getCallingUid();
3936        flags = updateFlagsForPackage(flags, userId, packageName);
3937        enforceCrossUserPermission(callingUid, userId,
3938                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3939
3940        // reader
3941        synchronized (mPackages) {
3942            final PackageParser.Package p = mPackages.get(packageName);
3943            if (p != null && p.isMatch(flags)) {
3944                PackageSetting ps = (PackageSetting) p.mExtras;
3945                if (filterAppAccessLPr(ps, callingUid, userId)) {
3946                    return -1;
3947                }
3948                return UserHandle.getUid(userId, p.applicationInfo.uid);
3949            }
3950            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3951                final PackageSetting ps = mSettings.mPackages.get(packageName);
3952                if (ps != null && ps.isMatch(flags)
3953                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3954                    return UserHandle.getUid(userId, ps.appId);
3955                }
3956            }
3957        }
3958
3959        return -1;
3960    }
3961
3962    @Override
3963    public int[] getPackageGids(String packageName, int flags, int userId) {
3964        if (!sUserManager.exists(userId)) return null;
3965        final int callingUid = Binder.getCallingUid();
3966        flags = updateFlagsForPackage(flags, userId, packageName);
3967        enforceCrossUserPermission(callingUid, userId,
3968                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3969
3970        // reader
3971        synchronized (mPackages) {
3972            final PackageParser.Package p = mPackages.get(packageName);
3973            if (p != null && p.isMatch(flags)) {
3974                PackageSetting ps = (PackageSetting) p.mExtras;
3975                if (filterAppAccessLPr(ps, callingUid, userId)) {
3976                    return null;
3977                }
3978                // TODO: Shouldn't this be checking for package installed state for userId and
3979                // return null?
3980                return ps.getPermissionsState().computeGids(userId);
3981            }
3982            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3983                final PackageSetting ps = mSettings.mPackages.get(packageName);
3984                if (ps != null && ps.isMatch(flags)
3985                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3986                    return ps.getPermissionsState().computeGids(userId);
3987                }
3988            }
3989        }
3990
3991        return null;
3992    }
3993
3994    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3995        if (bp.perm != null) {
3996            return PackageParser.generatePermissionInfo(bp.perm, flags);
3997        }
3998        PermissionInfo pi = new PermissionInfo();
3999        pi.name = bp.name;
4000        pi.packageName = bp.sourcePackage;
4001        pi.nonLocalizedLabel = bp.name;
4002        pi.protectionLevel = bp.protectionLevel;
4003        return pi;
4004    }
4005
4006    @Override
4007    public PermissionInfo getPermissionInfo(String name, int flags) {
4008        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4009            return null;
4010        }
4011        // reader
4012        synchronized (mPackages) {
4013            final BasePermission p = mSettings.mPermissions.get(name);
4014            if (p != null) {
4015                return generatePermissionInfo(p, flags);
4016            }
4017            return null;
4018        }
4019    }
4020
4021    @Override
4022    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4023            int flags) {
4024        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4025            return null;
4026        }
4027        // reader
4028        synchronized (mPackages) {
4029            if (group != null && !mPermissionGroups.containsKey(group)) {
4030                // This is thrown as NameNotFoundException
4031                return null;
4032            }
4033
4034            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4035            for (BasePermission p : mSettings.mPermissions.values()) {
4036                if (group == null) {
4037                    if (p.perm == null || p.perm.info.group == null) {
4038                        out.add(generatePermissionInfo(p, flags));
4039                    }
4040                } else {
4041                    if (p.perm != null && group.equals(p.perm.info.group)) {
4042                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4043                    }
4044                }
4045            }
4046            return new ParceledListSlice<>(out);
4047        }
4048    }
4049
4050    @Override
4051    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4052        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4053            return null;
4054        }
4055        // reader
4056        synchronized (mPackages) {
4057            return PackageParser.generatePermissionGroupInfo(
4058                    mPermissionGroups.get(name), flags);
4059        }
4060    }
4061
4062    @Override
4063    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4064        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4065            return ParceledListSlice.emptyList();
4066        }
4067        // reader
4068        synchronized (mPackages) {
4069            final int N = mPermissionGroups.size();
4070            ArrayList<PermissionGroupInfo> out
4071                    = new ArrayList<PermissionGroupInfo>(N);
4072            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4073                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4074            }
4075            return new ParceledListSlice<>(out);
4076        }
4077    }
4078
4079    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4080            int filterCallingUid, int userId) {
4081        if (!sUserManager.exists(userId)) return null;
4082        PackageSetting ps = mSettings.mPackages.get(packageName);
4083        if (ps != null) {
4084            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4085                return null;
4086            }
4087            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4088                return null;
4089            }
4090            if (ps.pkg == null) {
4091                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4092                if (pInfo != null) {
4093                    return pInfo.applicationInfo;
4094                }
4095                return null;
4096            }
4097            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4098                    ps.readUserState(userId), userId);
4099            if (ai != null) {
4100                rebaseEnabledOverlays(ai, userId);
4101                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4102            }
4103            return ai;
4104        }
4105        return null;
4106    }
4107
4108    @Override
4109    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4110        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4111    }
4112
4113    /**
4114     * Important: The provided filterCallingUid is used exclusively to filter out applications
4115     * that can be seen based on user state. It's typically the original caller uid prior
4116     * to clearing. Because it can only be provided by trusted code, it's value can be
4117     * trusted and will be used as-is; unlike userId which will be validated by this method.
4118     */
4119    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4120            int filterCallingUid, int userId) {
4121        if (!sUserManager.exists(userId)) return null;
4122        flags = updateFlagsForApplication(flags, userId, packageName);
4123        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4124                false /* requireFullPermission */, false /* checkShell */, "get application info");
4125
4126        // writer
4127        synchronized (mPackages) {
4128            // Normalize package name to handle renamed packages and static libs
4129            packageName = resolveInternalPackageNameLPr(packageName,
4130                    PackageManager.VERSION_CODE_HIGHEST);
4131
4132            PackageParser.Package p = mPackages.get(packageName);
4133            if (DEBUG_PACKAGE_INFO) Log.v(
4134                    TAG, "getApplicationInfo " + packageName
4135                    + ": " + p);
4136            if (p != null) {
4137                PackageSetting ps = mSettings.mPackages.get(packageName);
4138                if (ps == null) return null;
4139                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4140                    return null;
4141                }
4142                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4143                    return null;
4144                }
4145                // Note: isEnabledLP() does not apply here - always return info
4146                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4147                        p, flags, ps.readUserState(userId), userId);
4148                if (ai != null) {
4149                    rebaseEnabledOverlays(ai, userId);
4150                    ai.packageName = resolveExternalPackageNameLPr(p);
4151                }
4152                return ai;
4153            }
4154            if ("android".equals(packageName)||"system".equals(packageName)) {
4155                return mAndroidApplication;
4156            }
4157            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4158                // Already generates the external package name
4159                return generateApplicationInfoFromSettingsLPw(packageName,
4160                        flags, filterCallingUid, userId);
4161            }
4162        }
4163        return null;
4164    }
4165
4166    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
4167        List<String> paths = new ArrayList<>();
4168        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
4169            mEnabledOverlayPaths.get(userId);
4170        if (userSpecificOverlays != null) {
4171            if (!"android".equals(ai.packageName)) {
4172                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
4173                if (frameworkOverlays != null) {
4174                    paths.addAll(frameworkOverlays);
4175                }
4176            }
4177
4178            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
4179            if (appOverlays != null) {
4180                paths.addAll(appOverlays);
4181            }
4182        }
4183        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
4184    }
4185
4186    private String normalizePackageNameLPr(String packageName) {
4187        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4188        return normalizedPackageName != null ? normalizedPackageName : packageName;
4189    }
4190
4191    @Override
4192    public void deletePreloadsFileCache() {
4193        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4194            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4195        }
4196        File dir = Environment.getDataPreloadsFileCacheDirectory();
4197        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4198        FileUtils.deleteContents(dir);
4199    }
4200
4201    @Override
4202    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4203            final int storageFlags, final IPackageDataObserver observer) {
4204        mContext.enforceCallingOrSelfPermission(
4205                android.Manifest.permission.CLEAR_APP_CACHE, null);
4206        mHandler.post(() -> {
4207            boolean success = false;
4208            try {
4209                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4210                success = true;
4211            } catch (IOException e) {
4212                Slog.w(TAG, e);
4213            }
4214            if (observer != null) {
4215                try {
4216                    observer.onRemoveCompleted(null, success);
4217                } catch (RemoteException e) {
4218                    Slog.w(TAG, e);
4219                }
4220            }
4221        });
4222    }
4223
4224    @Override
4225    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4226            final int storageFlags, final IntentSender pi) {
4227        mContext.enforceCallingOrSelfPermission(
4228                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4229        mHandler.post(() -> {
4230            boolean success = false;
4231            try {
4232                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4233                success = true;
4234            } catch (IOException e) {
4235                Slog.w(TAG, e);
4236            }
4237            if (pi != null) {
4238                try {
4239                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4240                } catch (SendIntentException e) {
4241                    Slog.w(TAG, e);
4242                }
4243            }
4244        });
4245    }
4246
4247    /**
4248     * Blocking call to clear various types of cached data across the system
4249     * until the requested bytes are available.
4250     */
4251    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4252        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4253        final File file = storage.findPathForUuid(volumeUuid);
4254        if (file.getUsableSpace() >= bytes) return;
4255
4256        if (ENABLE_FREE_CACHE_V2) {
4257            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4258                    volumeUuid);
4259            final boolean aggressive = (storageFlags
4260                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4261            final boolean defyReserved = (storageFlags
4262                    & StorageManager.FLAG_ALLOCATE_DEFY_RESERVED) != 0;
4263            final long reservedBytes = (aggressive || defyReserved) ? 0
4264                    : storage.getStorageCacheBytes(file);
4265
4266            // 1. Pre-flight to determine if we have any chance to succeed
4267            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4268            if (internalVolume && (aggressive || SystemProperties
4269                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4270                deletePreloadsFileCache();
4271                if (file.getUsableSpace() >= bytes) return;
4272            }
4273
4274            // 3. Consider parsed APK data (aggressive only)
4275            if (internalVolume && aggressive) {
4276                FileUtils.deleteContents(mCacheDir);
4277                if (file.getUsableSpace() >= bytes) return;
4278            }
4279
4280            // 4. Consider cached app data (above quotas)
4281            try {
4282                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4283                        Installer.FLAG_FREE_CACHE_V2);
4284            } catch (InstallerException ignored) {
4285            }
4286            if (file.getUsableSpace() >= bytes) return;
4287
4288            // 5. Consider shared libraries with refcount=0 and age>min cache period
4289            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4290                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4291                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4292                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4293                return;
4294            }
4295
4296            // 6. Consider dexopt output (aggressive only)
4297            // TODO: Implement
4298
4299            // 7. Consider installed instant apps unused longer than min cache period
4300            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4301                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4302                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4303                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4304                return;
4305            }
4306
4307            // 8. Consider cached app data (below quotas)
4308            try {
4309                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4310                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4311            } catch (InstallerException ignored) {
4312            }
4313            if (file.getUsableSpace() >= bytes) return;
4314
4315            // 9. Consider DropBox entries
4316            // TODO: Implement
4317
4318            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4319            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4320                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4321                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4322                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4323                return;
4324            }
4325        } else {
4326            try {
4327                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4328            } catch (InstallerException ignored) {
4329            }
4330            if (file.getUsableSpace() >= bytes) return;
4331        }
4332
4333        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4334    }
4335
4336    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4337            throws IOException {
4338        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4339        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4340
4341        List<VersionedPackage> packagesToDelete = null;
4342        final long now = System.currentTimeMillis();
4343
4344        synchronized (mPackages) {
4345            final int[] allUsers = sUserManager.getUserIds();
4346            final int libCount = mSharedLibraries.size();
4347            for (int i = 0; i < libCount; i++) {
4348                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4349                if (versionedLib == null) {
4350                    continue;
4351                }
4352                final int versionCount = versionedLib.size();
4353                for (int j = 0; j < versionCount; j++) {
4354                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4355                    // Skip packages that are not static shared libs.
4356                    if (!libInfo.isStatic()) {
4357                        break;
4358                    }
4359                    // Important: We skip static shared libs used for some user since
4360                    // in such a case we need to keep the APK on the device. The check for
4361                    // a lib being used for any user is performed by the uninstall call.
4362                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4363                    // Resolve the package name - we use synthetic package names internally
4364                    final String internalPackageName = resolveInternalPackageNameLPr(
4365                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4366                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4367                    // Skip unused static shared libs cached less than the min period
4368                    // to prevent pruning a lib needed by a subsequently installed package.
4369                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4370                        continue;
4371                    }
4372                    if (packagesToDelete == null) {
4373                        packagesToDelete = new ArrayList<>();
4374                    }
4375                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4376                            declaringPackage.getVersionCode()));
4377                }
4378            }
4379        }
4380
4381        if (packagesToDelete != null) {
4382            final int packageCount = packagesToDelete.size();
4383            for (int i = 0; i < packageCount; i++) {
4384                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4385                // Delete the package synchronously (will fail of the lib used for any user).
4386                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4387                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4388                                == PackageManager.DELETE_SUCCEEDED) {
4389                    if (volume.getUsableSpace() >= neededSpace) {
4390                        return true;
4391                    }
4392                }
4393            }
4394        }
4395
4396        return false;
4397    }
4398
4399    /**
4400     * Update given flags based on encryption status of current user.
4401     */
4402    private int updateFlags(int flags, int userId) {
4403        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4404                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4405            // Caller expressed an explicit opinion about what encryption
4406            // aware/unaware components they want to see, so fall through and
4407            // give them what they want
4408        } else {
4409            // Caller expressed no opinion, so match based on user state
4410            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4411                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4412            } else {
4413                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4414            }
4415        }
4416        return flags;
4417    }
4418
4419    private UserManagerInternal getUserManagerInternal() {
4420        if (mUserManagerInternal == null) {
4421            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4422        }
4423        return mUserManagerInternal;
4424    }
4425
4426    private DeviceIdleController.LocalService getDeviceIdleController() {
4427        if (mDeviceIdleController == null) {
4428            mDeviceIdleController =
4429                    LocalServices.getService(DeviceIdleController.LocalService.class);
4430        }
4431        return mDeviceIdleController;
4432    }
4433
4434    /**
4435     * Update given flags when being used to request {@link PackageInfo}.
4436     */
4437    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4438        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4439        boolean triaged = true;
4440        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4441                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4442            // Caller is asking for component details, so they'd better be
4443            // asking for specific encryption matching behavior, or be triaged
4444            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4445                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4446                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4447                triaged = false;
4448            }
4449        }
4450        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4451                | PackageManager.MATCH_SYSTEM_ONLY
4452                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4453            triaged = false;
4454        }
4455        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4456            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4457                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4458                    + Debug.getCallers(5));
4459        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4460                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4461            // If the caller wants all packages and has a restricted profile associated with it,
4462            // then match all users. This is to make sure that launchers that need to access work
4463            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4464            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4465            flags |= PackageManager.MATCH_ANY_USER;
4466        }
4467        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4468            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4469                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4470        }
4471        return updateFlags(flags, userId);
4472    }
4473
4474    /**
4475     * Update given flags when being used to request {@link ApplicationInfo}.
4476     */
4477    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4478        return updateFlagsForPackage(flags, userId, cookie);
4479    }
4480
4481    /**
4482     * Update given flags when being used to request {@link ComponentInfo}.
4483     */
4484    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4485        if (cookie instanceof Intent) {
4486            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4487                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4488            }
4489        }
4490
4491        boolean triaged = true;
4492        // Caller is asking for component details, so they'd better be
4493        // asking for specific encryption matching behavior, or be triaged
4494        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4495                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4496                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4497            triaged = false;
4498        }
4499        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4500            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4501                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4502        }
4503
4504        return updateFlags(flags, userId);
4505    }
4506
4507    /**
4508     * Update given intent when being used to request {@link ResolveInfo}.
4509     */
4510    private Intent updateIntentForResolve(Intent intent) {
4511        if (intent.getSelector() != null) {
4512            intent = intent.getSelector();
4513        }
4514        if (DEBUG_PREFERRED) {
4515            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4516        }
4517        return intent;
4518    }
4519
4520    /**
4521     * Update given flags when being used to request {@link ResolveInfo}.
4522     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4523     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4524     * flag set. However, this flag is only honoured in three circumstances:
4525     * <ul>
4526     * <li>when called from a system process</li>
4527     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4528     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4529     * action and a {@code android.intent.category.BROWSABLE} category</li>
4530     * </ul>
4531     */
4532    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4533        return updateFlagsForResolve(flags, userId, intent, callingUid,
4534                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4535    }
4536    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4537            boolean wantInstantApps) {
4538        return updateFlagsForResolve(flags, userId, intent, callingUid,
4539                wantInstantApps, false /*onlyExposedExplicitly*/);
4540    }
4541    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4542            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4543        // Safe mode means we shouldn't match any third-party components
4544        if (mSafeMode) {
4545            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4546        }
4547        if (getInstantAppPackageName(callingUid) != null) {
4548            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4549            if (onlyExposedExplicitly) {
4550                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4551            }
4552            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4553            flags |= PackageManager.MATCH_INSTANT;
4554        } else {
4555            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4556            final boolean allowMatchInstant =
4557                    (wantInstantApps
4558                            && Intent.ACTION_VIEW.equals(intent.getAction())
4559                            && hasWebURI(intent))
4560                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4561            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4562                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4563            if (!allowMatchInstant) {
4564                flags &= ~PackageManager.MATCH_INSTANT;
4565            }
4566        }
4567        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4568    }
4569
4570    private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state,
4571            int userId) {
4572        ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId);
4573        if (ret != null) {
4574            rebaseEnabledOverlays(ret.applicationInfo, userId);
4575        }
4576        return ret;
4577    }
4578
4579    private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags,
4580            PackageUserState state, int userId) {
4581        ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId);
4582        if (ai != null) {
4583            rebaseEnabledOverlays(ai.applicationInfo, userId);
4584        }
4585        return ai;
4586    }
4587
4588    @Override
4589    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4590        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4591    }
4592
4593    /**
4594     * Important: The provided filterCallingUid is used exclusively to filter out activities
4595     * that can be seen based on user state. It's typically the original caller uid prior
4596     * to clearing. Because it can only be provided by trusted code, it's value can be
4597     * trusted and will be used as-is; unlike userId which will be validated by this method.
4598     */
4599    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4600            int filterCallingUid, int userId) {
4601        if (!sUserManager.exists(userId)) return null;
4602        flags = updateFlagsForComponent(flags, userId, component);
4603        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4604                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4605        synchronized (mPackages) {
4606            PackageParser.Activity a = mActivities.mActivities.get(component);
4607
4608            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4609            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4610                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4611                if (ps == null) return null;
4612                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4613                    return null;
4614                }
4615                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4616            }
4617            if (mResolveComponentName.equals(component)) {
4618                return generateActivityInfo(mResolveActivity, flags, new PackageUserState(),
4619                        userId);
4620            }
4621        }
4622        return null;
4623    }
4624
4625    @Override
4626    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4627            String resolvedType) {
4628        synchronized (mPackages) {
4629            if (component.equals(mResolveComponentName)) {
4630                // The resolver supports EVERYTHING!
4631                return true;
4632            }
4633            final int callingUid = Binder.getCallingUid();
4634            final int callingUserId = UserHandle.getUserId(callingUid);
4635            PackageParser.Activity a = mActivities.mActivities.get(component);
4636            if (a == null) {
4637                return false;
4638            }
4639            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4640            if (ps == null) {
4641                return false;
4642            }
4643            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4644                return false;
4645            }
4646            for (int i=0; i<a.intents.size(); i++) {
4647                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4648                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4649                    return true;
4650                }
4651            }
4652            return false;
4653        }
4654    }
4655
4656    @Override
4657    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4658        if (!sUserManager.exists(userId)) return null;
4659        final int callingUid = Binder.getCallingUid();
4660        flags = updateFlagsForComponent(flags, userId, component);
4661        enforceCrossUserPermission(callingUid, userId,
4662                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4663        synchronized (mPackages) {
4664            PackageParser.Activity a = mReceivers.mActivities.get(component);
4665            if (DEBUG_PACKAGE_INFO) Log.v(
4666                TAG, "getReceiverInfo " + component + ": " + a);
4667            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4668                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4669                if (ps == null) return null;
4670                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4671                    return null;
4672                }
4673                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4674            }
4675        }
4676        return null;
4677    }
4678
4679    @Override
4680    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4681            int flags, int userId) {
4682        if (!sUserManager.exists(userId)) return null;
4683        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4684        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4685            return null;
4686        }
4687
4688        flags = updateFlagsForPackage(flags, userId, null);
4689
4690        final boolean canSeeStaticLibraries =
4691                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4692                        == PERMISSION_GRANTED
4693                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4694                        == PERMISSION_GRANTED
4695                || canRequestPackageInstallsInternal(packageName,
4696                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4697                        false  /* throwIfPermNotDeclared*/)
4698                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4699                        == PERMISSION_GRANTED;
4700
4701        synchronized (mPackages) {
4702            List<SharedLibraryInfo> result = null;
4703
4704            final int libCount = mSharedLibraries.size();
4705            for (int i = 0; i < libCount; i++) {
4706                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4707                if (versionedLib == null) {
4708                    continue;
4709                }
4710
4711                final int versionCount = versionedLib.size();
4712                for (int j = 0; j < versionCount; j++) {
4713                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4714                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4715                        break;
4716                    }
4717                    final long identity = Binder.clearCallingIdentity();
4718                    try {
4719                        PackageInfo packageInfo = getPackageInfoVersioned(
4720                                libInfo.getDeclaringPackage(), flags
4721                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4722                        if (packageInfo == null) {
4723                            continue;
4724                        }
4725                    } finally {
4726                        Binder.restoreCallingIdentity(identity);
4727                    }
4728
4729                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4730                            libInfo.getVersion(), libInfo.getType(),
4731                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4732                            flags, userId));
4733
4734                    if (result == null) {
4735                        result = new ArrayList<>();
4736                    }
4737                    result.add(resLibInfo);
4738                }
4739            }
4740
4741            return result != null ? new ParceledListSlice<>(result) : null;
4742        }
4743    }
4744
4745    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4746            SharedLibraryInfo libInfo, int flags, int userId) {
4747        List<VersionedPackage> versionedPackages = null;
4748        final int packageCount = mSettings.mPackages.size();
4749        for (int i = 0; i < packageCount; i++) {
4750            PackageSetting ps = mSettings.mPackages.valueAt(i);
4751
4752            if (ps == null) {
4753                continue;
4754            }
4755
4756            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4757                continue;
4758            }
4759
4760            final String libName = libInfo.getName();
4761            if (libInfo.isStatic()) {
4762                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4763                if (libIdx < 0) {
4764                    continue;
4765                }
4766                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4767                    continue;
4768                }
4769                if (versionedPackages == null) {
4770                    versionedPackages = new ArrayList<>();
4771                }
4772                // If the dependent is a static shared lib, use the public package name
4773                String dependentPackageName = ps.name;
4774                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4775                    dependentPackageName = ps.pkg.manifestPackageName;
4776                }
4777                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4778            } else if (ps.pkg != null) {
4779                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4780                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4781                    if (versionedPackages == null) {
4782                        versionedPackages = new ArrayList<>();
4783                    }
4784                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4785                }
4786            }
4787        }
4788
4789        return versionedPackages;
4790    }
4791
4792    @Override
4793    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4794        if (!sUserManager.exists(userId)) return null;
4795        final int callingUid = Binder.getCallingUid();
4796        flags = updateFlagsForComponent(flags, userId, component);
4797        enforceCrossUserPermission(callingUid, userId,
4798                false /* requireFullPermission */, false /* checkShell */, "get service info");
4799        synchronized (mPackages) {
4800            PackageParser.Service s = mServices.mServices.get(component);
4801            if (DEBUG_PACKAGE_INFO) Log.v(
4802                TAG, "getServiceInfo " + component + ": " + s);
4803            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4804                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4805                if (ps == null) return null;
4806                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4807                    return null;
4808                }
4809                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4810                        ps.readUserState(userId), userId);
4811                if (si != null) {
4812                    rebaseEnabledOverlays(si.applicationInfo, userId);
4813                }
4814                return si;
4815            }
4816        }
4817        return null;
4818    }
4819
4820    @Override
4821    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4822        if (!sUserManager.exists(userId)) return null;
4823        final int callingUid = Binder.getCallingUid();
4824        flags = updateFlagsForComponent(flags, userId, component);
4825        enforceCrossUserPermission(callingUid, userId,
4826                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4827        synchronized (mPackages) {
4828            PackageParser.Provider p = mProviders.mProviders.get(component);
4829            if (DEBUG_PACKAGE_INFO) Log.v(
4830                TAG, "getProviderInfo " + component + ": " + p);
4831            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4832                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4833                if (ps == null) return null;
4834                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4835                    return null;
4836                }
4837                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4838                        ps.readUserState(userId), userId);
4839                if (pi != null) {
4840                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4841                }
4842                return pi;
4843            }
4844        }
4845        return null;
4846    }
4847
4848    @Override
4849    public String[] getSystemSharedLibraryNames() {
4850        // allow instant applications
4851        synchronized (mPackages) {
4852            Set<String> libs = null;
4853            final int libCount = mSharedLibraries.size();
4854            for (int i = 0; i < libCount; i++) {
4855                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4856                if (versionedLib == null) {
4857                    continue;
4858                }
4859                final int versionCount = versionedLib.size();
4860                for (int j = 0; j < versionCount; j++) {
4861                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4862                    if (!libEntry.info.isStatic()) {
4863                        if (libs == null) {
4864                            libs = new ArraySet<>();
4865                        }
4866                        libs.add(libEntry.info.getName());
4867                        break;
4868                    }
4869                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4870                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4871                            UserHandle.getUserId(Binder.getCallingUid()),
4872                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4873                        if (libs == null) {
4874                            libs = new ArraySet<>();
4875                        }
4876                        libs.add(libEntry.info.getName());
4877                        break;
4878                    }
4879                }
4880            }
4881
4882            if (libs != null) {
4883                String[] libsArray = new String[libs.size()];
4884                libs.toArray(libsArray);
4885                return libsArray;
4886            }
4887
4888            return null;
4889        }
4890    }
4891
4892    @Override
4893    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4894        // allow instant applications
4895        synchronized (mPackages) {
4896            return mServicesSystemSharedLibraryPackageName;
4897        }
4898    }
4899
4900    @Override
4901    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4902        // allow instant applications
4903        synchronized (mPackages) {
4904            return mSharedSystemSharedLibraryPackageName;
4905        }
4906    }
4907
4908    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4909        for (int i = userList.length - 1; i >= 0; --i) {
4910            final int userId = userList[i];
4911            // don't add instant app to the list of updates
4912            if (pkgSetting.getInstantApp(userId)) {
4913                continue;
4914            }
4915            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4916            if (changedPackages == null) {
4917                changedPackages = new SparseArray<>();
4918                mChangedPackages.put(userId, changedPackages);
4919            }
4920            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4921            if (sequenceNumbers == null) {
4922                sequenceNumbers = new HashMap<>();
4923                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4924            }
4925            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4926            if (sequenceNumber != null) {
4927                changedPackages.remove(sequenceNumber);
4928            }
4929            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4930            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4931        }
4932        mChangedPackagesSequenceNumber++;
4933    }
4934
4935    @Override
4936    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4937        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4938            return null;
4939        }
4940        synchronized (mPackages) {
4941            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4942                return null;
4943            }
4944            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4945            if (changedPackages == null) {
4946                return null;
4947            }
4948            final List<String> packageNames =
4949                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4950            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4951                final String packageName = changedPackages.get(i);
4952                if (packageName != null) {
4953                    packageNames.add(packageName);
4954                }
4955            }
4956            return packageNames.isEmpty()
4957                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4958        }
4959    }
4960
4961    @Override
4962    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4963        // allow instant applications
4964        ArrayList<FeatureInfo> res;
4965        synchronized (mAvailableFeatures) {
4966            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4967            res.addAll(mAvailableFeatures.values());
4968        }
4969        final FeatureInfo fi = new FeatureInfo();
4970        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4971                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4972        res.add(fi);
4973
4974        return new ParceledListSlice<>(res);
4975    }
4976
4977    @Override
4978    public boolean hasSystemFeature(String name, int version) {
4979        // allow instant applications
4980        synchronized (mAvailableFeatures) {
4981            final FeatureInfo feat = mAvailableFeatures.get(name);
4982            if (feat == null) {
4983                return false;
4984            } else {
4985                return feat.version >= version;
4986            }
4987        }
4988    }
4989
4990    @Override
4991    public int checkPermission(String permName, String pkgName, int userId) {
4992        if (!sUserManager.exists(userId)) {
4993            return PackageManager.PERMISSION_DENIED;
4994        }
4995        final int callingUid = Binder.getCallingUid();
4996
4997        synchronized (mPackages) {
4998            final PackageParser.Package p = mPackages.get(pkgName);
4999            if (p != null && p.mExtras != null) {
5000                final PackageSetting ps = (PackageSetting) p.mExtras;
5001                if (filterAppAccessLPr(ps, callingUid, userId)) {
5002                    return PackageManager.PERMISSION_DENIED;
5003                }
5004                final boolean instantApp = ps.getInstantApp(userId);
5005                final PermissionsState permissionsState = ps.getPermissionsState();
5006                if (permissionsState.hasPermission(permName, userId)) {
5007                    if (instantApp) {
5008                        BasePermission bp = mSettings.mPermissions.get(permName);
5009                        if (bp != null && bp.isInstant()) {
5010                            return PackageManager.PERMISSION_GRANTED;
5011                        }
5012                    } else {
5013                        return PackageManager.PERMISSION_GRANTED;
5014                    }
5015                }
5016                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5017                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5018                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5019                    return PackageManager.PERMISSION_GRANTED;
5020                }
5021            }
5022        }
5023
5024        return PackageManager.PERMISSION_DENIED;
5025    }
5026
5027    @Override
5028    public int checkUidPermission(String permName, int uid) {
5029        final int callingUid = Binder.getCallingUid();
5030        final int callingUserId = UserHandle.getUserId(callingUid);
5031        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5032        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5033        final int userId = UserHandle.getUserId(uid);
5034        if (!sUserManager.exists(userId)) {
5035            return PackageManager.PERMISSION_DENIED;
5036        }
5037
5038        synchronized (mPackages) {
5039            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5040            if (obj != null) {
5041                if (obj instanceof SharedUserSetting) {
5042                    if (isCallerInstantApp) {
5043                        return PackageManager.PERMISSION_DENIED;
5044                    }
5045                } else if (obj instanceof PackageSetting) {
5046                    final PackageSetting ps = (PackageSetting) obj;
5047                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5048                        return PackageManager.PERMISSION_DENIED;
5049                    }
5050                }
5051                final SettingBase settingBase = (SettingBase) obj;
5052                final PermissionsState permissionsState = settingBase.getPermissionsState();
5053                if (permissionsState.hasPermission(permName, userId)) {
5054                    if (isUidInstantApp) {
5055                        BasePermission bp = mSettings.mPermissions.get(permName);
5056                        if (bp != null && bp.isInstant()) {
5057                            return PackageManager.PERMISSION_GRANTED;
5058                        }
5059                    } else {
5060                        return PackageManager.PERMISSION_GRANTED;
5061                    }
5062                }
5063                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5064                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5065                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5066                    return PackageManager.PERMISSION_GRANTED;
5067                }
5068            } else {
5069                ArraySet<String> perms = mSystemPermissions.get(uid);
5070                if (perms != null) {
5071                    if (perms.contains(permName)) {
5072                        return PackageManager.PERMISSION_GRANTED;
5073                    }
5074                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5075                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5076                        return PackageManager.PERMISSION_GRANTED;
5077                    }
5078                }
5079            }
5080        }
5081
5082        return PackageManager.PERMISSION_DENIED;
5083    }
5084
5085    @Override
5086    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5087        if (UserHandle.getCallingUserId() != userId) {
5088            mContext.enforceCallingPermission(
5089                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5090                    "isPermissionRevokedByPolicy for user " + userId);
5091        }
5092
5093        if (checkPermission(permission, packageName, userId)
5094                == PackageManager.PERMISSION_GRANTED) {
5095            return false;
5096        }
5097
5098        final int callingUid = Binder.getCallingUid();
5099        if (getInstantAppPackageName(callingUid) != null) {
5100            if (!isCallerSameApp(packageName, callingUid)) {
5101                return false;
5102            }
5103        } else {
5104            if (isInstantApp(packageName, userId)) {
5105                return false;
5106            }
5107        }
5108
5109        final long identity = Binder.clearCallingIdentity();
5110        try {
5111            final int flags = getPermissionFlags(permission, packageName, userId);
5112            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5113        } finally {
5114            Binder.restoreCallingIdentity(identity);
5115        }
5116    }
5117
5118    @Override
5119    public String getPermissionControllerPackageName() {
5120        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5121            throw new SecurityException("Instant applications don't have access to this method");
5122        }
5123        synchronized (mPackages) {
5124            return mRequiredInstallerPackage;
5125        }
5126    }
5127
5128    /**
5129     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5130     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5131     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5132     * @param message the message to log on security exception
5133     */
5134    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5135            boolean checkShell, String message) {
5136        if (userId < 0) {
5137            throw new IllegalArgumentException("Invalid userId " + userId);
5138        }
5139        if (checkShell) {
5140            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5141        }
5142        if (userId == UserHandle.getUserId(callingUid)) return;
5143        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5144            if (requireFullPermission) {
5145                mContext.enforceCallingOrSelfPermission(
5146                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5147            } else {
5148                try {
5149                    mContext.enforceCallingOrSelfPermission(
5150                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5151                } catch (SecurityException se) {
5152                    mContext.enforceCallingOrSelfPermission(
5153                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5154                }
5155            }
5156        }
5157    }
5158
5159    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5160        if (callingUid == Process.SHELL_UID) {
5161            if (userHandle >= 0
5162                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5163                throw new SecurityException("Shell does not have permission to access user "
5164                        + userHandle);
5165            } else if (userHandle < 0) {
5166                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5167                        + Debug.getCallers(3));
5168            }
5169        }
5170    }
5171
5172    private BasePermission findPermissionTreeLP(String permName) {
5173        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5174            if (permName.startsWith(bp.name) &&
5175                    permName.length() > bp.name.length() &&
5176                    permName.charAt(bp.name.length()) == '.') {
5177                return bp;
5178            }
5179        }
5180        return null;
5181    }
5182
5183    private BasePermission checkPermissionTreeLP(String permName) {
5184        if (permName != null) {
5185            BasePermission bp = findPermissionTreeLP(permName);
5186            if (bp != null) {
5187                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5188                    return bp;
5189                }
5190                throw new SecurityException("Calling uid "
5191                        + Binder.getCallingUid()
5192                        + " is not allowed to add to permission tree "
5193                        + bp.name + " owned by uid " + bp.uid);
5194            }
5195        }
5196        throw new SecurityException("No permission tree found for " + permName);
5197    }
5198
5199    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5200        if (s1 == null) {
5201            return s2 == null;
5202        }
5203        if (s2 == null) {
5204            return false;
5205        }
5206        if (s1.getClass() != s2.getClass()) {
5207            return false;
5208        }
5209        return s1.equals(s2);
5210    }
5211
5212    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5213        if (pi1.icon != pi2.icon) return false;
5214        if (pi1.logo != pi2.logo) return false;
5215        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5216        if (!compareStrings(pi1.name, pi2.name)) return false;
5217        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5218        // We'll take care of setting this one.
5219        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5220        // These are not currently stored in settings.
5221        //if (!compareStrings(pi1.group, pi2.group)) return false;
5222        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5223        //if (pi1.labelRes != pi2.labelRes) return false;
5224        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5225        return true;
5226    }
5227
5228    int permissionInfoFootprint(PermissionInfo info) {
5229        int size = info.name.length();
5230        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5231        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5232        return size;
5233    }
5234
5235    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5236        int size = 0;
5237        for (BasePermission perm : mSettings.mPermissions.values()) {
5238            if (perm.uid == tree.uid) {
5239                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5240            }
5241        }
5242        return size;
5243    }
5244
5245    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5246        // We calculate the max size of permissions defined by this uid and throw
5247        // if that plus the size of 'info' would exceed our stated maximum.
5248        if (tree.uid != Process.SYSTEM_UID) {
5249            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5250            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5251                throw new SecurityException("Permission tree size cap exceeded");
5252            }
5253        }
5254    }
5255
5256    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5257        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5258            throw new SecurityException("Instant apps can't add permissions");
5259        }
5260        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5261            throw new SecurityException("Label must be specified in permission");
5262        }
5263        BasePermission tree = checkPermissionTreeLP(info.name);
5264        BasePermission bp = mSettings.mPermissions.get(info.name);
5265        boolean added = bp == null;
5266        boolean changed = true;
5267        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5268        if (added) {
5269            enforcePermissionCapLocked(info, tree);
5270            bp = new BasePermission(info.name, tree.sourcePackage,
5271                    BasePermission.TYPE_DYNAMIC);
5272        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5273            throw new SecurityException(
5274                    "Not allowed to modify non-dynamic permission "
5275                    + info.name);
5276        } else {
5277            if (bp.protectionLevel == fixedLevel
5278                    && bp.perm.owner.equals(tree.perm.owner)
5279                    && bp.uid == tree.uid
5280                    && comparePermissionInfos(bp.perm.info, info)) {
5281                changed = false;
5282            }
5283        }
5284        bp.protectionLevel = fixedLevel;
5285        info = new PermissionInfo(info);
5286        info.protectionLevel = fixedLevel;
5287        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5288        bp.perm.info.packageName = tree.perm.info.packageName;
5289        bp.uid = tree.uid;
5290        if (added) {
5291            mSettings.mPermissions.put(info.name, bp);
5292        }
5293        if (changed) {
5294            if (!async) {
5295                mSettings.writeLPr();
5296            } else {
5297                scheduleWriteSettingsLocked();
5298            }
5299        }
5300        return added;
5301    }
5302
5303    @Override
5304    public boolean addPermission(PermissionInfo info) {
5305        synchronized (mPackages) {
5306            return addPermissionLocked(info, false);
5307        }
5308    }
5309
5310    @Override
5311    public boolean addPermissionAsync(PermissionInfo info) {
5312        synchronized (mPackages) {
5313            return addPermissionLocked(info, true);
5314        }
5315    }
5316
5317    @Override
5318    public void removePermission(String name) {
5319        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5320            throw new SecurityException("Instant applications don't have access to this method");
5321        }
5322        synchronized (mPackages) {
5323            checkPermissionTreeLP(name);
5324            BasePermission bp = mSettings.mPermissions.get(name);
5325            if (bp != null) {
5326                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5327                    throw new SecurityException(
5328                            "Not allowed to modify non-dynamic permission "
5329                            + name);
5330                }
5331                mSettings.mPermissions.remove(name);
5332                mSettings.writeLPr();
5333            }
5334        }
5335    }
5336
5337    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5338            PackageParser.Package pkg, BasePermission bp) {
5339        int index = pkg.requestedPermissions.indexOf(bp.name);
5340        if (index == -1) {
5341            throw new SecurityException("Package " + pkg.packageName
5342                    + " has not requested permission " + bp.name);
5343        }
5344        if (!bp.isRuntime() && !bp.isDevelopment()) {
5345            throw new SecurityException("Permission " + bp.name
5346                    + " is not a changeable permission type");
5347        }
5348    }
5349
5350    @Override
5351    public void grantRuntimePermission(String packageName, String name, final int userId) {
5352        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5353    }
5354
5355    private void grantRuntimePermission(String packageName, String name, final int userId,
5356            boolean overridePolicy) {
5357        if (!sUserManager.exists(userId)) {
5358            Log.e(TAG, "No such user:" + userId);
5359            return;
5360        }
5361        final int callingUid = Binder.getCallingUid();
5362
5363        mContext.enforceCallingOrSelfPermission(
5364                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5365                "grantRuntimePermission");
5366
5367        enforceCrossUserPermission(callingUid, userId,
5368                true /* requireFullPermission */, true /* checkShell */,
5369                "grantRuntimePermission");
5370
5371        final int uid;
5372        final PackageSetting ps;
5373
5374        synchronized (mPackages) {
5375            final PackageParser.Package pkg = mPackages.get(packageName);
5376            if (pkg == null) {
5377                throw new IllegalArgumentException("Unknown package: " + packageName);
5378            }
5379            final BasePermission bp = mSettings.mPermissions.get(name);
5380            if (bp == null) {
5381                throw new IllegalArgumentException("Unknown permission: " + name);
5382            }
5383            ps = (PackageSetting) pkg.mExtras;
5384            if (ps == null
5385                    || filterAppAccessLPr(ps, callingUid, userId)) {
5386                throw new IllegalArgumentException("Unknown package: " + packageName);
5387            }
5388
5389            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5390
5391            // If a permission review is required for legacy apps we represent
5392            // their permissions as always granted runtime ones since we need
5393            // to keep the review required permission flag per user while an
5394            // install permission's state is shared across all users.
5395            if (mPermissionReviewRequired
5396                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5397                    && bp.isRuntime()) {
5398                return;
5399            }
5400
5401            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5402
5403            final PermissionsState permissionsState = ps.getPermissionsState();
5404
5405            final int flags = permissionsState.getPermissionFlags(name, userId);
5406            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5407                throw new SecurityException("Cannot grant system fixed permission "
5408                        + name + " for package " + packageName);
5409            }
5410            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5411                throw new SecurityException("Cannot grant policy fixed permission "
5412                        + name + " for package " + packageName);
5413            }
5414
5415            if (bp.isDevelopment()) {
5416                // Development permissions must be handled specially, since they are not
5417                // normal runtime permissions.  For now they apply to all users.
5418                if (permissionsState.grantInstallPermission(bp) !=
5419                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5420                    scheduleWriteSettingsLocked();
5421                }
5422                return;
5423            }
5424
5425            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5426                throw new SecurityException("Cannot grant non-ephemeral permission"
5427                        + name + " for package " + packageName);
5428            }
5429
5430            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5431                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5432                return;
5433            }
5434
5435            final int result = permissionsState.grantRuntimePermission(bp, userId);
5436            switch (result) {
5437                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5438                    return;
5439                }
5440
5441                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5442                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5443                    mHandler.post(new Runnable() {
5444                        @Override
5445                        public void run() {
5446                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5447                        }
5448                    });
5449                }
5450                break;
5451            }
5452
5453            if (bp.isRuntime()) {
5454                logPermissionGranted(mContext, name, packageName);
5455            }
5456
5457            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5458
5459            // Not critical if that is lost - app has to request again.
5460            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5461        }
5462
5463        // Only need to do this if user is initialized. Otherwise it's a new user
5464        // and there are no processes running as the user yet and there's no need
5465        // to make an expensive call to remount processes for the changed permissions.
5466        if (READ_EXTERNAL_STORAGE.equals(name)
5467                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5468            final long token = Binder.clearCallingIdentity();
5469            try {
5470                if (sUserManager.isInitialized(userId)) {
5471                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5472                            StorageManagerInternal.class);
5473                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5474                }
5475            } finally {
5476                Binder.restoreCallingIdentity(token);
5477            }
5478        }
5479    }
5480
5481    @Override
5482    public void revokeRuntimePermission(String packageName, String name, int userId) {
5483        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5484    }
5485
5486    private void revokeRuntimePermission(String packageName, String name, int userId,
5487            boolean overridePolicy) {
5488        if (!sUserManager.exists(userId)) {
5489            Log.e(TAG, "No such user:" + userId);
5490            return;
5491        }
5492
5493        mContext.enforceCallingOrSelfPermission(
5494                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5495                "revokeRuntimePermission");
5496
5497        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5498                true /* requireFullPermission */, true /* checkShell */,
5499                "revokeRuntimePermission");
5500
5501        final int appId;
5502
5503        synchronized (mPackages) {
5504            final PackageParser.Package pkg = mPackages.get(packageName);
5505            if (pkg == null) {
5506                throw new IllegalArgumentException("Unknown package: " + packageName);
5507            }
5508            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5509            if (ps == null
5510                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5511                throw new IllegalArgumentException("Unknown package: " + packageName);
5512            }
5513            final BasePermission bp = mSettings.mPermissions.get(name);
5514            if (bp == null) {
5515                throw new IllegalArgumentException("Unknown permission: " + name);
5516            }
5517
5518            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5519
5520            // If a permission review is required for legacy apps we represent
5521            // their permissions as always granted runtime ones since we need
5522            // to keep the review required permission flag per user while an
5523            // install permission's state is shared across all users.
5524            if (mPermissionReviewRequired
5525                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5526                    && bp.isRuntime()) {
5527                return;
5528            }
5529
5530            final PermissionsState permissionsState = ps.getPermissionsState();
5531
5532            final int flags = permissionsState.getPermissionFlags(name, userId);
5533            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5534                throw new SecurityException("Cannot revoke system fixed permission "
5535                        + name + " for package " + packageName);
5536            }
5537            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5538                throw new SecurityException("Cannot revoke policy fixed permission "
5539                        + name + " for package " + packageName);
5540            }
5541
5542            if (bp.isDevelopment()) {
5543                // Development permissions must be handled specially, since they are not
5544                // normal runtime permissions.  For now they apply to all users.
5545                if (permissionsState.revokeInstallPermission(bp) !=
5546                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5547                    scheduleWriteSettingsLocked();
5548                }
5549                return;
5550            }
5551
5552            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5553                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5554                return;
5555            }
5556
5557            if (bp.isRuntime()) {
5558                logPermissionRevoked(mContext, name, packageName);
5559            }
5560
5561            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5562
5563            // Critical, after this call app should never have the permission.
5564            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5565
5566            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5567        }
5568
5569        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5570    }
5571
5572    /**
5573     * Get the first event id for the permission.
5574     *
5575     * <p>There are four events for each permission: <ul>
5576     *     <li>Request permission: first id + 0</li>
5577     *     <li>Grant permission: first id + 1</li>
5578     *     <li>Request for permission denied: first id + 2</li>
5579     *     <li>Revoke permission: first id + 3</li>
5580     * </ul></p>
5581     *
5582     * @param name name of the permission
5583     *
5584     * @return The first event id for the permission
5585     */
5586    private static int getBaseEventId(@NonNull String name) {
5587        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5588
5589        if (eventIdIndex == -1) {
5590            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5591                    || "user".equals(Build.TYPE)) {
5592                Log.i(TAG, "Unknown permission " + name);
5593
5594                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5595            } else {
5596                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5597                //
5598                // Also update
5599                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5600                // - metrics_constants.proto
5601                throw new IllegalStateException("Unknown permission " + name);
5602            }
5603        }
5604
5605        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5606    }
5607
5608    /**
5609     * Log that a permission was revoked.
5610     *
5611     * @param context Context of the caller
5612     * @param name name of the permission
5613     * @param packageName package permission if for
5614     */
5615    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5616            @NonNull String packageName) {
5617        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5618    }
5619
5620    /**
5621     * Log that a permission request was granted.
5622     *
5623     * @param context Context of the caller
5624     * @param name name of the permission
5625     * @param packageName package permission if for
5626     */
5627    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5628            @NonNull String packageName) {
5629        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5630    }
5631
5632    @Override
5633    public void resetRuntimePermissions() {
5634        mContext.enforceCallingOrSelfPermission(
5635                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5636                "revokeRuntimePermission");
5637
5638        int callingUid = Binder.getCallingUid();
5639        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5640            mContext.enforceCallingOrSelfPermission(
5641                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5642                    "resetRuntimePermissions");
5643        }
5644
5645        synchronized (mPackages) {
5646            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5647            for (int userId : UserManagerService.getInstance().getUserIds()) {
5648                final int packageCount = mPackages.size();
5649                for (int i = 0; i < packageCount; i++) {
5650                    PackageParser.Package pkg = mPackages.valueAt(i);
5651                    if (!(pkg.mExtras instanceof PackageSetting)) {
5652                        continue;
5653                    }
5654                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5655                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5656                }
5657            }
5658        }
5659    }
5660
5661    @Override
5662    public int getPermissionFlags(String name, String packageName, int userId) {
5663        if (!sUserManager.exists(userId)) {
5664            return 0;
5665        }
5666
5667        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5668
5669        final int callingUid = Binder.getCallingUid();
5670        enforceCrossUserPermission(callingUid, userId,
5671                true /* requireFullPermission */, false /* checkShell */,
5672                "getPermissionFlags");
5673
5674        synchronized (mPackages) {
5675            final PackageParser.Package pkg = mPackages.get(packageName);
5676            if (pkg == null) {
5677                return 0;
5678            }
5679            final BasePermission bp = mSettings.mPermissions.get(name);
5680            if (bp == null) {
5681                return 0;
5682            }
5683            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5684            if (ps == null
5685                    || filterAppAccessLPr(ps, callingUid, userId)) {
5686                return 0;
5687            }
5688            PermissionsState permissionsState = ps.getPermissionsState();
5689            return permissionsState.getPermissionFlags(name, userId);
5690        }
5691    }
5692
5693    @Override
5694    public void updatePermissionFlags(String name, String packageName, int flagMask,
5695            int flagValues, int userId) {
5696        if (!sUserManager.exists(userId)) {
5697            return;
5698        }
5699
5700        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5701
5702        final int callingUid = Binder.getCallingUid();
5703        enforceCrossUserPermission(callingUid, userId,
5704                true /* requireFullPermission */, true /* checkShell */,
5705                "updatePermissionFlags");
5706
5707        // Only the system can change these flags and nothing else.
5708        if (getCallingUid() != Process.SYSTEM_UID) {
5709            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5710            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5711            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5712            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5713            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5714        }
5715
5716        synchronized (mPackages) {
5717            final PackageParser.Package pkg = mPackages.get(packageName);
5718            if (pkg == null) {
5719                throw new IllegalArgumentException("Unknown package: " + packageName);
5720            }
5721            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5722            if (ps == null
5723                    || filterAppAccessLPr(ps, callingUid, userId)) {
5724                throw new IllegalArgumentException("Unknown package: " + packageName);
5725            }
5726
5727            final BasePermission bp = mSettings.mPermissions.get(name);
5728            if (bp == null) {
5729                throw new IllegalArgumentException("Unknown permission: " + name);
5730            }
5731
5732            PermissionsState permissionsState = ps.getPermissionsState();
5733
5734            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5735
5736            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5737                // Install and runtime permissions are stored in different places,
5738                // so figure out what permission changed and persist the change.
5739                if (permissionsState.getInstallPermissionState(name) != null) {
5740                    scheduleWriteSettingsLocked();
5741                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5742                        || hadState) {
5743                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5744                }
5745            }
5746        }
5747    }
5748
5749    /**
5750     * Update the permission flags for all packages and runtime permissions of a user in order
5751     * to allow device or profile owner to remove POLICY_FIXED.
5752     */
5753    @Override
5754    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5755        if (!sUserManager.exists(userId)) {
5756            return;
5757        }
5758
5759        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5760
5761        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5762                true /* requireFullPermission */, true /* checkShell */,
5763                "updatePermissionFlagsForAllApps");
5764
5765        // Only the system can change system fixed flags.
5766        if (getCallingUid() != Process.SYSTEM_UID) {
5767            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5768            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5769        }
5770
5771        synchronized (mPackages) {
5772            boolean changed = false;
5773            final int packageCount = mPackages.size();
5774            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5775                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5776                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5777                if (ps == null) {
5778                    continue;
5779                }
5780                PermissionsState permissionsState = ps.getPermissionsState();
5781                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5782                        userId, flagMask, flagValues);
5783            }
5784            if (changed) {
5785                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5786            }
5787        }
5788    }
5789
5790    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5791        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5792                != PackageManager.PERMISSION_GRANTED
5793            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5794                != PackageManager.PERMISSION_GRANTED) {
5795            throw new SecurityException(message + " requires "
5796                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5797                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5798        }
5799    }
5800
5801    @Override
5802    public boolean shouldShowRequestPermissionRationale(String permissionName,
5803            String packageName, int userId) {
5804        if (UserHandle.getCallingUserId() != userId) {
5805            mContext.enforceCallingPermission(
5806                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5807                    "canShowRequestPermissionRationale for user " + userId);
5808        }
5809
5810        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5811        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5812            return false;
5813        }
5814
5815        if (checkPermission(permissionName, packageName, userId)
5816                == PackageManager.PERMISSION_GRANTED) {
5817            return false;
5818        }
5819
5820        final int flags;
5821
5822        final long identity = Binder.clearCallingIdentity();
5823        try {
5824            flags = getPermissionFlags(permissionName,
5825                    packageName, userId);
5826        } finally {
5827            Binder.restoreCallingIdentity(identity);
5828        }
5829
5830        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5831                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5832                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5833
5834        if ((flags & fixedFlags) != 0) {
5835            return false;
5836        }
5837
5838        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5839    }
5840
5841    @Override
5842    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5843        mContext.enforceCallingOrSelfPermission(
5844                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5845                "addOnPermissionsChangeListener");
5846
5847        synchronized (mPackages) {
5848            mOnPermissionChangeListeners.addListenerLocked(listener);
5849        }
5850    }
5851
5852    @Override
5853    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5854        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5855            throw new SecurityException("Instant applications don't have access to this method");
5856        }
5857        synchronized (mPackages) {
5858            mOnPermissionChangeListeners.removeListenerLocked(listener);
5859        }
5860    }
5861
5862    @Override
5863    public boolean isProtectedBroadcast(String actionName) {
5864        // allow instant applications
5865        synchronized (mPackages) {
5866            if (mProtectedBroadcasts.contains(actionName)) {
5867                return true;
5868            } else if (actionName != null) {
5869                // TODO: remove these terrible hacks
5870                if (actionName.startsWith("android.net.netmon.lingerExpired")
5871                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5872                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5873                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5874                    return true;
5875                }
5876            }
5877        }
5878        return false;
5879    }
5880
5881    @Override
5882    public int checkSignatures(String pkg1, String pkg2) {
5883        synchronized (mPackages) {
5884            final PackageParser.Package p1 = mPackages.get(pkg1);
5885            final PackageParser.Package p2 = mPackages.get(pkg2);
5886            if (p1 == null || p1.mExtras == null
5887                    || p2 == null || p2.mExtras == null) {
5888                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5889            }
5890            final int callingUid = Binder.getCallingUid();
5891            final int callingUserId = UserHandle.getUserId(callingUid);
5892            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5893            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5894            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5895                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5896                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5897            }
5898            return compareSignatures(p1.mSignatures, p2.mSignatures);
5899        }
5900    }
5901
5902    @Override
5903    public int checkUidSignatures(int uid1, int uid2) {
5904        final int callingUid = Binder.getCallingUid();
5905        final int callingUserId = UserHandle.getUserId(callingUid);
5906        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5907        // Map to base uids.
5908        uid1 = UserHandle.getAppId(uid1);
5909        uid2 = UserHandle.getAppId(uid2);
5910        // reader
5911        synchronized (mPackages) {
5912            Signature[] s1;
5913            Signature[] s2;
5914            Object obj = mSettings.getUserIdLPr(uid1);
5915            if (obj != null) {
5916                if (obj instanceof SharedUserSetting) {
5917                    if (isCallerInstantApp) {
5918                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5919                    }
5920                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5921                } else if (obj instanceof PackageSetting) {
5922                    final PackageSetting ps = (PackageSetting) obj;
5923                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5924                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5925                    }
5926                    s1 = ps.signatures.mSignatures;
5927                } else {
5928                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5929                }
5930            } else {
5931                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5932            }
5933            obj = mSettings.getUserIdLPr(uid2);
5934            if (obj != null) {
5935                if (obj instanceof SharedUserSetting) {
5936                    if (isCallerInstantApp) {
5937                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5938                    }
5939                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5940                } else if (obj instanceof PackageSetting) {
5941                    final PackageSetting ps = (PackageSetting) obj;
5942                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5943                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5944                    }
5945                    s2 = ps.signatures.mSignatures;
5946                } else {
5947                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5948                }
5949            } else {
5950                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5951            }
5952            return compareSignatures(s1, s2);
5953        }
5954    }
5955
5956    /**
5957     * This method should typically only be used when granting or revoking
5958     * permissions, since the app may immediately restart after this call.
5959     * <p>
5960     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5961     * guard your work against the app being relaunched.
5962     */
5963    private void killUid(int appId, int userId, String reason) {
5964        final long identity = Binder.clearCallingIdentity();
5965        try {
5966            IActivityManager am = ActivityManager.getService();
5967            if (am != null) {
5968                try {
5969                    am.killUid(appId, userId, reason);
5970                } catch (RemoteException e) {
5971                    /* ignore - same process */
5972                }
5973            }
5974        } finally {
5975            Binder.restoreCallingIdentity(identity);
5976        }
5977    }
5978
5979    /**
5980     * Compares two sets of signatures. Returns:
5981     * <br />
5982     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5983     * <br />
5984     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5985     * <br />
5986     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5987     * <br />
5988     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5989     * <br />
5990     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5991     */
5992    static int compareSignatures(Signature[] s1, Signature[] s2) {
5993        if (s1 == null) {
5994            return s2 == null
5995                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5996                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5997        }
5998
5999        if (s2 == null) {
6000            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6001        }
6002
6003        if (s1.length != s2.length) {
6004            return PackageManager.SIGNATURE_NO_MATCH;
6005        }
6006
6007        // Since both signature sets are of size 1, we can compare without HashSets.
6008        if (s1.length == 1) {
6009            return s1[0].equals(s2[0]) ?
6010                    PackageManager.SIGNATURE_MATCH :
6011                    PackageManager.SIGNATURE_NO_MATCH;
6012        }
6013
6014        ArraySet<Signature> set1 = new ArraySet<Signature>();
6015        for (Signature sig : s1) {
6016            set1.add(sig);
6017        }
6018        ArraySet<Signature> set2 = new ArraySet<Signature>();
6019        for (Signature sig : s2) {
6020            set2.add(sig);
6021        }
6022        // Make sure s2 contains all signatures in s1.
6023        if (set1.equals(set2)) {
6024            return PackageManager.SIGNATURE_MATCH;
6025        }
6026        return PackageManager.SIGNATURE_NO_MATCH;
6027    }
6028
6029    /**
6030     * If the database version for this type of package (internal storage or
6031     * external storage) is less than the version where package signatures
6032     * were updated, return true.
6033     */
6034    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6035        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6036        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6037    }
6038
6039    /**
6040     * Used for backward compatibility to make sure any packages with
6041     * certificate chains get upgraded to the new style. {@code existingSigs}
6042     * will be in the old format (since they were stored on disk from before the
6043     * system upgrade) and {@code scannedSigs} will be in the newer format.
6044     */
6045    private int compareSignaturesCompat(PackageSignatures existingSigs,
6046            PackageParser.Package scannedPkg) {
6047        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6048            return PackageManager.SIGNATURE_NO_MATCH;
6049        }
6050
6051        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6052        for (Signature sig : existingSigs.mSignatures) {
6053            existingSet.add(sig);
6054        }
6055        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6056        for (Signature sig : scannedPkg.mSignatures) {
6057            try {
6058                Signature[] chainSignatures = sig.getChainSignatures();
6059                for (Signature chainSig : chainSignatures) {
6060                    scannedCompatSet.add(chainSig);
6061                }
6062            } catch (CertificateEncodingException e) {
6063                scannedCompatSet.add(sig);
6064            }
6065        }
6066        /*
6067         * Make sure the expanded scanned set contains all signatures in the
6068         * existing one.
6069         */
6070        if (scannedCompatSet.equals(existingSet)) {
6071            // Migrate the old signatures to the new scheme.
6072            existingSigs.assignSignatures(scannedPkg.mSignatures);
6073            // The new KeySets will be re-added later in the scanning process.
6074            synchronized (mPackages) {
6075                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6076            }
6077            return PackageManager.SIGNATURE_MATCH;
6078        }
6079        return PackageManager.SIGNATURE_NO_MATCH;
6080    }
6081
6082    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6083        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6084        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6085    }
6086
6087    private int compareSignaturesRecover(PackageSignatures existingSigs,
6088            PackageParser.Package scannedPkg) {
6089        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6090            return PackageManager.SIGNATURE_NO_MATCH;
6091        }
6092
6093        String msg = null;
6094        try {
6095            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6096                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6097                        + scannedPkg.packageName);
6098                return PackageManager.SIGNATURE_MATCH;
6099            }
6100        } catch (CertificateException e) {
6101            msg = e.getMessage();
6102        }
6103
6104        logCriticalInfo(Log.INFO,
6105                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6106        return PackageManager.SIGNATURE_NO_MATCH;
6107    }
6108
6109    @Override
6110    public List<String> getAllPackages() {
6111        final int callingUid = Binder.getCallingUid();
6112        final int callingUserId = UserHandle.getUserId(callingUid);
6113        synchronized (mPackages) {
6114            if (canViewInstantApps(callingUid, callingUserId)) {
6115                return new ArrayList<String>(mPackages.keySet());
6116            }
6117            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6118            final List<String> result = new ArrayList<>();
6119            if (instantAppPkgName != null) {
6120                // caller is an instant application; filter unexposed applications
6121                for (PackageParser.Package pkg : mPackages.values()) {
6122                    if (!pkg.visibleToInstantApps) {
6123                        continue;
6124                    }
6125                    result.add(pkg.packageName);
6126                }
6127            } else {
6128                // caller is a normal application; filter instant applications
6129                for (PackageParser.Package pkg : mPackages.values()) {
6130                    final PackageSetting ps =
6131                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6132                    if (ps != null
6133                            && ps.getInstantApp(callingUserId)
6134                            && !mInstantAppRegistry.isInstantAccessGranted(
6135                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6136                        continue;
6137                    }
6138                    result.add(pkg.packageName);
6139                }
6140            }
6141            return result;
6142        }
6143    }
6144
6145    @Override
6146    public String[] getPackagesForUid(int uid) {
6147        final int callingUid = Binder.getCallingUid();
6148        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6149        final int userId = UserHandle.getUserId(uid);
6150        uid = UserHandle.getAppId(uid);
6151        // reader
6152        synchronized (mPackages) {
6153            Object obj = mSettings.getUserIdLPr(uid);
6154            if (obj instanceof SharedUserSetting) {
6155                if (isCallerInstantApp) {
6156                    return null;
6157                }
6158                final SharedUserSetting sus = (SharedUserSetting) obj;
6159                final int N = sus.packages.size();
6160                String[] res = new String[N];
6161                final Iterator<PackageSetting> it = sus.packages.iterator();
6162                int i = 0;
6163                while (it.hasNext()) {
6164                    PackageSetting ps = it.next();
6165                    if (ps.getInstalled(userId)) {
6166                        res[i++] = ps.name;
6167                    } else {
6168                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6169                    }
6170                }
6171                return res;
6172            } else if (obj instanceof PackageSetting) {
6173                final PackageSetting ps = (PackageSetting) obj;
6174                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6175                    return new String[]{ps.name};
6176                }
6177            }
6178        }
6179        return null;
6180    }
6181
6182    @Override
6183    public String getNameForUid(int uid) {
6184        final int callingUid = Binder.getCallingUid();
6185        if (getInstantAppPackageName(callingUid) != null) {
6186            return null;
6187        }
6188        synchronized (mPackages) {
6189            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6190            if (obj instanceof SharedUserSetting) {
6191                final SharedUserSetting sus = (SharedUserSetting) obj;
6192                return sus.name + ":" + sus.userId;
6193            } else if (obj instanceof PackageSetting) {
6194                final PackageSetting ps = (PackageSetting) obj;
6195                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6196                    return null;
6197                }
6198                return ps.name;
6199            }
6200        }
6201        return null;
6202    }
6203
6204    @Override
6205    public int getUidForSharedUser(String sharedUserName) {
6206        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6207            return -1;
6208        }
6209        if (sharedUserName == null) {
6210            return -1;
6211        }
6212        // reader
6213        synchronized (mPackages) {
6214            SharedUserSetting suid;
6215            try {
6216                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6217                if (suid != null) {
6218                    return suid.userId;
6219                }
6220            } catch (PackageManagerException ignore) {
6221                // can't happen, but, still need to catch it
6222            }
6223            return -1;
6224        }
6225    }
6226
6227    @Override
6228    public int getFlagsForUid(int uid) {
6229        final int callingUid = Binder.getCallingUid();
6230        if (getInstantAppPackageName(callingUid) != null) {
6231            return 0;
6232        }
6233        synchronized (mPackages) {
6234            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6235            if (obj instanceof SharedUserSetting) {
6236                final SharedUserSetting sus = (SharedUserSetting) obj;
6237                return sus.pkgFlags;
6238            } else if (obj instanceof PackageSetting) {
6239                final PackageSetting ps = (PackageSetting) obj;
6240                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6241                    return 0;
6242                }
6243                return ps.pkgFlags;
6244            }
6245        }
6246        return 0;
6247    }
6248
6249    @Override
6250    public int getPrivateFlagsForUid(int uid) {
6251        final int callingUid = Binder.getCallingUid();
6252        if (getInstantAppPackageName(callingUid) != null) {
6253            return 0;
6254        }
6255        synchronized (mPackages) {
6256            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6257            if (obj instanceof SharedUserSetting) {
6258                final SharedUserSetting sus = (SharedUserSetting) obj;
6259                return sus.pkgPrivateFlags;
6260            } else if (obj instanceof PackageSetting) {
6261                final PackageSetting ps = (PackageSetting) obj;
6262                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6263                    return 0;
6264                }
6265                return ps.pkgPrivateFlags;
6266            }
6267        }
6268        return 0;
6269    }
6270
6271    @Override
6272    public boolean isUidPrivileged(int uid) {
6273        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6274            return false;
6275        }
6276        uid = UserHandle.getAppId(uid);
6277        // reader
6278        synchronized (mPackages) {
6279            Object obj = mSettings.getUserIdLPr(uid);
6280            if (obj instanceof SharedUserSetting) {
6281                final SharedUserSetting sus = (SharedUserSetting) obj;
6282                final Iterator<PackageSetting> it = sus.packages.iterator();
6283                while (it.hasNext()) {
6284                    if (it.next().isPrivileged()) {
6285                        return true;
6286                    }
6287                }
6288            } else if (obj instanceof PackageSetting) {
6289                final PackageSetting ps = (PackageSetting) obj;
6290                return ps.isPrivileged();
6291            }
6292        }
6293        return false;
6294    }
6295
6296    @Override
6297    public String[] getAppOpPermissionPackages(String permissionName) {
6298        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6299            return null;
6300        }
6301        synchronized (mPackages) {
6302            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6303            if (pkgs == null) {
6304                return null;
6305            }
6306            return pkgs.toArray(new String[pkgs.size()]);
6307        }
6308    }
6309
6310    @Override
6311    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6312            int flags, int userId) {
6313        return resolveIntentInternal(
6314                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6315    }
6316
6317    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6318            int flags, int userId, boolean resolveForStart) {
6319        try {
6320            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6321
6322            if (!sUserManager.exists(userId)) return null;
6323            final int callingUid = Binder.getCallingUid();
6324            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6325            enforceCrossUserPermission(callingUid, userId,
6326                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6327
6328            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6329            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6330                    flags, callingUid, userId, resolveForStart);
6331            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6332
6333            final ResolveInfo bestChoice =
6334                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6335            return bestChoice;
6336        } finally {
6337            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6338        }
6339    }
6340
6341    @Override
6342    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6343        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6344            throw new SecurityException(
6345                    "findPersistentPreferredActivity can only be run by the system");
6346        }
6347        if (!sUserManager.exists(userId)) {
6348            return null;
6349        }
6350        final int callingUid = Binder.getCallingUid();
6351        intent = updateIntentForResolve(intent);
6352        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6353        final int flags = updateFlagsForResolve(
6354                0, userId, intent, callingUid, false /*includeInstantApps*/);
6355        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6356                userId);
6357        synchronized (mPackages) {
6358            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6359                    userId);
6360        }
6361    }
6362
6363    @Override
6364    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6365            IntentFilter filter, int match, ComponentName activity) {
6366        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6367            return;
6368        }
6369        final int userId = UserHandle.getCallingUserId();
6370        if (DEBUG_PREFERRED) {
6371            Log.v(TAG, "setLastChosenActivity intent=" + intent
6372                + " resolvedType=" + resolvedType
6373                + " flags=" + flags
6374                + " filter=" + filter
6375                + " match=" + match
6376                + " activity=" + activity);
6377            filter.dump(new PrintStreamPrinter(System.out), "    ");
6378        }
6379        intent.setComponent(null);
6380        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6381                userId);
6382        // Find any earlier preferred or last chosen entries and nuke them
6383        findPreferredActivity(intent, resolvedType,
6384                flags, query, 0, false, true, false, userId);
6385        // Add the new activity as the last chosen for this filter
6386        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6387                "Setting last chosen");
6388    }
6389
6390    @Override
6391    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6392        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6393            return null;
6394        }
6395        final int userId = UserHandle.getCallingUserId();
6396        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6397        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6398                userId);
6399        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6400                false, false, false, userId);
6401    }
6402
6403    /**
6404     * Returns whether or not instant apps have been disabled remotely.
6405     */
6406    private boolean isEphemeralDisabled() {
6407        return mEphemeralAppsDisabled;
6408    }
6409
6410    private boolean isInstantAppAllowed(
6411            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6412            boolean skipPackageCheck) {
6413        if (mInstantAppResolverConnection == null) {
6414            return false;
6415        }
6416        if (mInstantAppInstallerActivity == null) {
6417            return false;
6418        }
6419        if (intent.getComponent() != null) {
6420            return false;
6421        }
6422        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6423            return false;
6424        }
6425        if (!skipPackageCheck && intent.getPackage() != null) {
6426            return false;
6427        }
6428        final boolean isWebUri = hasWebURI(intent);
6429        if (!isWebUri || intent.getData().getHost() == null) {
6430            return false;
6431        }
6432        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6433        // Or if there's already an ephemeral app installed that handles the action
6434        synchronized (mPackages) {
6435            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6436            for (int n = 0; n < count; n++) {
6437                final ResolveInfo info = resolvedActivities.get(n);
6438                final String packageName = info.activityInfo.packageName;
6439                final PackageSetting ps = mSettings.mPackages.get(packageName);
6440                if (ps != null) {
6441                    // only check domain verification status if the app is not a browser
6442                    if (!info.handleAllWebDataURI) {
6443                        // Try to get the status from User settings first
6444                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6445                        final int status = (int) (packedStatus >> 32);
6446                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6447                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6448                            if (DEBUG_EPHEMERAL) {
6449                                Slog.v(TAG, "DENY instant app;"
6450                                    + " pkg: " + packageName + ", status: " + status);
6451                            }
6452                            return false;
6453                        }
6454                    }
6455                    if (ps.getInstantApp(userId)) {
6456                        if (DEBUG_EPHEMERAL) {
6457                            Slog.v(TAG, "DENY instant app installed;"
6458                                    + " pkg: " + packageName);
6459                        }
6460                        return false;
6461                    }
6462                }
6463            }
6464        }
6465        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6466        return true;
6467    }
6468
6469    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6470            Intent origIntent, String resolvedType, String callingPackage,
6471            Bundle verificationBundle, int userId) {
6472        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6473                new InstantAppRequest(responseObj, origIntent, resolvedType,
6474                        callingPackage, userId, verificationBundle));
6475        mHandler.sendMessage(msg);
6476    }
6477
6478    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6479            int flags, List<ResolveInfo> query, int userId) {
6480        if (query != null) {
6481            final int N = query.size();
6482            if (N == 1) {
6483                return query.get(0);
6484            } else if (N > 1) {
6485                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6486                // If there is more than one activity with the same priority,
6487                // then let the user decide between them.
6488                ResolveInfo r0 = query.get(0);
6489                ResolveInfo r1 = query.get(1);
6490                if (DEBUG_INTENT_MATCHING || debug) {
6491                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6492                            + r1.activityInfo.name + "=" + r1.priority);
6493                }
6494                // If the first activity has a higher priority, or a different
6495                // default, then it is always desirable to pick it.
6496                if (r0.priority != r1.priority
6497                        || r0.preferredOrder != r1.preferredOrder
6498                        || r0.isDefault != r1.isDefault) {
6499                    return query.get(0);
6500                }
6501                // If we have saved a preference for a preferred activity for
6502                // this Intent, use that.
6503                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6504                        flags, query, r0.priority, true, false, debug, userId);
6505                if (ri != null) {
6506                    return ri;
6507                }
6508                // If we have an ephemeral app, use it
6509                for (int i = 0; i < N; i++) {
6510                    ri = query.get(i);
6511                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6512                        final String packageName = ri.activityInfo.packageName;
6513                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6514                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6515                        final int status = (int)(packedStatus >> 32);
6516                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6517                            return ri;
6518                        }
6519                    }
6520                }
6521                ri = new ResolveInfo(mResolveInfo);
6522                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6523                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6524                // If all of the options come from the same package, show the application's
6525                // label and icon instead of the generic resolver's.
6526                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6527                // and then throw away the ResolveInfo itself, meaning that the caller loses
6528                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6529                // a fallback for this case; we only set the target package's resources on
6530                // the ResolveInfo, not the ActivityInfo.
6531                final String intentPackage = intent.getPackage();
6532                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6533                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6534                    ri.resolvePackageName = intentPackage;
6535                    if (userNeedsBadging(userId)) {
6536                        ri.noResourceId = true;
6537                    } else {
6538                        ri.icon = appi.icon;
6539                    }
6540                    ri.iconResourceId = appi.icon;
6541                    ri.labelRes = appi.labelRes;
6542                }
6543                ri.activityInfo.applicationInfo = new ApplicationInfo(
6544                        ri.activityInfo.applicationInfo);
6545                if (userId != 0) {
6546                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6547                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6548                }
6549                // Make sure that the resolver is displayable in car mode
6550                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6551                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6552                return ri;
6553            }
6554        }
6555        return null;
6556    }
6557
6558    /**
6559     * Return true if the given list is not empty and all of its contents have
6560     * an activityInfo with the given package name.
6561     */
6562    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6563        if (ArrayUtils.isEmpty(list)) {
6564            return false;
6565        }
6566        for (int i = 0, N = list.size(); i < N; i++) {
6567            final ResolveInfo ri = list.get(i);
6568            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6569            if (ai == null || !packageName.equals(ai.packageName)) {
6570                return false;
6571            }
6572        }
6573        return true;
6574    }
6575
6576    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6577            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6578        final int N = query.size();
6579        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6580                .get(userId);
6581        // Get the list of persistent preferred activities that handle the intent
6582        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6583        List<PersistentPreferredActivity> pprefs = ppir != null
6584                ? ppir.queryIntent(intent, resolvedType,
6585                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6586                        userId)
6587                : null;
6588        if (pprefs != null && pprefs.size() > 0) {
6589            final int M = pprefs.size();
6590            for (int i=0; i<M; i++) {
6591                final PersistentPreferredActivity ppa = pprefs.get(i);
6592                if (DEBUG_PREFERRED || debug) {
6593                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6594                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6595                            + "\n  component=" + ppa.mComponent);
6596                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6597                }
6598                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6599                        flags | MATCH_DISABLED_COMPONENTS, userId);
6600                if (DEBUG_PREFERRED || debug) {
6601                    Slog.v(TAG, "Found persistent preferred activity:");
6602                    if (ai != null) {
6603                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6604                    } else {
6605                        Slog.v(TAG, "  null");
6606                    }
6607                }
6608                if (ai == null) {
6609                    // This previously registered persistent preferred activity
6610                    // component is no longer known. Ignore it and do NOT remove it.
6611                    continue;
6612                }
6613                for (int j=0; j<N; j++) {
6614                    final ResolveInfo ri = query.get(j);
6615                    if (!ri.activityInfo.applicationInfo.packageName
6616                            .equals(ai.applicationInfo.packageName)) {
6617                        continue;
6618                    }
6619                    if (!ri.activityInfo.name.equals(ai.name)) {
6620                        continue;
6621                    }
6622                    //  Found a persistent preference that can handle the intent.
6623                    if (DEBUG_PREFERRED || debug) {
6624                        Slog.v(TAG, "Returning persistent preferred activity: " +
6625                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6626                    }
6627                    return ri;
6628                }
6629            }
6630        }
6631        return null;
6632    }
6633
6634    // TODO: handle preferred activities missing while user has amnesia
6635    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6636            List<ResolveInfo> query, int priority, boolean always,
6637            boolean removeMatches, boolean debug, int userId) {
6638        if (!sUserManager.exists(userId)) return null;
6639        final int callingUid = Binder.getCallingUid();
6640        flags = updateFlagsForResolve(
6641                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6642        intent = updateIntentForResolve(intent);
6643        // writer
6644        synchronized (mPackages) {
6645            // Try to find a matching persistent preferred activity.
6646            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6647                    debug, userId);
6648
6649            // If a persistent preferred activity matched, use it.
6650            if (pri != null) {
6651                return pri;
6652            }
6653
6654            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6655            // Get the list of preferred activities that handle the intent
6656            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6657            List<PreferredActivity> prefs = pir != null
6658                    ? pir.queryIntent(intent, resolvedType,
6659                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6660                            userId)
6661                    : null;
6662            if (prefs != null && prefs.size() > 0) {
6663                boolean changed = false;
6664                try {
6665                    // First figure out how good the original match set is.
6666                    // We will only allow preferred activities that came
6667                    // from the same match quality.
6668                    int match = 0;
6669
6670                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6671
6672                    final int N = query.size();
6673                    for (int j=0; j<N; j++) {
6674                        final ResolveInfo ri = query.get(j);
6675                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6676                                + ": 0x" + Integer.toHexString(match));
6677                        if (ri.match > match) {
6678                            match = ri.match;
6679                        }
6680                    }
6681
6682                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6683                            + Integer.toHexString(match));
6684
6685                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6686                    final int M = prefs.size();
6687                    for (int i=0; i<M; i++) {
6688                        final PreferredActivity pa = prefs.get(i);
6689                        if (DEBUG_PREFERRED || debug) {
6690                            Slog.v(TAG, "Checking PreferredActivity ds="
6691                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6692                                    + "\n  component=" + pa.mPref.mComponent);
6693                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6694                        }
6695                        if (pa.mPref.mMatch != match) {
6696                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6697                                    + Integer.toHexString(pa.mPref.mMatch));
6698                            continue;
6699                        }
6700                        // If it's not an "always" type preferred activity and that's what we're
6701                        // looking for, skip it.
6702                        if (always && !pa.mPref.mAlways) {
6703                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6704                            continue;
6705                        }
6706                        final ActivityInfo ai = getActivityInfo(
6707                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6708                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6709                                userId);
6710                        if (DEBUG_PREFERRED || debug) {
6711                            Slog.v(TAG, "Found preferred activity:");
6712                            if (ai != null) {
6713                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6714                            } else {
6715                                Slog.v(TAG, "  null");
6716                            }
6717                        }
6718                        if (ai == null) {
6719                            // This previously registered preferred activity
6720                            // component is no longer known.  Most likely an update
6721                            // to the app was installed and in the new version this
6722                            // component no longer exists.  Clean it up by removing
6723                            // it from the preferred activities list, and skip it.
6724                            Slog.w(TAG, "Removing dangling preferred activity: "
6725                                    + pa.mPref.mComponent);
6726                            pir.removeFilter(pa);
6727                            changed = true;
6728                            continue;
6729                        }
6730                        for (int j=0; j<N; j++) {
6731                            final ResolveInfo ri = query.get(j);
6732                            if (!ri.activityInfo.applicationInfo.packageName
6733                                    .equals(ai.applicationInfo.packageName)) {
6734                                continue;
6735                            }
6736                            if (!ri.activityInfo.name.equals(ai.name)) {
6737                                continue;
6738                            }
6739
6740                            if (removeMatches) {
6741                                pir.removeFilter(pa);
6742                                changed = true;
6743                                if (DEBUG_PREFERRED) {
6744                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6745                                }
6746                                break;
6747                            }
6748
6749                            // Okay we found a previously set preferred or last chosen app.
6750                            // If the result set is different from when this
6751                            // was created, we need to clear it and re-ask the
6752                            // user their preference, if we're looking for an "always" type entry.
6753                            if (always && !pa.mPref.sameSet(query)) {
6754                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6755                                        + intent + " type " + resolvedType);
6756                                if (DEBUG_PREFERRED) {
6757                                    Slog.v(TAG, "Removing preferred activity since set changed "
6758                                            + pa.mPref.mComponent);
6759                                }
6760                                pir.removeFilter(pa);
6761                                // Re-add the filter as a "last chosen" entry (!always)
6762                                PreferredActivity lastChosen = new PreferredActivity(
6763                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6764                                pir.addFilter(lastChosen);
6765                                changed = true;
6766                                return null;
6767                            }
6768
6769                            // Yay! Either the set matched or we're looking for the last chosen
6770                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6771                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6772                            return ri;
6773                        }
6774                    }
6775                } finally {
6776                    if (changed) {
6777                        if (DEBUG_PREFERRED) {
6778                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6779                        }
6780                        scheduleWritePackageRestrictionsLocked(userId);
6781                    }
6782                }
6783            }
6784        }
6785        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6786        return null;
6787    }
6788
6789    /*
6790     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6791     */
6792    @Override
6793    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6794            int targetUserId) {
6795        mContext.enforceCallingOrSelfPermission(
6796                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6797        List<CrossProfileIntentFilter> matches =
6798                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6799        if (matches != null) {
6800            int size = matches.size();
6801            for (int i = 0; i < size; i++) {
6802                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6803            }
6804        }
6805        if (hasWebURI(intent)) {
6806            // cross-profile app linking works only towards the parent.
6807            final int callingUid = Binder.getCallingUid();
6808            final UserInfo parent = getProfileParent(sourceUserId);
6809            synchronized(mPackages) {
6810                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6811                        false /*includeInstantApps*/);
6812                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6813                        intent, resolvedType, flags, sourceUserId, parent.id);
6814                return xpDomainInfo != null;
6815            }
6816        }
6817        return false;
6818    }
6819
6820    private UserInfo getProfileParent(int userId) {
6821        final long identity = Binder.clearCallingIdentity();
6822        try {
6823            return sUserManager.getProfileParent(userId);
6824        } finally {
6825            Binder.restoreCallingIdentity(identity);
6826        }
6827    }
6828
6829    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6830            String resolvedType, int userId) {
6831        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6832        if (resolver != null) {
6833            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6834        }
6835        return null;
6836    }
6837
6838    @Override
6839    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6840            String resolvedType, int flags, int userId) {
6841        try {
6842            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6843
6844            return new ParceledListSlice<>(
6845                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6846        } finally {
6847            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6848        }
6849    }
6850
6851    /**
6852     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6853     * instant, returns {@code null}.
6854     */
6855    private String getInstantAppPackageName(int callingUid) {
6856        synchronized (mPackages) {
6857            // If the caller is an isolated app use the owner's uid for the lookup.
6858            if (Process.isIsolated(callingUid)) {
6859                callingUid = mIsolatedOwners.get(callingUid);
6860            }
6861            final int appId = UserHandle.getAppId(callingUid);
6862            final Object obj = mSettings.getUserIdLPr(appId);
6863            if (obj instanceof PackageSetting) {
6864                final PackageSetting ps = (PackageSetting) obj;
6865                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6866                return isInstantApp ? ps.pkg.packageName : null;
6867            }
6868        }
6869        return null;
6870    }
6871
6872    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6873            String resolvedType, int flags, int userId) {
6874        return queryIntentActivitiesInternal(
6875                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6876    }
6877
6878    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6879            String resolvedType, int flags, int filterCallingUid, int userId,
6880            boolean resolveForStart) {
6881        if (!sUserManager.exists(userId)) return Collections.emptyList();
6882        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6883        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6884                false /* requireFullPermission */, false /* checkShell */,
6885                "query intent activities");
6886        final String pkgName = intent.getPackage();
6887        ComponentName comp = intent.getComponent();
6888        if (comp == null) {
6889            if (intent.getSelector() != null) {
6890                intent = intent.getSelector();
6891                comp = intent.getComponent();
6892            }
6893        }
6894
6895        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6896                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6897        if (comp != null) {
6898            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6899            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6900            if (ai != null) {
6901                // When specifying an explicit component, we prevent the activity from being
6902                // used when either 1) the calling package is normal and the activity is within
6903                // an ephemeral application or 2) the calling package is ephemeral and the
6904                // activity is not visible to ephemeral applications.
6905                final boolean matchInstantApp =
6906                        (flags & PackageManager.MATCH_INSTANT) != 0;
6907                final boolean matchVisibleToInstantAppOnly =
6908                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6909                final boolean matchExplicitlyVisibleOnly =
6910                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6911                final boolean isCallerInstantApp =
6912                        instantAppPkgName != null;
6913                final boolean isTargetSameInstantApp =
6914                        comp.getPackageName().equals(instantAppPkgName);
6915                final boolean isTargetInstantApp =
6916                        (ai.applicationInfo.privateFlags
6917                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6918                final boolean isTargetVisibleToInstantApp =
6919                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6920                final boolean isTargetExplicitlyVisibleToInstantApp =
6921                        isTargetVisibleToInstantApp
6922                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6923                final boolean isTargetHiddenFromInstantApp =
6924                        !isTargetVisibleToInstantApp
6925                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6926                final boolean blockResolution =
6927                        !isTargetSameInstantApp
6928                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6929                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6930                                        && isTargetHiddenFromInstantApp));
6931                if (!blockResolution) {
6932                    final ResolveInfo ri = new ResolveInfo();
6933                    ri.activityInfo = ai;
6934                    list.add(ri);
6935                }
6936            }
6937            return applyPostResolutionFilter(list, instantAppPkgName);
6938        }
6939
6940        // reader
6941        boolean sortResult = false;
6942        boolean addEphemeral = false;
6943        List<ResolveInfo> result;
6944        final boolean ephemeralDisabled = isEphemeralDisabled();
6945        synchronized (mPackages) {
6946            if (pkgName == null) {
6947                List<CrossProfileIntentFilter> matchingFilters =
6948                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6949                // Check for results that need to skip the current profile.
6950                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6951                        resolvedType, flags, userId);
6952                if (xpResolveInfo != null) {
6953                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6954                    xpResult.add(xpResolveInfo);
6955                    return applyPostResolutionFilter(
6956                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6957                }
6958
6959                // Check for results in the current profile.
6960                result = filterIfNotSystemUser(mActivities.queryIntent(
6961                        intent, resolvedType, flags, userId), userId);
6962                addEphemeral = !ephemeralDisabled
6963                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6964                // Check for cross profile results.
6965                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6966                xpResolveInfo = queryCrossProfileIntents(
6967                        matchingFilters, intent, resolvedType, flags, userId,
6968                        hasNonNegativePriorityResult);
6969                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6970                    boolean isVisibleToUser = filterIfNotSystemUser(
6971                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6972                    if (isVisibleToUser) {
6973                        result.add(xpResolveInfo);
6974                        sortResult = true;
6975                    }
6976                }
6977                if (hasWebURI(intent)) {
6978                    CrossProfileDomainInfo xpDomainInfo = null;
6979                    final UserInfo parent = getProfileParent(userId);
6980                    if (parent != null) {
6981                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6982                                flags, userId, parent.id);
6983                    }
6984                    if (xpDomainInfo != null) {
6985                        if (xpResolveInfo != null) {
6986                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6987                            // in the result.
6988                            result.remove(xpResolveInfo);
6989                        }
6990                        if (result.size() == 0 && !addEphemeral) {
6991                            // No result in current profile, but found candidate in parent user.
6992                            // And we are not going to add emphemeral app, so we can return the
6993                            // result straight away.
6994                            result.add(xpDomainInfo.resolveInfo);
6995                            return applyPostResolutionFilter(result, instantAppPkgName);
6996                        }
6997                    } else if (result.size() <= 1 && !addEphemeral) {
6998                        // No result in parent user and <= 1 result in current profile, and we
6999                        // are not going to add emphemeral app, so we can return the result without
7000                        // further processing.
7001                        return applyPostResolutionFilter(result, instantAppPkgName);
7002                    }
7003                    // We have more than one candidate (combining results from current and parent
7004                    // profile), so we need filtering and sorting.
7005                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7006                            intent, flags, result, xpDomainInfo, userId);
7007                    sortResult = true;
7008                }
7009            } else {
7010                final PackageParser.Package pkg = mPackages.get(pkgName);
7011                result = null;
7012                if (pkg != null) {
7013                    result = filterIfNotSystemUser(
7014                            mActivities.queryIntentForPackage(
7015                                    intent, resolvedType, flags, pkg.activities, userId),
7016                            userId);
7017                }
7018                if (result == null || result.size() == 0) {
7019                    // the caller wants to resolve for a particular package; however, there
7020                    // were no installed results, so, try to find an ephemeral result
7021                    addEphemeral = !ephemeralDisabled
7022                            && isInstantAppAllowed(
7023                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7024                    if (result == null) {
7025                        result = new ArrayList<>();
7026                    }
7027                }
7028            }
7029        }
7030        if (addEphemeral) {
7031            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7032        }
7033        if (sortResult) {
7034            Collections.sort(result, mResolvePrioritySorter);
7035        }
7036        return applyPostResolutionFilter(result, instantAppPkgName);
7037    }
7038
7039    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7040            String resolvedType, int flags, int userId) {
7041        // first, check to see if we've got an instant app already installed
7042        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7043        ResolveInfo localInstantApp = null;
7044        boolean blockResolution = false;
7045        if (!alreadyResolvedLocally) {
7046            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7047                    flags
7048                        | PackageManager.GET_RESOLVED_FILTER
7049                        | PackageManager.MATCH_INSTANT
7050                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7051                    userId);
7052            for (int i = instantApps.size() - 1; i >= 0; --i) {
7053                final ResolveInfo info = instantApps.get(i);
7054                final String packageName = info.activityInfo.packageName;
7055                final PackageSetting ps = mSettings.mPackages.get(packageName);
7056                if (ps.getInstantApp(userId)) {
7057                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7058                    final int status = (int)(packedStatus >> 32);
7059                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7060                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7061                        // there's a local instant application installed, but, the user has
7062                        // chosen to never use it; skip resolution and don't acknowledge
7063                        // an instant application is even available
7064                        if (DEBUG_EPHEMERAL) {
7065                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7066                        }
7067                        blockResolution = true;
7068                        break;
7069                    } else {
7070                        // we have a locally installed instant application; skip resolution
7071                        // but acknowledge there's an instant application available
7072                        if (DEBUG_EPHEMERAL) {
7073                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7074                        }
7075                        localInstantApp = info;
7076                        break;
7077                    }
7078                }
7079            }
7080        }
7081        // no app installed, let's see if one's available
7082        AuxiliaryResolveInfo auxiliaryResponse = null;
7083        if (!blockResolution) {
7084            if (localInstantApp == null) {
7085                // we don't have an instant app locally, resolve externally
7086                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7087                final InstantAppRequest requestObject = new InstantAppRequest(
7088                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7089                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7090                auxiliaryResponse =
7091                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7092                                mContext, mInstantAppResolverConnection, requestObject);
7093                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7094            } else {
7095                // we have an instant application locally, but, we can't admit that since
7096                // callers shouldn't be able to determine prior browsing. create a dummy
7097                // auxiliary response so the downstream code behaves as if there's an
7098                // instant application available externally. when it comes time to start
7099                // the instant application, we'll do the right thing.
7100                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7101                auxiliaryResponse = new AuxiliaryResolveInfo(
7102                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7103            }
7104        }
7105        if (auxiliaryResponse != null) {
7106            if (DEBUG_EPHEMERAL) {
7107                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7108            }
7109            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7110            final PackageSetting ps =
7111                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7112            if (ps != null) {
7113                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7114                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7115                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7116                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7117                // make sure this resolver is the default
7118                ephemeralInstaller.isDefault = true;
7119                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7120                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7121                // add a non-generic filter
7122                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7123                ephemeralInstaller.filter.addDataPath(
7124                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7125                ephemeralInstaller.isInstantAppAvailable = true;
7126                result.add(ephemeralInstaller);
7127            }
7128        }
7129        return result;
7130    }
7131
7132    private static class CrossProfileDomainInfo {
7133        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7134        ResolveInfo resolveInfo;
7135        /* Best domain verification status of the activities found in the other profile */
7136        int bestDomainVerificationStatus;
7137    }
7138
7139    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7140            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7141        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7142                sourceUserId)) {
7143            return null;
7144        }
7145        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7146                resolvedType, flags, parentUserId);
7147
7148        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7149            return null;
7150        }
7151        CrossProfileDomainInfo result = null;
7152        int size = resultTargetUser.size();
7153        for (int i = 0; i < size; i++) {
7154            ResolveInfo riTargetUser = resultTargetUser.get(i);
7155            // Intent filter verification is only for filters that specify a host. So don't return
7156            // those that handle all web uris.
7157            if (riTargetUser.handleAllWebDataURI) {
7158                continue;
7159            }
7160            String packageName = riTargetUser.activityInfo.packageName;
7161            PackageSetting ps = mSettings.mPackages.get(packageName);
7162            if (ps == null) {
7163                continue;
7164            }
7165            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7166            int status = (int)(verificationState >> 32);
7167            if (result == null) {
7168                result = new CrossProfileDomainInfo();
7169                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7170                        sourceUserId, parentUserId);
7171                result.bestDomainVerificationStatus = status;
7172            } else {
7173                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7174                        result.bestDomainVerificationStatus);
7175            }
7176        }
7177        // Don't consider matches with status NEVER across profiles.
7178        if (result != null && result.bestDomainVerificationStatus
7179                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7180            return null;
7181        }
7182        return result;
7183    }
7184
7185    /**
7186     * Verification statuses are ordered from the worse to the best, except for
7187     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7188     */
7189    private int bestDomainVerificationStatus(int status1, int status2) {
7190        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7191            return status2;
7192        }
7193        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7194            return status1;
7195        }
7196        return (int) MathUtils.max(status1, status2);
7197    }
7198
7199    private boolean isUserEnabled(int userId) {
7200        long callingId = Binder.clearCallingIdentity();
7201        try {
7202            UserInfo userInfo = sUserManager.getUserInfo(userId);
7203            return userInfo != null && userInfo.isEnabled();
7204        } finally {
7205            Binder.restoreCallingIdentity(callingId);
7206        }
7207    }
7208
7209    /**
7210     * Filter out activities with systemUserOnly flag set, when current user is not System.
7211     *
7212     * @return filtered list
7213     */
7214    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7215        if (userId == UserHandle.USER_SYSTEM) {
7216            return resolveInfos;
7217        }
7218        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7219            ResolveInfo info = resolveInfos.get(i);
7220            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7221                resolveInfos.remove(i);
7222            }
7223        }
7224        return resolveInfos;
7225    }
7226
7227    /**
7228     * Filters out ephemeral activities.
7229     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7230     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7231     *
7232     * @param resolveInfos The pre-filtered list of resolved activities
7233     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7234     *          is performed.
7235     * @return A filtered list of resolved activities.
7236     */
7237    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7238            String ephemeralPkgName) {
7239        // TODO: When adding on-demand split support for non-instant apps, remove this check
7240        // and always apply post filtering
7241        if (ephemeralPkgName == null) {
7242            return resolveInfos;
7243        }
7244        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7245            final ResolveInfo info = resolveInfos.get(i);
7246            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7247            // allow activities that are defined in the provided package
7248            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
7249                if (info.activityInfo.splitName != null
7250                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7251                                info.activityInfo.splitName)) {
7252                    // requested activity is defined in a split that hasn't been installed yet.
7253                    // add the installer to the resolve list
7254                    if (DEBUG_EPHEMERAL) {
7255                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7256                    }
7257                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7258                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7259                            info.activityInfo.packageName, info.activityInfo.splitName,
7260                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7261                    // make sure this resolver is the default
7262                    installerInfo.isDefault = true;
7263                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7264                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7265                    // add a non-generic filter
7266                    installerInfo.filter = new IntentFilter();
7267                    // load resources from the correct package
7268                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7269                    resolveInfos.set(i, installerInfo);
7270                }
7271                continue;
7272            }
7273            // allow activities that have been explicitly exposed to ephemeral apps
7274            if (!isEphemeralApp
7275                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7276                continue;
7277            }
7278            resolveInfos.remove(i);
7279        }
7280        return resolveInfos;
7281    }
7282
7283    /**
7284     * @param resolveInfos list of resolve infos in descending priority order
7285     * @return if the list contains a resolve info with non-negative priority
7286     */
7287    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7288        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7289    }
7290
7291    private static boolean hasWebURI(Intent intent) {
7292        if (intent.getData() == null) {
7293            return false;
7294        }
7295        final String scheme = intent.getScheme();
7296        if (TextUtils.isEmpty(scheme)) {
7297            return false;
7298        }
7299        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7300    }
7301
7302    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7303            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7304            int userId) {
7305        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7306
7307        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7308            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7309                    candidates.size());
7310        }
7311
7312        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7313        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7314        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7315        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7316        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7317        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7318
7319        synchronized (mPackages) {
7320            final int count = candidates.size();
7321            // First, try to use linked apps. Partition the candidates into four lists:
7322            // one for the final results, one for the "do not use ever", one for "undefined status"
7323            // and finally one for "browser app type".
7324            for (int n=0; n<count; n++) {
7325                ResolveInfo info = candidates.get(n);
7326                String packageName = info.activityInfo.packageName;
7327                PackageSetting ps = mSettings.mPackages.get(packageName);
7328                if (ps != null) {
7329                    // Add to the special match all list (Browser use case)
7330                    if (info.handleAllWebDataURI) {
7331                        matchAllList.add(info);
7332                        continue;
7333                    }
7334                    // Try to get the status from User settings first
7335                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7336                    int status = (int)(packedStatus >> 32);
7337                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7338                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7339                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7340                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7341                                    + " : linkgen=" + linkGeneration);
7342                        }
7343                        // Use link-enabled generation as preferredOrder, i.e.
7344                        // prefer newly-enabled over earlier-enabled.
7345                        info.preferredOrder = linkGeneration;
7346                        alwaysList.add(info);
7347                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7348                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7349                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7350                        }
7351                        neverList.add(info);
7352                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7353                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7354                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7355                        }
7356                        alwaysAskList.add(info);
7357                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7358                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7359                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7360                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7361                        }
7362                        undefinedList.add(info);
7363                    }
7364                }
7365            }
7366
7367            // We'll want to include browser possibilities in a few cases
7368            boolean includeBrowser = false;
7369
7370            // First try to add the "always" resolution(s) for the current user, if any
7371            if (alwaysList.size() > 0) {
7372                result.addAll(alwaysList);
7373            } else {
7374                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7375                result.addAll(undefinedList);
7376                // Maybe add one for the other profile.
7377                if (xpDomainInfo != null && (
7378                        xpDomainInfo.bestDomainVerificationStatus
7379                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7380                    result.add(xpDomainInfo.resolveInfo);
7381                }
7382                includeBrowser = true;
7383            }
7384
7385            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7386            // If there were 'always' entries their preferred order has been set, so we also
7387            // back that off to make the alternatives equivalent
7388            if (alwaysAskList.size() > 0) {
7389                for (ResolveInfo i : result) {
7390                    i.preferredOrder = 0;
7391                }
7392                result.addAll(alwaysAskList);
7393                includeBrowser = true;
7394            }
7395
7396            if (includeBrowser) {
7397                // Also add browsers (all of them or only the default one)
7398                if (DEBUG_DOMAIN_VERIFICATION) {
7399                    Slog.v(TAG, "   ...including browsers in candidate set");
7400                }
7401                if ((matchFlags & MATCH_ALL) != 0) {
7402                    result.addAll(matchAllList);
7403                } else {
7404                    // Browser/generic handling case.  If there's a default browser, go straight
7405                    // to that (but only if there is no other higher-priority match).
7406                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7407                    int maxMatchPrio = 0;
7408                    ResolveInfo defaultBrowserMatch = null;
7409                    final int numCandidates = matchAllList.size();
7410                    for (int n = 0; n < numCandidates; n++) {
7411                        ResolveInfo info = matchAllList.get(n);
7412                        // track the highest overall match priority...
7413                        if (info.priority > maxMatchPrio) {
7414                            maxMatchPrio = info.priority;
7415                        }
7416                        // ...and the highest-priority default browser match
7417                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7418                            if (defaultBrowserMatch == null
7419                                    || (defaultBrowserMatch.priority < info.priority)) {
7420                                if (debug) {
7421                                    Slog.v(TAG, "Considering default browser match " + info);
7422                                }
7423                                defaultBrowserMatch = info;
7424                            }
7425                        }
7426                    }
7427                    if (defaultBrowserMatch != null
7428                            && defaultBrowserMatch.priority >= maxMatchPrio
7429                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7430                    {
7431                        if (debug) {
7432                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7433                        }
7434                        result.add(defaultBrowserMatch);
7435                    } else {
7436                        result.addAll(matchAllList);
7437                    }
7438                }
7439
7440                // If there is nothing selected, add all candidates and remove the ones that the user
7441                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7442                if (result.size() == 0) {
7443                    result.addAll(candidates);
7444                    result.removeAll(neverList);
7445                }
7446            }
7447        }
7448        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7449            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7450                    result.size());
7451            for (ResolveInfo info : result) {
7452                Slog.v(TAG, "  + " + info.activityInfo);
7453            }
7454        }
7455        return result;
7456    }
7457
7458    // Returns a packed value as a long:
7459    //
7460    // high 'int'-sized word: link status: undefined/ask/never/always.
7461    // low 'int'-sized word: relative priority among 'always' results.
7462    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7463        long result = ps.getDomainVerificationStatusForUser(userId);
7464        // if none available, get the master status
7465        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7466            if (ps.getIntentFilterVerificationInfo() != null) {
7467                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7468            }
7469        }
7470        return result;
7471    }
7472
7473    private ResolveInfo querySkipCurrentProfileIntents(
7474            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7475            int flags, int sourceUserId) {
7476        if (matchingFilters != null) {
7477            int size = matchingFilters.size();
7478            for (int i = 0; i < size; i ++) {
7479                CrossProfileIntentFilter filter = matchingFilters.get(i);
7480                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7481                    // Checking if there are activities in the target user that can handle the
7482                    // intent.
7483                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7484                            resolvedType, flags, sourceUserId);
7485                    if (resolveInfo != null) {
7486                        return resolveInfo;
7487                    }
7488                }
7489            }
7490        }
7491        return null;
7492    }
7493
7494    // Return matching ResolveInfo in target user if any.
7495    private ResolveInfo queryCrossProfileIntents(
7496            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7497            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7498        if (matchingFilters != null) {
7499            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7500            // match the same intent. For performance reasons, it is better not to
7501            // run queryIntent twice for the same userId
7502            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7503            int size = matchingFilters.size();
7504            for (int i = 0; i < size; i++) {
7505                CrossProfileIntentFilter filter = matchingFilters.get(i);
7506                int targetUserId = filter.getTargetUserId();
7507                boolean skipCurrentProfile =
7508                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7509                boolean skipCurrentProfileIfNoMatchFound =
7510                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7511                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7512                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7513                    // Checking if there are activities in the target user that can handle the
7514                    // intent.
7515                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7516                            resolvedType, flags, sourceUserId);
7517                    if (resolveInfo != null) return resolveInfo;
7518                    alreadyTriedUserIds.put(targetUserId, true);
7519                }
7520            }
7521        }
7522        return null;
7523    }
7524
7525    /**
7526     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7527     * will forward the intent to the filter's target user.
7528     * Otherwise, returns null.
7529     */
7530    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7531            String resolvedType, int flags, int sourceUserId) {
7532        int targetUserId = filter.getTargetUserId();
7533        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7534                resolvedType, flags, targetUserId);
7535        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7536            // If all the matches in the target profile are suspended, return null.
7537            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7538                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7539                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7540                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7541                            targetUserId);
7542                }
7543            }
7544        }
7545        return null;
7546    }
7547
7548    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7549            int sourceUserId, int targetUserId) {
7550        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7551        long ident = Binder.clearCallingIdentity();
7552        boolean targetIsProfile;
7553        try {
7554            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7555        } finally {
7556            Binder.restoreCallingIdentity(ident);
7557        }
7558        String className;
7559        if (targetIsProfile) {
7560            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7561        } else {
7562            className = FORWARD_INTENT_TO_PARENT;
7563        }
7564        ComponentName forwardingActivityComponentName = new ComponentName(
7565                mAndroidApplication.packageName, className);
7566        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7567                sourceUserId);
7568        if (!targetIsProfile) {
7569            forwardingActivityInfo.showUserIcon = targetUserId;
7570            forwardingResolveInfo.noResourceId = true;
7571        }
7572        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7573        forwardingResolveInfo.priority = 0;
7574        forwardingResolveInfo.preferredOrder = 0;
7575        forwardingResolveInfo.match = 0;
7576        forwardingResolveInfo.isDefault = true;
7577        forwardingResolveInfo.filter = filter;
7578        forwardingResolveInfo.targetUserId = targetUserId;
7579        return forwardingResolveInfo;
7580    }
7581
7582    @Override
7583    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7584            Intent[] specifics, String[] specificTypes, Intent intent,
7585            String resolvedType, int flags, int userId) {
7586        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7587                specificTypes, intent, resolvedType, flags, userId));
7588    }
7589
7590    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7591            Intent[] specifics, String[] specificTypes, Intent intent,
7592            String resolvedType, int flags, int userId) {
7593        if (!sUserManager.exists(userId)) return Collections.emptyList();
7594        final int callingUid = Binder.getCallingUid();
7595        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7596                false /*includeInstantApps*/);
7597        enforceCrossUserPermission(callingUid, userId,
7598                false /*requireFullPermission*/, false /*checkShell*/,
7599                "query intent activity options");
7600        final String resultsAction = intent.getAction();
7601
7602        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7603                | PackageManager.GET_RESOLVED_FILTER, userId);
7604
7605        if (DEBUG_INTENT_MATCHING) {
7606            Log.v(TAG, "Query " + intent + ": " + results);
7607        }
7608
7609        int specificsPos = 0;
7610        int N;
7611
7612        // todo: note that the algorithm used here is O(N^2).  This
7613        // isn't a problem in our current environment, but if we start running
7614        // into situations where we have more than 5 or 10 matches then this
7615        // should probably be changed to something smarter...
7616
7617        // First we go through and resolve each of the specific items
7618        // that were supplied, taking care of removing any corresponding
7619        // duplicate items in the generic resolve list.
7620        if (specifics != null) {
7621            for (int i=0; i<specifics.length; i++) {
7622                final Intent sintent = specifics[i];
7623                if (sintent == null) {
7624                    continue;
7625                }
7626
7627                if (DEBUG_INTENT_MATCHING) {
7628                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7629                }
7630
7631                String action = sintent.getAction();
7632                if (resultsAction != null && resultsAction.equals(action)) {
7633                    // If this action was explicitly requested, then don't
7634                    // remove things that have it.
7635                    action = null;
7636                }
7637
7638                ResolveInfo ri = null;
7639                ActivityInfo ai = null;
7640
7641                ComponentName comp = sintent.getComponent();
7642                if (comp == null) {
7643                    ri = resolveIntent(
7644                        sintent,
7645                        specificTypes != null ? specificTypes[i] : null,
7646                            flags, userId);
7647                    if (ri == null) {
7648                        continue;
7649                    }
7650                    if (ri == mResolveInfo) {
7651                        // ACK!  Must do something better with this.
7652                    }
7653                    ai = ri.activityInfo;
7654                    comp = new ComponentName(ai.applicationInfo.packageName,
7655                            ai.name);
7656                } else {
7657                    ai = getActivityInfo(comp, flags, userId);
7658                    if (ai == null) {
7659                        continue;
7660                    }
7661                }
7662
7663                // Look for any generic query activities that are duplicates
7664                // of this specific one, and remove them from the results.
7665                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7666                N = results.size();
7667                int j;
7668                for (j=specificsPos; j<N; j++) {
7669                    ResolveInfo sri = results.get(j);
7670                    if ((sri.activityInfo.name.equals(comp.getClassName())
7671                            && sri.activityInfo.applicationInfo.packageName.equals(
7672                                    comp.getPackageName()))
7673                        || (action != null && sri.filter.matchAction(action))) {
7674                        results.remove(j);
7675                        if (DEBUG_INTENT_MATCHING) Log.v(
7676                            TAG, "Removing duplicate item from " + j
7677                            + " due to specific " + specificsPos);
7678                        if (ri == null) {
7679                            ri = sri;
7680                        }
7681                        j--;
7682                        N--;
7683                    }
7684                }
7685
7686                // Add this specific item to its proper place.
7687                if (ri == null) {
7688                    ri = new ResolveInfo();
7689                    ri.activityInfo = ai;
7690                }
7691                results.add(specificsPos, ri);
7692                ri.specificIndex = i;
7693                specificsPos++;
7694            }
7695        }
7696
7697        // Now we go through the remaining generic results and remove any
7698        // duplicate actions that are found here.
7699        N = results.size();
7700        for (int i=specificsPos; i<N-1; i++) {
7701            final ResolveInfo rii = results.get(i);
7702            if (rii.filter == null) {
7703                continue;
7704            }
7705
7706            // Iterate over all of the actions of this result's intent
7707            // filter...  typically this should be just one.
7708            final Iterator<String> it = rii.filter.actionsIterator();
7709            if (it == null) {
7710                continue;
7711            }
7712            while (it.hasNext()) {
7713                final String action = it.next();
7714                if (resultsAction != null && resultsAction.equals(action)) {
7715                    // If this action was explicitly requested, then don't
7716                    // remove things that have it.
7717                    continue;
7718                }
7719                for (int j=i+1; j<N; j++) {
7720                    final ResolveInfo rij = results.get(j);
7721                    if (rij.filter != null && rij.filter.hasAction(action)) {
7722                        results.remove(j);
7723                        if (DEBUG_INTENT_MATCHING) Log.v(
7724                            TAG, "Removing duplicate item from " + j
7725                            + " due to action " + action + " at " + i);
7726                        j--;
7727                        N--;
7728                    }
7729                }
7730            }
7731
7732            // If the caller didn't request filter information, drop it now
7733            // so we don't have to marshall/unmarshall it.
7734            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7735                rii.filter = null;
7736            }
7737        }
7738
7739        // Filter out the caller activity if so requested.
7740        if (caller != null) {
7741            N = results.size();
7742            for (int i=0; i<N; i++) {
7743                ActivityInfo ainfo = results.get(i).activityInfo;
7744                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7745                        && caller.getClassName().equals(ainfo.name)) {
7746                    results.remove(i);
7747                    break;
7748                }
7749            }
7750        }
7751
7752        // If the caller didn't request filter information,
7753        // drop them now so we don't have to
7754        // marshall/unmarshall it.
7755        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7756            N = results.size();
7757            for (int i=0; i<N; i++) {
7758                results.get(i).filter = null;
7759            }
7760        }
7761
7762        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7763        return results;
7764    }
7765
7766    @Override
7767    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7768            String resolvedType, int flags, int userId) {
7769        return new ParceledListSlice<>(
7770                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7771    }
7772
7773    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7774            String resolvedType, int flags, int userId) {
7775        if (!sUserManager.exists(userId)) return Collections.emptyList();
7776        final int callingUid = Binder.getCallingUid();
7777        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7778        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7779                false /*includeInstantApps*/);
7780        ComponentName comp = intent.getComponent();
7781        if (comp == null) {
7782            if (intent.getSelector() != null) {
7783                intent = intent.getSelector();
7784                comp = intent.getComponent();
7785            }
7786        }
7787        if (comp != null) {
7788            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7789            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7790            if (ai != null) {
7791                // When specifying an explicit component, we prevent the activity from being
7792                // used when either 1) the calling package is normal and the activity is within
7793                // an instant application or 2) the calling package is ephemeral and the
7794                // activity is not visible to instant applications.
7795                final boolean matchInstantApp =
7796                        (flags & PackageManager.MATCH_INSTANT) != 0;
7797                final boolean matchVisibleToInstantAppOnly =
7798                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7799                final boolean matchExplicitlyVisibleOnly =
7800                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7801                final boolean isCallerInstantApp =
7802                        instantAppPkgName != null;
7803                final boolean isTargetSameInstantApp =
7804                        comp.getPackageName().equals(instantAppPkgName);
7805                final boolean isTargetInstantApp =
7806                        (ai.applicationInfo.privateFlags
7807                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7808                final boolean isTargetVisibleToInstantApp =
7809                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7810                final boolean isTargetExplicitlyVisibleToInstantApp =
7811                        isTargetVisibleToInstantApp
7812                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7813                final boolean isTargetHiddenFromInstantApp =
7814                        !isTargetVisibleToInstantApp
7815                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7816                final boolean blockResolution =
7817                        !isTargetSameInstantApp
7818                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7819                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7820                                        && isTargetHiddenFromInstantApp));
7821                if (!blockResolution) {
7822                    ResolveInfo ri = new ResolveInfo();
7823                    ri.activityInfo = ai;
7824                    list.add(ri);
7825                }
7826            }
7827            return applyPostResolutionFilter(list, instantAppPkgName);
7828        }
7829
7830        // reader
7831        synchronized (mPackages) {
7832            String pkgName = intent.getPackage();
7833            if (pkgName == null) {
7834                final List<ResolveInfo> result =
7835                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7836                return applyPostResolutionFilter(result, instantAppPkgName);
7837            }
7838            final PackageParser.Package pkg = mPackages.get(pkgName);
7839            if (pkg != null) {
7840                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7841                        intent, resolvedType, flags, pkg.receivers, userId);
7842                return applyPostResolutionFilter(result, instantAppPkgName);
7843            }
7844            return Collections.emptyList();
7845        }
7846    }
7847
7848    @Override
7849    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7850        final int callingUid = Binder.getCallingUid();
7851        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7852    }
7853
7854    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7855            int userId, int callingUid) {
7856        if (!sUserManager.exists(userId)) return null;
7857        flags = updateFlagsForResolve(
7858                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7859        List<ResolveInfo> query = queryIntentServicesInternal(
7860                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7861        if (query != null) {
7862            if (query.size() >= 1) {
7863                // If there is more than one service with the same priority,
7864                // just arbitrarily pick the first one.
7865                return query.get(0);
7866            }
7867        }
7868        return null;
7869    }
7870
7871    @Override
7872    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7873            String resolvedType, int flags, int userId) {
7874        final int callingUid = Binder.getCallingUid();
7875        return new ParceledListSlice<>(queryIntentServicesInternal(
7876                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7877    }
7878
7879    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7880            String resolvedType, int flags, int userId, int callingUid,
7881            boolean includeInstantApps) {
7882        if (!sUserManager.exists(userId)) return Collections.emptyList();
7883        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7884        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7885        ComponentName comp = intent.getComponent();
7886        if (comp == null) {
7887            if (intent.getSelector() != null) {
7888                intent = intent.getSelector();
7889                comp = intent.getComponent();
7890            }
7891        }
7892        if (comp != null) {
7893            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7894            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7895            if (si != null) {
7896                // When specifying an explicit component, we prevent the service from being
7897                // used when either 1) the service is in an instant application and the
7898                // caller is not the same instant application or 2) the calling package is
7899                // ephemeral and the activity is not visible to ephemeral applications.
7900                final boolean matchInstantApp =
7901                        (flags & PackageManager.MATCH_INSTANT) != 0;
7902                final boolean matchVisibleToInstantAppOnly =
7903                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7904                final boolean isCallerInstantApp =
7905                        instantAppPkgName != null;
7906                final boolean isTargetSameInstantApp =
7907                        comp.getPackageName().equals(instantAppPkgName);
7908                final boolean isTargetInstantApp =
7909                        (si.applicationInfo.privateFlags
7910                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7911                final boolean isTargetHiddenFromInstantApp =
7912                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7913                final boolean blockResolution =
7914                        !isTargetSameInstantApp
7915                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7916                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7917                                        && isTargetHiddenFromInstantApp));
7918                if (!blockResolution) {
7919                    final ResolveInfo ri = new ResolveInfo();
7920                    ri.serviceInfo = si;
7921                    list.add(ri);
7922                }
7923            }
7924            return list;
7925        }
7926
7927        // reader
7928        synchronized (mPackages) {
7929            String pkgName = intent.getPackage();
7930            if (pkgName == null) {
7931                return applyPostServiceResolutionFilter(
7932                        mServices.queryIntent(intent, resolvedType, flags, userId),
7933                        instantAppPkgName);
7934            }
7935            final PackageParser.Package pkg = mPackages.get(pkgName);
7936            if (pkg != null) {
7937                return applyPostServiceResolutionFilter(
7938                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7939                                userId),
7940                        instantAppPkgName);
7941            }
7942            return Collections.emptyList();
7943        }
7944    }
7945
7946    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7947            String instantAppPkgName) {
7948        // TODO: When adding on-demand split support for non-instant apps, remove this check
7949        // and always apply post filtering
7950        if (instantAppPkgName == null) {
7951            return resolveInfos;
7952        }
7953        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7954            final ResolveInfo info = resolveInfos.get(i);
7955            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7956            // allow services that are defined in the provided package
7957            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7958                if (info.serviceInfo.splitName != null
7959                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7960                                info.serviceInfo.splitName)) {
7961                    // requested service is defined in a split that hasn't been installed yet.
7962                    // add the installer to the resolve list
7963                    if (DEBUG_EPHEMERAL) {
7964                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7965                    }
7966                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7967                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7968                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7969                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7970                    // make sure this resolver is the default
7971                    installerInfo.isDefault = true;
7972                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7973                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7974                    // add a non-generic filter
7975                    installerInfo.filter = new IntentFilter();
7976                    // load resources from the correct package
7977                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7978                    resolveInfos.set(i, installerInfo);
7979                }
7980                continue;
7981            }
7982            // allow services that have been explicitly exposed to ephemeral apps
7983            if (!isEphemeralApp
7984                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7985                continue;
7986            }
7987            resolveInfos.remove(i);
7988        }
7989        return resolveInfos;
7990    }
7991
7992    @Override
7993    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7994            String resolvedType, int flags, int userId) {
7995        return new ParceledListSlice<>(
7996                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7997    }
7998
7999    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8000            Intent intent, String resolvedType, int flags, int userId) {
8001        if (!sUserManager.exists(userId)) return Collections.emptyList();
8002        final int callingUid = Binder.getCallingUid();
8003        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8004        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8005                false /*includeInstantApps*/);
8006        ComponentName comp = intent.getComponent();
8007        if (comp == null) {
8008            if (intent.getSelector() != null) {
8009                intent = intent.getSelector();
8010                comp = intent.getComponent();
8011            }
8012        }
8013        if (comp != null) {
8014            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8015            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8016            if (pi != null) {
8017                // When specifying an explicit component, we prevent the provider from being
8018                // used when either 1) the provider is in an instant application and the
8019                // caller is not the same instant application or 2) the calling package is an
8020                // instant application and the provider is not visible to instant applications.
8021                final boolean matchInstantApp =
8022                        (flags & PackageManager.MATCH_INSTANT) != 0;
8023                final boolean matchVisibleToInstantAppOnly =
8024                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8025                final boolean isCallerInstantApp =
8026                        instantAppPkgName != null;
8027                final boolean isTargetSameInstantApp =
8028                        comp.getPackageName().equals(instantAppPkgName);
8029                final boolean isTargetInstantApp =
8030                        (pi.applicationInfo.privateFlags
8031                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8032                final boolean isTargetHiddenFromInstantApp =
8033                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8034                final boolean blockResolution =
8035                        !isTargetSameInstantApp
8036                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8037                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8038                                        && isTargetHiddenFromInstantApp));
8039                if (!blockResolution) {
8040                    final ResolveInfo ri = new ResolveInfo();
8041                    ri.providerInfo = pi;
8042                    list.add(ri);
8043                }
8044            }
8045            return list;
8046        }
8047
8048        // reader
8049        synchronized (mPackages) {
8050            String pkgName = intent.getPackage();
8051            if (pkgName == null) {
8052                return applyPostContentProviderResolutionFilter(
8053                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8054                        instantAppPkgName);
8055            }
8056            final PackageParser.Package pkg = mPackages.get(pkgName);
8057            if (pkg != null) {
8058                return applyPostContentProviderResolutionFilter(
8059                        mProviders.queryIntentForPackage(
8060                        intent, resolvedType, flags, pkg.providers, userId),
8061                        instantAppPkgName);
8062            }
8063            return Collections.emptyList();
8064        }
8065    }
8066
8067    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8068            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8069        // TODO: When adding on-demand split support for non-instant applications, remove
8070        // this check and always apply post filtering
8071        if (instantAppPkgName == null) {
8072            return resolveInfos;
8073        }
8074        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8075            final ResolveInfo info = resolveInfos.get(i);
8076            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8077            // allow providers that are defined in the provided package
8078            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8079                if (info.providerInfo.splitName != null
8080                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8081                                info.providerInfo.splitName)) {
8082                    // requested provider is defined in a split that hasn't been installed yet.
8083                    // add the installer to the resolve list
8084                    if (DEBUG_EPHEMERAL) {
8085                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8086                    }
8087                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8088                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8089                            info.providerInfo.packageName, info.providerInfo.splitName,
8090                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8091                    // make sure this resolver is the default
8092                    installerInfo.isDefault = true;
8093                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8094                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8095                    // add a non-generic filter
8096                    installerInfo.filter = new IntentFilter();
8097                    // load resources from the correct package
8098                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8099                    resolveInfos.set(i, installerInfo);
8100                }
8101                continue;
8102            }
8103            // allow providers that have been explicitly exposed to instant applications
8104            if (!isEphemeralApp
8105                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8106                continue;
8107            }
8108            resolveInfos.remove(i);
8109        }
8110        return resolveInfos;
8111    }
8112
8113    @Override
8114    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8115        final int callingUid = Binder.getCallingUid();
8116        if (getInstantAppPackageName(callingUid) != null) {
8117            return ParceledListSlice.emptyList();
8118        }
8119        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8120        flags = updateFlagsForPackage(flags, userId, null);
8121        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8122        enforceCrossUserPermission(callingUid, userId,
8123                true /* requireFullPermission */, false /* checkShell */,
8124                "get installed packages");
8125
8126        // writer
8127        synchronized (mPackages) {
8128            ArrayList<PackageInfo> list;
8129            if (listUninstalled) {
8130                list = new ArrayList<>(mSettings.mPackages.size());
8131                for (PackageSetting ps : mSettings.mPackages.values()) {
8132                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8133                        continue;
8134                    }
8135                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8136                        return null;
8137                    }
8138                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8139                    if (pi != null) {
8140                        list.add(pi);
8141                    }
8142                }
8143            } else {
8144                list = new ArrayList<>(mPackages.size());
8145                for (PackageParser.Package p : mPackages.values()) {
8146                    final PackageSetting ps = (PackageSetting) p.mExtras;
8147                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8148                        continue;
8149                    }
8150                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8151                        return null;
8152                    }
8153                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8154                            p.mExtras, flags, userId);
8155                    if (pi != null) {
8156                        list.add(pi);
8157                    }
8158                }
8159            }
8160
8161            return new ParceledListSlice<>(list);
8162        }
8163    }
8164
8165    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8166            String[] permissions, boolean[] tmp, int flags, int userId) {
8167        int numMatch = 0;
8168        final PermissionsState permissionsState = ps.getPermissionsState();
8169        for (int i=0; i<permissions.length; i++) {
8170            final String permission = permissions[i];
8171            if (permissionsState.hasPermission(permission, userId)) {
8172                tmp[i] = true;
8173                numMatch++;
8174            } else {
8175                tmp[i] = false;
8176            }
8177        }
8178        if (numMatch == 0) {
8179            return;
8180        }
8181        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8182
8183        // The above might return null in cases of uninstalled apps or install-state
8184        // skew across users/profiles.
8185        if (pi != null) {
8186            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8187                if (numMatch == permissions.length) {
8188                    pi.requestedPermissions = permissions;
8189                } else {
8190                    pi.requestedPermissions = new String[numMatch];
8191                    numMatch = 0;
8192                    for (int i=0; i<permissions.length; i++) {
8193                        if (tmp[i]) {
8194                            pi.requestedPermissions[numMatch] = permissions[i];
8195                            numMatch++;
8196                        }
8197                    }
8198                }
8199            }
8200            list.add(pi);
8201        }
8202    }
8203
8204    @Override
8205    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8206            String[] permissions, int flags, int userId) {
8207        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8208        flags = updateFlagsForPackage(flags, userId, permissions);
8209        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8210                true /* requireFullPermission */, false /* checkShell */,
8211                "get packages holding permissions");
8212        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8213
8214        // writer
8215        synchronized (mPackages) {
8216            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8217            boolean[] tmpBools = new boolean[permissions.length];
8218            if (listUninstalled) {
8219                for (PackageSetting ps : mSettings.mPackages.values()) {
8220                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8221                            userId);
8222                }
8223            } else {
8224                for (PackageParser.Package pkg : mPackages.values()) {
8225                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8226                    if (ps != null) {
8227                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8228                                userId);
8229                    }
8230                }
8231            }
8232
8233            return new ParceledListSlice<PackageInfo>(list);
8234        }
8235    }
8236
8237    @Override
8238    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8239        final int callingUid = Binder.getCallingUid();
8240        if (getInstantAppPackageName(callingUid) != null) {
8241            return ParceledListSlice.emptyList();
8242        }
8243        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8244        flags = updateFlagsForApplication(flags, userId, null);
8245        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8246
8247        // writer
8248        synchronized (mPackages) {
8249            ArrayList<ApplicationInfo> list;
8250            if (listUninstalled) {
8251                list = new ArrayList<>(mSettings.mPackages.size());
8252                for (PackageSetting ps : mSettings.mPackages.values()) {
8253                    ApplicationInfo ai;
8254                    int effectiveFlags = flags;
8255                    if (ps.isSystem()) {
8256                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8257                    }
8258                    if (ps.pkg != null) {
8259                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8260                            continue;
8261                        }
8262                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8263                            return null;
8264                        }
8265                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8266                                ps.readUserState(userId), userId);
8267                        if (ai != null) {
8268                            rebaseEnabledOverlays(ai, userId);
8269                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8270                        }
8271                    } else {
8272                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8273                        // and already converts to externally visible package name
8274                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8275                                callingUid, effectiveFlags, userId);
8276                    }
8277                    if (ai != null) {
8278                        list.add(ai);
8279                    }
8280                }
8281            } else {
8282                list = new ArrayList<>(mPackages.size());
8283                for (PackageParser.Package p : mPackages.values()) {
8284                    if (p.mExtras != null) {
8285                        PackageSetting ps = (PackageSetting) p.mExtras;
8286                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8287                            continue;
8288                        }
8289                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8290                            return null;
8291                        }
8292                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8293                                ps.readUserState(userId), userId);
8294                        if (ai != null) {
8295                            rebaseEnabledOverlays(ai, userId);
8296                            ai.packageName = resolveExternalPackageNameLPr(p);
8297                            list.add(ai);
8298                        }
8299                    }
8300                }
8301            }
8302
8303            return new ParceledListSlice<>(list);
8304        }
8305    }
8306
8307    @Override
8308    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8309        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8310            return null;
8311        }
8312        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8313                "getEphemeralApplications");
8314        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8315                true /* requireFullPermission */, false /* checkShell */,
8316                "getEphemeralApplications");
8317        synchronized (mPackages) {
8318            List<InstantAppInfo> instantApps = mInstantAppRegistry
8319                    .getInstantAppsLPr(userId);
8320            if (instantApps != null) {
8321                return new ParceledListSlice<>(instantApps);
8322            }
8323        }
8324        return null;
8325    }
8326
8327    @Override
8328    public boolean isInstantApp(String packageName, int userId) {
8329        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8330                true /* requireFullPermission */, false /* checkShell */,
8331                "isInstantApp");
8332        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8333            return false;
8334        }
8335
8336        synchronized (mPackages) {
8337            int callingUid = Binder.getCallingUid();
8338            if (Process.isIsolated(callingUid)) {
8339                callingUid = mIsolatedOwners.get(callingUid);
8340            }
8341            final PackageSetting ps = mSettings.mPackages.get(packageName);
8342            PackageParser.Package pkg = mPackages.get(packageName);
8343            final boolean returnAllowed =
8344                    ps != null
8345                    && (isCallerSameApp(packageName, callingUid)
8346                            || canViewInstantApps(callingUid, userId)
8347                            || mInstantAppRegistry.isInstantAccessGranted(
8348                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8349            if (returnAllowed) {
8350                return ps.getInstantApp(userId);
8351            }
8352        }
8353        return false;
8354    }
8355
8356    @Override
8357    public byte[] getInstantAppCookie(String packageName, int userId) {
8358        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8359            return null;
8360        }
8361
8362        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8363                true /* requireFullPermission */, false /* checkShell */,
8364                "getInstantAppCookie");
8365        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8366            return null;
8367        }
8368        synchronized (mPackages) {
8369            return mInstantAppRegistry.getInstantAppCookieLPw(
8370                    packageName, userId);
8371        }
8372    }
8373
8374    @Override
8375    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8376        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8377            return true;
8378        }
8379
8380        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8381                true /* requireFullPermission */, true /* checkShell */,
8382                "setInstantAppCookie");
8383        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8384            return false;
8385        }
8386        synchronized (mPackages) {
8387            return mInstantAppRegistry.setInstantAppCookieLPw(
8388                    packageName, cookie, userId);
8389        }
8390    }
8391
8392    @Override
8393    public Bitmap getInstantAppIcon(String packageName, int userId) {
8394        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8395            return null;
8396        }
8397
8398        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8399                "getInstantAppIcon");
8400
8401        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8402                true /* requireFullPermission */, false /* checkShell */,
8403                "getInstantAppIcon");
8404
8405        synchronized (mPackages) {
8406            return mInstantAppRegistry.getInstantAppIconLPw(
8407                    packageName, userId);
8408        }
8409    }
8410
8411    private boolean isCallerSameApp(String packageName, int uid) {
8412        PackageParser.Package pkg = mPackages.get(packageName);
8413        return pkg != null
8414                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8415    }
8416
8417    @Override
8418    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8419        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8420            return ParceledListSlice.emptyList();
8421        }
8422        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8423    }
8424
8425    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8426        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8427
8428        // reader
8429        synchronized (mPackages) {
8430            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8431            final int userId = UserHandle.getCallingUserId();
8432            while (i.hasNext()) {
8433                final PackageParser.Package p = i.next();
8434                if (p.applicationInfo == null) continue;
8435
8436                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8437                        && !p.applicationInfo.isDirectBootAware();
8438                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8439                        && p.applicationInfo.isDirectBootAware();
8440
8441                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8442                        && (!mSafeMode || isSystemApp(p))
8443                        && (matchesUnaware || matchesAware)) {
8444                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8445                    if (ps != null) {
8446                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8447                                ps.readUserState(userId), userId);
8448                        if (ai != null) {
8449                            rebaseEnabledOverlays(ai, userId);
8450                            finalList.add(ai);
8451                        }
8452                    }
8453                }
8454            }
8455        }
8456
8457        return finalList;
8458    }
8459
8460    @Override
8461    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8462        if (!sUserManager.exists(userId)) return null;
8463        flags = updateFlagsForComponent(flags, userId, name);
8464        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8465        // reader
8466        synchronized (mPackages) {
8467            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8468            PackageSetting ps = provider != null
8469                    ? mSettings.mPackages.get(provider.owner.packageName)
8470                    : null;
8471            if (ps != null) {
8472                final boolean isInstantApp = ps.getInstantApp(userId);
8473                // normal application; filter out instant application provider
8474                if (instantAppPkgName == null && isInstantApp) {
8475                    return null;
8476                }
8477                // instant application; filter out other instant applications
8478                if (instantAppPkgName != null
8479                        && isInstantApp
8480                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8481                    return null;
8482                }
8483                // instant application; filter out non-exposed provider
8484                if (instantAppPkgName != null
8485                        && !isInstantApp
8486                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8487                    return null;
8488                }
8489                // provider not enabled
8490                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8491                    return null;
8492                }
8493                return PackageParser.generateProviderInfo(
8494                        provider, flags, ps.readUserState(userId), userId);
8495            }
8496            return null;
8497        }
8498    }
8499
8500    /**
8501     * @deprecated
8502     */
8503    @Deprecated
8504    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8505        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8506            return;
8507        }
8508        // reader
8509        synchronized (mPackages) {
8510            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8511                    .entrySet().iterator();
8512            final int userId = UserHandle.getCallingUserId();
8513            while (i.hasNext()) {
8514                Map.Entry<String, PackageParser.Provider> entry = i.next();
8515                PackageParser.Provider p = entry.getValue();
8516                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8517
8518                if (ps != null && p.syncable
8519                        && (!mSafeMode || (p.info.applicationInfo.flags
8520                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8521                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8522                            ps.readUserState(userId), userId);
8523                    if (info != null) {
8524                        outNames.add(entry.getKey());
8525                        outInfo.add(info);
8526                    }
8527                }
8528            }
8529        }
8530    }
8531
8532    @Override
8533    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8534            int uid, int flags, String metaDataKey) {
8535        final int callingUid = Binder.getCallingUid();
8536        final int userId = processName != null ? UserHandle.getUserId(uid)
8537                : UserHandle.getCallingUserId();
8538        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8539        flags = updateFlagsForComponent(flags, userId, processName);
8540        ArrayList<ProviderInfo> finalList = null;
8541        // reader
8542        synchronized (mPackages) {
8543            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8544            while (i.hasNext()) {
8545                final PackageParser.Provider p = i.next();
8546                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8547                if (ps != null && p.info.authority != null
8548                        && (processName == null
8549                                || (p.info.processName.equals(processName)
8550                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8551                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8552
8553                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8554                    // parameter.
8555                    if (metaDataKey != null
8556                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8557                        continue;
8558                    }
8559                    final ComponentName component =
8560                            new ComponentName(p.info.packageName, p.info.name);
8561                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8562                        continue;
8563                    }
8564                    if (finalList == null) {
8565                        finalList = new ArrayList<ProviderInfo>(3);
8566                    }
8567                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8568                            ps.readUserState(userId), userId);
8569                    if (info != null) {
8570                        finalList.add(info);
8571                    }
8572                }
8573            }
8574        }
8575
8576        if (finalList != null) {
8577            Collections.sort(finalList, mProviderInitOrderSorter);
8578            return new ParceledListSlice<ProviderInfo>(finalList);
8579        }
8580
8581        return ParceledListSlice.emptyList();
8582    }
8583
8584    @Override
8585    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8586        // reader
8587        synchronized (mPackages) {
8588            final int callingUid = Binder.getCallingUid();
8589            final int callingUserId = UserHandle.getUserId(callingUid);
8590            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8591            if (ps == null) return null;
8592            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8593                return null;
8594            }
8595            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8596            return PackageParser.generateInstrumentationInfo(i, flags);
8597        }
8598    }
8599
8600    @Override
8601    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8602            String targetPackage, int flags) {
8603        final int callingUid = Binder.getCallingUid();
8604        final int callingUserId = UserHandle.getUserId(callingUid);
8605        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8606        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8607            return ParceledListSlice.emptyList();
8608        }
8609        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8610    }
8611
8612    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8613            int flags) {
8614        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8615
8616        // reader
8617        synchronized (mPackages) {
8618            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8619            while (i.hasNext()) {
8620                final PackageParser.Instrumentation p = i.next();
8621                if (targetPackage == null
8622                        || targetPackage.equals(p.info.targetPackage)) {
8623                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8624                            flags);
8625                    if (ii != null) {
8626                        finalList.add(ii);
8627                    }
8628                }
8629            }
8630        }
8631
8632        return finalList;
8633    }
8634
8635    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8636        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8637        try {
8638            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8639        } finally {
8640            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8641        }
8642    }
8643
8644    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8645        final File[] files = dir.listFiles();
8646        if (ArrayUtils.isEmpty(files)) {
8647            Log.d(TAG, "No files in app dir " + dir);
8648            return;
8649        }
8650
8651        if (DEBUG_PACKAGE_SCANNING) {
8652            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8653                    + " flags=0x" + Integer.toHexString(parseFlags));
8654        }
8655        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8656                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8657                mParallelPackageParserCallback);
8658
8659        // Submit files for parsing in parallel
8660        int fileCount = 0;
8661        for (File file : files) {
8662            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8663                    && !PackageInstallerService.isStageName(file.getName());
8664            if (!isPackage) {
8665                // Ignore entries which are not packages
8666                continue;
8667            }
8668            parallelPackageParser.submit(file, parseFlags);
8669            fileCount++;
8670        }
8671
8672        // Process results one by one
8673        for (; fileCount > 0; fileCount--) {
8674            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8675            Throwable throwable = parseResult.throwable;
8676            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8677
8678            if (throwable == null) {
8679                // Static shared libraries have synthetic package names
8680                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8681                    renameStaticSharedLibraryPackage(parseResult.pkg);
8682                }
8683                try {
8684                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8685                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8686                                currentTime, null);
8687                    }
8688                } catch (PackageManagerException e) {
8689                    errorCode = e.error;
8690                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8691                }
8692            } else if (throwable instanceof PackageParser.PackageParserException) {
8693                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8694                        throwable;
8695                errorCode = e.error;
8696                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8697            } else {
8698                throw new IllegalStateException("Unexpected exception occurred while parsing "
8699                        + parseResult.scanFile, throwable);
8700            }
8701
8702            // Delete invalid userdata apps
8703            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8704                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8705                logCriticalInfo(Log.WARN,
8706                        "Deleting invalid package at " + parseResult.scanFile);
8707                removeCodePathLI(parseResult.scanFile);
8708            }
8709        }
8710        parallelPackageParser.close();
8711    }
8712
8713    private static File getSettingsProblemFile() {
8714        File dataDir = Environment.getDataDirectory();
8715        File systemDir = new File(dataDir, "system");
8716        File fname = new File(systemDir, "uiderrors.txt");
8717        return fname;
8718    }
8719
8720    static void reportSettingsProblem(int priority, String msg) {
8721        logCriticalInfo(priority, msg);
8722    }
8723
8724    public static void logCriticalInfo(int priority, String msg) {
8725        Slog.println(priority, TAG, msg);
8726        EventLogTags.writePmCriticalInfo(msg);
8727        try {
8728            File fname = getSettingsProblemFile();
8729            FileOutputStream out = new FileOutputStream(fname, true);
8730            PrintWriter pw = new FastPrintWriter(out);
8731            SimpleDateFormat formatter = new SimpleDateFormat();
8732            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8733            pw.println(dateString + ": " + msg);
8734            pw.close();
8735            FileUtils.setPermissions(
8736                    fname.toString(),
8737                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8738                    -1, -1);
8739        } catch (java.io.IOException e) {
8740        }
8741    }
8742
8743    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8744        if (srcFile.isDirectory()) {
8745            final File baseFile = new File(pkg.baseCodePath);
8746            long maxModifiedTime = baseFile.lastModified();
8747            if (pkg.splitCodePaths != null) {
8748                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8749                    final File splitFile = new File(pkg.splitCodePaths[i]);
8750                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8751                }
8752            }
8753            return maxModifiedTime;
8754        }
8755        return srcFile.lastModified();
8756    }
8757
8758    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8759            final int policyFlags) throws PackageManagerException {
8760        // When upgrading from pre-N MR1, verify the package time stamp using the package
8761        // directory and not the APK file.
8762        final long lastModifiedTime = mIsPreNMR1Upgrade
8763                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8764        if (ps != null
8765                && ps.codePath.equals(srcFile)
8766                && ps.timeStamp == lastModifiedTime
8767                && !isCompatSignatureUpdateNeeded(pkg)
8768                && !isRecoverSignatureUpdateNeeded(pkg)) {
8769            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8770            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8771            ArraySet<PublicKey> signingKs;
8772            synchronized (mPackages) {
8773                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8774            }
8775            if (ps.signatures.mSignatures != null
8776                    && ps.signatures.mSignatures.length != 0
8777                    && signingKs != null) {
8778                // Optimization: reuse the existing cached certificates
8779                // if the package appears to be unchanged.
8780                pkg.mSignatures = ps.signatures.mSignatures;
8781                pkg.mSigningKeys = signingKs;
8782                return;
8783            }
8784
8785            Slog.w(TAG, "PackageSetting for " + ps.name
8786                    + " is missing signatures.  Collecting certs again to recover them.");
8787        } else {
8788            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8789        }
8790
8791        try {
8792            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8793            PackageParser.collectCertificates(pkg, policyFlags);
8794        } catch (PackageParserException e) {
8795            throw PackageManagerException.from(e);
8796        } finally {
8797            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8798        }
8799    }
8800
8801    /**
8802     *  Traces a package scan.
8803     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8804     */
8805    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8806            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8807        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8808        try {
8809            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8810        } finally {
8811            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8812        }
8813    }
8814
8815    /**
8816     *  Scans a package and returns the newly parsed package.
8817     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8818     */
8819    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8820            long currentTime, UserHandle user) throws PackageManagerException {
8821        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8822        PackageParser pp = new PackageParser();
8823        pp.setSeparateProcesses(mSeparateProcesses);
8824        pp.setOnlyCoreApps(mOnlyCore);
8825        pp.setDisplayMetrics(mMetrics);
8826        pp.setCallback(mPackageParserCallback);
8827
8828        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8829            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8830        }
8831
8832        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8833        final PackageParser.Package pkg;
8834        try {
8835            pkg = pp.parsePackage(scanFile, parseFlags);
8836        } catch (PackageParserException e) {
8837            throw PackageManagerException.from(e);
8838        } finally {
8839            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8840        }
8841
8842        // Static shared libraries have synthetic package names
8843        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8844            renameStaticSharedLibraryPackage(pkg);
8845        }
8846
8847        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8848    }
8849
8850    /**
8851     *  Scans a package and returns the newly parsed package.
8852     *  @throws PackageManagerException on a parse error.
8853     */
8854    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8855            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8856            throws PackageManagerException {
8857        // If the package has children and this is the first dive in the function
8858        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8859        // packages (parent and children) would be successfully scanned before the
8860        // actual scan since scanning mutates internal state and we want to atomically
8861        // install the package and its children.
8862        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8863            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8864                scanFlags |= SCAN_CHECK_ONLY;
8865            }
8866        } else {
8867            scanFlags &= ~SCAN_CHECK_ONLY;
8868        }
8869
8870        // Scan the parent
8871        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8872                scanFlags, currentTime, user);
8873
8874        // Scan the children
8875        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8876        for (int i = 0; i < childCount; i++) {
8877            PackageParser.Package childPackage = pkg.childPackages.get(i);
8878            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8879                    currentTime, user);
8880        }
8881
8882
8883        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8884            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8885        }
8886
8887        return scannedPkg;
8888    }
8889
8890    /**
8891     *  Scans a package and returns the newly parsed package.
8892     *  @throws PackageManagerException on a parse error.
8893     */
8894    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8895            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8896            throws PackageManagerException {
8897        PackageSetting ps = null;
8898        PackageSetting updatedPkg;
8899        // reader
8900        synchronized (mPackages) {
8901            // Look to see if we already know about this package.
8902            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8903            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8904                // This package has been renamed to its original name.  Let's
8905                // use that.
8906                ps = mSettings.getPackageLPr(oldName);
8907            }
8908            // If there was no original package, see one for the real package name.
8909            if (ps == null) {
8910                ps = mSettings.getPackageLPr(pkg.packageName);
8911            }
8912            // Check to see if this package could be hiding/updating a system
8913            // package.  Must look for it either under the original or real
8914            // package name depending on our state.
8915            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8916            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8917
8918            // If this is a package we don't know about on the system partition, we
8919            // may need to remove disabled child packages on the system partition
8920            // or may need to not add child packages if the parent apk is updated
8921            // on the data partition and no longer defines this child package.
8922            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8923                // If this is a parent package for an updated system app and this system
8924                // app got an OTA update which no longer defines some of the child packages
8925                // we have to prune them from the disabled system packages.
8926                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8927                if (disabledPs != null) {
8928                    final int scannedChildCount = (pkg.childPackages != null)
8929                            ? pkg.childPackages.size() : 0;
8930                    final int disabledChildCount = disabledPs.childPackageNames != null
8931                            ? disabledPs.childPackageNames.size() : 0;
8932                    for (int i = 0; i < disabledChildCount; i++) {
8933                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8934                        boolean disabledPackageAvailable = false;
8935                        for (int j = 0; j < scannedChildCount; j++) {
8936                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8937                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8938                                disabledPackageAvailable = true;
8939                                break;
8940                            }
8941                         }
8942                         if (!disabledPackageAvailable) {
8943                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8944                         }
8945                    }
8946                }
8947            }
8948        }
8949
8950        boolean updatedPkgBetter = false;
8951        // First check if this is a system package that may involve an update
8952        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8953            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8954            // it needs to drop FLAG_PRIVILEGED.
8955            if (locationIsPrivileged(scanFile)) {
8956                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8957            } else {
8958                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8959            }
8960
8961            if (ps != null && !ps.codePath.equals(scanFile)) {
8962                // The path has changed from what was last scanned...  check the
8963                // version of the new path against what we have stored to determine
8964                // what to do.
8965                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8966                if (pkg.mVersionCode <= ps.versionCode) {
8967                    // The system package has been updated and the code path does not match
8968                    // Ignore entry. Skip it.
8969                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8970                            + " ignored: updated version " + ps.versionCode
8971                            + " better than this " + pkg.mVersionCode);
8972                    if (!updatedPkg.codePath.equals(scanFile)) {
8973                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8974                                + ps.name + " changing from " + updatedPkg.codePathString
8975                                + " to " + scanFile);
8976                        updatedPkg.codePath = scanFile;
8977                        updatedPkg.codePathString = scanFile.toString();
8978                        updatedPkg.resourcePath = scanFile;
8979                        updatedPkg.resourcePathString = scanFile.toString();
8980                    }
8981                    updatedPkg.pkg = pkg;
8982                    updatedPkg.versionCode = pkg.mVersionCode;
8983
8984                    // Update the disabled system child packages to point to the package too.
8985                    final int childCount = updatedPkg.childPackageNames != null
8986                            ? updatedPkg.childPackageNames.size() : 0;
8987                    for (int i = 0; i < childCount; i++) {
8988                        String childPackageName = updatedPkg.childPackageNames.get(i);
8989                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8990                                childPackageName);
8991                        if (updatedChildPkg != null) {
8992                            updatedChildPkg.pkg = pkg;
8993                            updatedChildPkg.versionCode = pkg.mVersionCode;
8994                        }
8995                    }
8996
8997                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8998                            + scanFile + " ignored: updated version " + ps.versionCode
8999                            + " better than this " + pkg.mVersionCode);
9000                } else {
9001                    // The current app on the system partition is better than
9002                    // what we have updated to on the data partition; switch
9003                    // back to the system partition version.
9004                    // At this point, its safely assumed that package installation for
9005                    // apps in system partition will go through. If not there won't be a working
9006                    // version of the app
9007                    // writer
9008                    synchronized (mPackages) {
9009                        // Just remove the loaded entries from package lists.
9010                        mPackages.remove(ps.name);
9011                    }
9012
9013                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9014                            + " reverting from " + ps.codePathString
9015                            + ": new version " + pkg.mVersionCode
9016                            + " better than installed " + ps.versionCode);
9017
9018                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9019                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9020                    synchronized (mInstallLock) {
9021                        args.cleanUpResourcesLI();
9022                    }
9023                    synchronized (mPackages) {
9024                        mSettings.enableSystemPackageLPw(ps.name);
9025                    }
9026                    updatedPkgBetter = true;
9027                }
9028            }
9029        }
9030
9031        if (updatedPkg != null) {
9032            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9033            // initially
9034            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9035
9036            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9037            // flag set initially
9038            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9039                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9040            }
9041        }
9042
9043        // Verify certificates against what was last scanned
9044        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9045
9046        /*
9047         * A new system app appeared, but we already had a non-system one of the
9048         * same name installed earlier.
9049         */
9050        boolean shouldHideSystemApp = false;
9051        if (updatedPkg == null && ps != null
9052                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9053            /*
9054             * Check to make sure the signatures match first. If they don't,
9055             * wipe the installed application and its data.
9056             */
9057            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9058                    != PackageManager.SIGNATURE_MATCH) {
9059                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9060                        + " signatures don't match existing userdata copy; removing");
9061                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9062                        "scanPackageInternalLI")) {
9063                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9064                }
9065                ps = null;
9066            } else {
9067                /*
9068                 * If the newly-added system app is an older version than the
9069                 * already installed version, hide it. It will be scanned later
9070                 * and re-added like an update.
9071                 */
9072                if (pkg.mVersionCode <= ps.versionCode) {
9073                    shouldHideSystemApp = true;
9074                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9075                            + " but new version " + pkg.mVersionCode + " better than installed "
9076                            + ps.versionCode + "; hiding system");
9077                } else {
9078                    /*
9079                     * The newly found system app is a newer version that the
9080                     * one previously installed. Simply remove the
9081                     * already-installed application and replace it with our own
9082                     * while keeping the application data.
9083                     */
9084                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9085                            + " reverting from " + ps.codePathString + ": new version "
9086                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9087                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9088                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9089                    synchronized (mInstallLock) {
9090                        args.cleanUpResourcesLI();
9091                    }
9092                }
9093            }
9094        }
9095
9096        // The apk is forward locked (not public) if its code and resources
9097        // are kept in different files. (except for app in either system or
9098        // vendor path).
9099        // TODO grab this value from PackageSettings
9100        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9101            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9102                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9103            }
9104        }
9105
9106        // TODO: extend to support forward-locked splits
9107        String resourcePath = null;
9108        String baseResourcePath = null;
9109        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
9110            if (ps != null && ps.resourcePathString != null) {
9111                resourcePath = ps.resourcePathString;
9112                baseResourcePath = ps.resourcePathString;
9113            } else {
9114                // Should not happen at all. Just log an error.
9115                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9116            }
9117        } else {
9118            resourcePath = pkg.codePath;
9119            baseResourcePath = pkg.baseCodePath;
9120        }
9121
9122        // Set application objects path explicitly.
9123        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9124        pkg.setApplicationInfoCodePath(pkg.codePath);
9125        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9126        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9127        pkg.setApplicationInfoResourcePath(resourcePath);
9128        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9129        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9130
9131        final int userId = ((user == null) ? 0 : user.getIdentifier());
9132        if (ps != null && ps.getInstantApp(userId)) {
9133            scanFlags |= SCAN_AS_INSTANT_APP;
9134        }
9135
9136        // Note that we invoke the following method only if we are about to unpack an application
9137        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9138                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9139
9140        /*
9141         * If the system app should be overridden by a previously installed
9142         * data, hide the system app now and let the /data/app scan pick it up
9143         * again.
9144         */
9145        if (shouldHideSystemApp) {
9146            synchronized (mPackages) {
9147                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9148            }
9149        }
9150
9151        return scannedPkg;
9152    }
9153
9154    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9155        // Derive the new package synthetic package name
9156        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9157                + pkg.staticSharedLibVersion);
9158    }
9159
9160    private static String fixProcessName(String defProcessName,
9161            String processName) {
9162        if (processName == null) {
9163            return defProcessName;
9164        }
9165        return processName;
9166    }
9167
9168    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9169            throws PackageManagerException {
9170        if (pkgSetting.signatures.mSignatures != null) {
9171            // Already existing package. Make sure signatures match
9172            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9173                    == PackageManager.SIGNATURE_MATCH;
9174            if (!match) {
9175                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9176                        == PackageManager.SIGNATURE_MATCH;
9177            }
9178            if (!match) {
9179                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9180                        == PackageManager.SIGNATURE_MATCH;
9181            }
9182            if (!match) {
9183                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9184                        + pkg.packageName + " signatures do not match the "
9185                        + "previously installed version; ignoring!");
9186            }
9187        }
9188
9189        // Check for shared user signatures
9190        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9191            // Already existing package. Make sure signatures match
9192            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9193                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9194            if (!match) {
9195                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9196                        == PackageManager.SIGNATURE_MATCH;
9197            }
9198            if (!match) {
9199                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9200                        == PackageManager.SIGNATURE_MATCH;
9201            }
9202            if (!match) {
9203                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9204                        "Package " + pkg.packageName
9205                        + " has no signatures that match those in shared user "
9206                        + pkgSetting.sharedUser.name + "; ignoring!");
9207            }
9208        }
9209    }
9210
9211    /**
9212     * Enforces that only the system UID or root's UID can call a method exposed
9213     * via Binder.
9214     *
9215     * @param message used as message if SecurityException is thrown
9216     * @throws SecurityException if the caller is not system or root
9217     */
9218    private static final void enforceSystemOrRoot(String message) {
9219        final int uid = Binder.getCallingUid();
9220        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9221            throw new SecurityException(message);
9222        }
9223    }
9224
9225    @Override
9226    public void performFstrimIfNeeded() {
9227        enforceSystemOrRoot("Only the system can request fstrim");
9228
9229        // Before everything else, see whether we need to fstrim.
9230        try {
9231            IStorageManager sm = PackageHelper.getStorageManager();
9232            if (sm != null) {
9233                boolean doTrim = false;
9234                final long interval = android.provider.Settings.Global.getLong(
9235                        mContext.getContentResolver(),
9236                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9237                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9238                if (interval > 0) {
9239                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9240                    if (timeSinceLast > interval) {
9241                        doTrim = true;
9242                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9243                                + "; running immediately");
9244                    }
9245                }
9246                if (doTrim) {
9247                    final boolean dexOptDialogShown;
9248                    synchronized (mPackages) {
9249                        dexOptDialogShown = mDexOptDialogShown;
9250                    }
9251                    if (!isFirstBoot() && dexOptDialogShown) {
9252                        try {
9253                            ActivityManager.getService().showBootMessage(
9254                                    mContext.getResources().getString(
9255                                            R.string.android_upgrading_fstrim), true);
9256                        } catch (RemoteException e) {
9257                        }
9258                    }
9259                    sm.runMaintenance();
9260                }
9261            } else {
9262                Slog.e(TAG, "storageManager service unavailable!");
9263            }
9264        } catch (RemoteException e) {
9265            // Can't happen; StorageManagerService is local
9266        }
9267    }
9268
9269    @Override
9270    public void updatePackagesIfNeeded() {
9271        enforceSystemOrRoot("Only the system can request package update");
9272
9273        // We need to re-extract after an OTA.
9274        boolean causeUpgrade = isUpgrade();
9275
9276        // First boot or factory reset.
9277        // Note: we also handle devices that are upgrading to N right now as if it is their
9278        //       first boot, as they do not have profile data.
9279        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9280
9281        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9282        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9283
9284        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9285            return;
9286        }
9287
9288        List<PackageParser.Package> pkgs;
9289        synchronized (mPackages) {
9290            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9291        }
9292
9293        final long startTime = System.nanoTime();
9294        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9295                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9296                    false /* bootComplete */);
9297
9298        final int elapsedTimeSeconds =
9299                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9300
9301        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9302        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9303        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9304        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9305        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9306    }
9307
9308    /*
9309     * Return the prebuilt profile path given a package base code path.
9310     */
9311    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9312        return pkg.baseCodePath + ".prof";
9313    }
9314
9315    /**
9316     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9317     * containing statistics about the invocation. The array consists of three elements,
9318     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9319     * and {@code numberOfPackagesFailed}.
9320     */
9321    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9322            String compilerFilter, boolean bootComplete) {
9323
9324        int numberOfPackagesVisited = 0;
9325        int numberOfPackagesOptimized = 0;
9326        int numberOfPackagesSkipped = 0;
9327        int numberOfPackagesFailed = 0;
9328        final int numberOfPackagesToDexopt = pkgs.size();
9329
9330        for (PackageParser.Package pkg : pkgs) {
9331            numberOfPackagesVisited++;
9332
9333            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9334                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9335                // that are already compiled.
9336                File profileFile = new File(getPrebuildProfilePath(pkg));
9337                // Copy profile if it exists.
9338                if (profileFile.exists()) {
9339                    try {
9340                        // We could also do this lazily before calling dexopt in
9341                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9342                        // is that we don't have a good way to say "do this only once".
9343                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9344                                pkg.applicationInfo.uid, pkg.packageName)) {
9345                            Log.e(TAG, "Installer failed to copy system profile!");
9346                        }
9347                    } catch (Exception e) {
9348                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9349                                e);
9350                    }
9351                }
9352            }
9353
9354            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9355                if (DEBUG_DEXOPT) {
9356                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9357                }
9358                numberOfPackagesSkipped++;
9359                continue;
9360            }
9361
9362            if (DEBUG_DEXOPT) {
9363                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9364                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9365            }
9366
9367            if (showDialog) {
9368                try {
9369                    ActivityManager.getService().showBootMessage(
9370                            mContext.getResources().getString(R.string.android_upgrading_apk,
9371                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9372                } catch (RemoteException e) {
9373                }
9374                synchronized (mPackages) {
9375                    mDexOptDialogShown = true;
9376                }
9377            }
9378
9379            // If the OTA updates a system app which was previously preopted to a non-preopted state
9380            // the app might end up being verified at runtime. That's because by default the apps
9381            // are verify-profile but for preopted apps there's no profile.
9382            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9383            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9384            // filter (by default 'quicken').
9385            // Note that at this stage unused apps are already filtered.
9386            if (isSystemApp(pkg) &&
9387                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9388                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9389                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9390            }
9391
9392            // checkProfiles is false to avoid merging profiles during boot which
9393            // might interfere with background compilation (b/28612421).
9394            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9395            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9396            // trade-off worth doing to save boot time work.
9397            int dexOptStatus = performDexOptTraced(pkg.packageName,
9398                    false /* checkProfiles */,
9399                    compilerFilter,
9400                    false /* force */,
9401                    bootComplete);
9402            switch (dexOptStatus) {
9403                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9404                    numberOfPackagesOptimized++;
9405                    break;
9406                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9407                    numberOfPackagesSkipped++;
9408                    break;
9409                case PackageDexOptimizer.DEX_OPT_FAILED:
9410                    numberOfPackagesFailed++;
9411                    break;
9412                default:
9413                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9414                    break;
9415            }
9416        }
9417
9418        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9419                numberOfPackagesFailed };
9420    }
9421
9422    @Override
9423    public void notifyPackageUse(String packageName, int reason) {
9424        synchronized (mPackages) {
9425            final int callingUid = Binder.getCallingUid();
9426            final int callingUserId = UserHandle.getUserId(callingUid);
9427            if (getInstantAppPackageName(callingUid) != null) {
9428                if (!isCallerSameApp(packageName, callingUid)) {
9429                    return;
9430                }
9431            } else {
9432                if (isInstantApp(packageName, callingUserId)) {
9433                    return;
9434                }
9435            }
9436            final PackageParser.Package p = mPackages.get(packageName);
9437            if (p == null) {
9438                return;
9439            }
9440            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9441        }
9442    }
9443
9444    @Override
9445    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9446        int userId = UserHandle.getCallingUserId();
9447        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9448        if (ai == null) {
9449            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9450                + loadingPackageName + ", user=" + userId);
9451            return;
9452        }
9453        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9454    }
9455
9456    @Override
9457    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9458            IDexModuleRegisterCallback callback) {
9459        int userId = UserHandle.getCallingUserId();
9460        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9461        DexManager.RegisterDexModuleResult result;
9462        if (ai == null) {
9463            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9464                     " calling user. package=" + packageName + ", user=" + userId);
9465            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9466        } else {
9467            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9468        }
9469
9470        if (callback != null) {
9471            mHandler.post(() -> {
9472                try {
9473                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9474                } catch (RemoteException e) {
9475                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9476                }
9477            });
9478        }
9479    }
9480
9481    @Override
9482    public boolean performDexOpt(String packageName,
9483            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9484        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9485            return false;
9486        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9487            return false;
9488        }
9489        int dexoptStatus = performDexOptWithStatus(
9490              packageName, checkProfiles, compileReason, force, bootComplete);
9491        return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9492    }
9493
9494    /**
9495     * Perform dexopt on the given package and return one of following result:
9496     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9497     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9498     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9499     */
9500    /* package */ int performDexOptWithStatus(String packageName,
9501            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9502        return performDexOptTraced(packageName, checkProfiles,
9503                getCompilerFilterForReason(compileReason), force, bootComplete);
9504    }
9505
9506    @Override
9507    public boolean performDexOptMode(String packageName,
9508            boolean checkProfiles, String targetCompilerFilter, boolean force,
9509            boolean bootComplete) {
9510        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9511            return false;
9512        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9513            return false;
9514        }
9515        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9516                targetCompilerFilter, force, bootComplete);
9517        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9518    }
9519
9520    private int performDexOptTraced(String packageName,
9521                boolean checkProfiles, String targetCompilerFilter, boolean force,
9522                boolean bootComplete) {
9523        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9524        try {
9525            return performDexOptInternal(packageName, checkProfiles,
9526                    targetCompilerFilter, force, bootComplete);
9527        } finally {
9528            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9529        }
9530    }
9531
9532    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9533    // if the package can now be considered up to date for the given filter.
9534    private int performDexOptInternal(String packageName,
9535                boolean checkProfiles, String targetCompilerFilter, boolean force,
9536                boolean bootComplete) {
9537        PackageParser.Package p;
9538        synchronized (mPackages) {
9539            p = mPackages.get(packageName);
9540            if (p == null) {
9541                // Package could not be found. Report failure.
9542                return PackageDexOptimizer.DEX_OPT_FAILED;
9543            }
9544            mPackageUsage.maybeWriteAsync(mPackages);
9545            mCompilerStats.maybeWriteAsync();
9546        }
9547        long callingId = Binder.clearCallingIdentity();
9548        try {
9549            synchronized (mInstallLock) {
9550                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9551                        targetCompilerFilter, force, bootComplete);
9552            }
9553        } finally {
9554            Binder.restoreCallingIdentity(callingId);
9555        }
9556    }
9557
9558    public ArraySet<String> getOptimizablePackages() {
9559        ArraySet<String> pkgs = new ArraySet<String>();
9560        synchronized (mPackages) {
9561            for (PackageParser.Package p : mPackages.values()) {
9562                if (PackageDexOptimizer.canOptimizePackage(p)) {
9563                    pkgs.add(p.packageName);
9564                }
9565            }
9566        }
9567        return pkgs;
9568    }
9569
9570    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9571            boolean checkProfiles, String targetCompilerFilter,
9572            boolean force, boolean bootComplete) {
9573        // Select the dex optimizer based on the force parameter.
9574        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9575        //       allocate an object here.
9576        PackageDexOptimizer pdo = force
9577                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9578                : mPackageDexOptimizer;
9579
9580        // Dexopt all dependencies first. Note: we ignore the return value and march on
9581        // on errors.
9582        // Note that we are going to call performDexOpt on those libraries as many times as
9583        // they are referenced in packages. When we do a batch of performDexOpt (for example
9584        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9585        // and the first package that uses the library will dexopt it. The
9586        // others will see that the compiled code for the library is up to date.
9587        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9588        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9589        if (!deps.isEmpty()) {
9590            for (PackageParser.Package depPackage : deps) {
9591                // TODO: Analyze and investigate if we (should) profile libraries.
9592                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9593                        false /* checkProfiles */,
9594                        targetCompilerFilter,
9595                        getOrCreateCompilerPackageStats(depPackage),
9596                        true /* isUsedByOtherApps */,
9597                        bootComplete);
9598            }
9599        }
9600        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9601                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9602                mDexManager.isUsedByOtherApps(p.packageName), bootComplete);
9603    }
9604
9605    // Performs dexopt on the used secondary dex files belonging to the given package.
9606    // Returns true if all dex files were process successfully (which could mean either dexopt or
9607    // skip). Returns false if any of the files caused errors.
9608    @Override
9609    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9610            boolean force) {
9611        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9612            return false;
9613        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9614            return false;
9615        }
9616        mDexManager.reconcileSecondaryDexFiles(packageName);
9617        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9618    }
9619
9620    public boolean performDexOptSecondary(String packageName, int compileReason,
9621            boolean force) {
9622        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9623    }
9624
9625    /**
9626     * Reconcile the information we have about the secondary dex files belonging to
9627     * {@code packagName} and the actual dex files. For all dex files that were
9628     * deleted, update the internal records and delete the generated oat files.
9629     */
9630    @Override
9631    public void reconcileSecondaryDexFiles(String packageName) {
9632        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9633            return;
9634        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9635            return;
9636        }
9637        mDexManager.reconcileSecondaryDexFiles(packageName);
9638    }
9639
9640    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9641    // a reference there.
9642    /*package*/ DexManager getDexManager() {
9643        return mDexManager;
9644    }
9645
9646    /**
9647     * Execute the background dexopt job immediately.
9648     */
9649    @Override
9650    public boolean runBackgroundDexoptJob() {
9651        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9652            return false;
9653        }
9654        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9655    }
9656
9657    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9658        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9659                || p.usesStaticLibraries != null) {
9660            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9661            Set<String> collectedNames = new HashSet<>();
9662            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9663
9664            retValue.remove(p);
9665
9666            return retValue;
9667        } else {
9668            return Collections.emptyList();
9669        }
9670    }
9671
9672    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9673            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9674        if (!collectedNames.contains(p.packageName)) {
9675            collectedNames.add(p.packageName);
9676            collected.add(p);
9677
9678            if (p.usesLibraries != null) {
9679                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9680                        null, collected, collectedNames);
9681            }
9682            if (p.usesOptionalLibraries != null) {
9683                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9684                        null, collected, collectedNames);
9685            }
9686            if (p.usesStaticLibraries != null) {
9687                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9688                        p.usesStaticLibrariesVersions, collected, collectedNames);
9689            }
9690        }
9691    }
9692
9693    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9694            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9695        final int libNameCount = libs.size();
9696        for (int i = 0; i < libNameCount; i++) {
9697            String libName = libs.get(i);
9698            int version = (versions != null && versions.length == libNameCount)
9699                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9700            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9701            if (libPkg != null) {
9702                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9703            }
9704        }
9705    }
9706
9707    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9708        synchronized (mPackages) {
9709            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9710            if (libEntry != null) {
9711                return mPackages.get(libEntry.apk);
9712            }
9713            return null;
9714        }
9715    }
9716
9717    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9718        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9719        if (versionedLib == null) {
9720            return null;
9721        }
9722        return versionedLib.get(version);
9723    }
9724
9725    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9726        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9727                pkg.staticSharedLibName);
9728        if (versionedLib == null) {
9729            return null;
9730        }
9731        int previousLibVersion = -1;
9732        final int versionCount = versionedLib.size();
9733        for (int i = 0; i < versionCount; i++) {
9734            final int libVersion = versionedLib.keyAt(i);
9735            if (libVersion < pkg.staticSharedLibVersion) {
9736                previousLibVersion = Math.max(previousLibVersion, libVersion);
9737            }
9738        }
9739        if (previousLibVersion >= 0) {
9740            return versionedLib.get(previousLibVersion);
9741        }
9742        return null;
9743    }
9744
9745    public void shutdown() {
9746        mPackageUsage.writeNow(mPackages);
9747        mCompilerStats.writeNow();
9748    }
9749
9750    @Override
9751    public void dumpProfiles(String packageName) {
9752        PackageParser.Package pkg;
9753        synchronized (mPackages) {
9754            pkg = mPackages.get(packageName);
9755            if (pkg == null) {
9756                throw new IllegalArgumentException("Unknown package: " + packageName);
9757            }
9758        }
9759        /* Only the shell, root, or the app user should be able to dump profiles. */
9760        int callingUid = Binder.getCallingUid();
9761        if (callingUid != Process.SHELL_UID &&
9762            callingUid != Process.ROOT_UID &&
9763            callingUid != pkg.applicationInfo.uid) {
9764            throw new SecurityException("dumpProfiles");
9765        }
9766
9767        synchronized (mInstallLock) {
9768            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9769            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9770            try {
9771                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9772                String codePaths = TextUtils.join(";", allCodePaths);
9773                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9774            } catch (InstallerException e) {
9775                Slog.w(TAG, "Failed to dump profiles", e);
9776            }
9777            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9778        }
9779    }
9780
9781    @Override
9782    public void forceDexOpt(String packageName) {
9783        enforceSystemOrRoot("forceDexOpt");
9784
9785        PackageParser.Package pkg;
9786        synchronized (mPackages) {
9787            pkg = mPackages.get(packageName);
9788            if (pkg == null) {
9789                throw new IllegalArgumentException("Unknown package: " + packageName);
9790            }
9791        }
9792
9793        synchronized (mInstallLock) {
9794            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9795
9796            // Whoever is calling forceDexOpt wants a compiled package.
9797            // Don't use profiles since that may cause compilation to be skipped.
9798            final int res = performDexOptInternalWithDependenciesLI(pkg,
9799                    false /* checkProfiles */, getDefaultCompilerFilter(),
9800                    true /* force */,
9801                    true /* bootComplete */);
9802
9803            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9804            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9805                throw new IllegalStateException("Failed to dexopt: " + res);
9806            }
9807        }
9808    }
9809
9810    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9811        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9812            Slog.w(TAG, "Unable to update from " + oldPkg.name
9813                    + " to " + newPkg.packageName
9814                    + ": old package not in system partition");
9815            return false;
9816        } else if (mPackages.get(oldPkg.name) != null) {
9817            Slog.w(TAG, "Unable to update from " + oldPkg.name
9818                    + " to " + newPkg.packageName
9819                    + ": old package still exists");
9820            return false;
9821        }
9822        return true;
9823    }
9824
9825    void removeCodePathLI(File codePath) {
9826        if (codePath.isDirectory()) {
9827            try {
9828                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9829            } catch (InstallerException e) {
9830                Slog.w(TAG, "Failed to remove code path", e);
9831            }
9832        } else {
9833            codePath.delete();
9834        }
9835    }
9836
9837    private int[] resolveUserIds(int userId) {
9838        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9839    }
9840
9841    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9842        if (pkg == null) {
9843            Slog.wtf(TAG, "Package was null!", new Throwable());
9844            return;
9845        }
9846        clearAppDataLeafLIF(pkg, userId, flags);
9847        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9848        for (int i = 0; i < childCount; i++) {
9849            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9850        }
9851    }
9852
9853    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9854        final PackageSetting ps;
9855        synchronized (mPackages) {
9856            ps = mSettings.mPackages.get(pkg.packageName);
9857        }
9858        for (int realUserId : resolveUserIds(userId)) {
9859            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9860            try {
9861                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9862                        ceDataInode);
9863            } catch (InstallerException e) {
9864                Slog.w(TAG, String.valueOf(e));
9865            }
9866        }
9867    }
9868
9869    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9870        if (pkg == null) {
9871            Slog.wtf(TAG, "Package was null!", new Throwable());
9872            return;
9873        }
9874        destroyAppDataLeafLIF(pkg, userId, flags);
9875        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9876        for (int i = 0; i < childCount; i++) {
9877            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9878        }
9879    }
9880
9881    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9882        final PackageSetting ps;
9883        synchronized (mPackages) {
9884            ps = mSettings.mPackages.get(pkg.packageName);
9885        }
9886        for (int realUserId : resolveUserIds(userId)) {
9887            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9888            try {
9889                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9890                        ceDataInode);
9891            } catch (InstallerException e) {
9892                Slog.w(TAG, String.valueOf(e));
9893            }
9894            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9895        }
9896    }
9897
9898    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9899        if (pkg == null) {
9900            Slog.wtf(TAG, "Package was null!", new Throwable());
9901            return;
9902        }
9903        destroyAppProfilesLeafLIF(pkg);
9904        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9905        for (int i = 0; i < childCount; i++) {
9906            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9907        }
9908    }
9909
9910    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9911        try {
9912            mInstaller.destroyAppProfiles(pkg.packageName);
9913        } catch (InstallerException e) {
9914            Slog.w(TAG, String.valueOf(e));
9915        }
9916    }
9917
9918    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9919        if (pkg == null) {
9920            Slog.wtf(TAG, "Package was null!", new Throwable());
9921            return;
9922        }
9923        clearAppProfilesLeafLIF(pkg);
9924        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9925        for (int i = 0; i < childCount; i++) {
9926            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9927        }
9928    }
9929
9930    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9931        try {
9932            mInstaller.clearAppProfiles(pkg.packageName);
9933        } catch (InstallerException e) {
9934            Slog.w(TAG, String.valueOf(e));
9935        }
9936    }
9937
9938    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9939            long lastUpdateTime) {
9940        // Set parent install/update time
9941        PackageSetting ps = (PackageSetting) pkg.mExtras;
9942        if (ps != null) {
9943            ps.firstInstallTime = firstInstallTime;
9944            ps.lastUpdateTime = lastUpdateTime;
9945        }
9946        // Set children install/update time
9947        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9948        for (int i = 0; i < childCount; i++) {
9949            PackageParser.Package childPkg = pkg.childPackages.get(i);
9950            ps = (PackageSetting) childPkg.mExtras;
9951            if (ps != null) {
9952                ps.firstInstallTime = firstInstallTime;
9953                ps.lastUpdateTime = lastUpdateTime;
9954            }
9955        }
9956    }
9957
9958    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9959            PackageParser.Package changingLib) {
9960        if (file.path != null) {
9961            usesLibraryFiles.add(file.path);
9962            return;
9963        }
9964        PackageParser.Package p = mPackages.get(file.apk);
9965        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9966            // If we are doing this while in the middle of updating a library apk,
9967            // then we need to make sure to use that new apk for determining the
9968            // dependencies here.  (We haven't yet finished committing the new apk
9969            // to the package manager state.)
9970            if (p == null || p.packageName.equals(changingLib.packageName)) {
9971                p = changingLib;
9972            }
9973        }
9974        if (p != null) {
9975            usesLibraryFiles.addAll(p.getAllCodePaths());
9976            if (p.usesLibraryFiles != null) {
9977                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9978            }
9979        }
9980    }
9981
9982    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9983            PackageParser.Package changingLib) throws PackageManagerException {
9984        if (pkg == null) {
9985            return;
9986        }
9987        ArraySet<String> usesLibraryFiles = null;
9988        if (pkg.usesLibraries != null) {
9989            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9990                    null, null, pkg.packageName, changingLib, true, null);
9991        }
9992        if (pkg.usesStaticLibraries != null) {
9993            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9994                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9995                    pkg.packageName, changingLib, true, usesLibraryFiles);
9996        }
9997        if (pkg.usesOptionalLibraries != null) {
9998            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9999                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10000        }
10001        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10002            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10003        } else {
10004            pkg.usesLibraryFiles = null;
10005        }
10006    }
10007
10008    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10009            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10010            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10011            boolean required, @Nullable ArraySet<String> outUsedLibraries)
10012            throws PackageManagerException {
10013        final int libCount = requestedLibraries.size();
10014        for (int i = 0; i < libCount; i++) {
10015            final String libName = requestedLibraries.get(i);
10016            final int libVersion = requiredVersions != null ? requiredVersions[i]
10017                    : SharedLibraryInfo.VERSION_UNDEFINED;
10018            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10019            if (libEntry == null) {
10020                if (required) {
10021                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10022                            "Package " + packageName + " requires unavailable shared library "
10023                                    + libName + "; failing!");
10024                } else if (DEBUG_SHARED_LIBRARIES) {
10025                    Slog.i(TAG, "Package " + packageName
10026                            + " desires unavailable shared library "
10027                            + libName + "; ignoring!");
10028                }
10029            } else {
10030                if (requiredVersions != null && requiredCertDigests != null) {
10031                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10032                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10033                            "Package " + packageName + " requires unavailable static shared"
10034                                    + " library " + libName + " version "
10035                                    + libEntry.info.getVersion() + "; failing!");
10036                    }
10037
10038                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10039                    if (libPkg == null) {
10040                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10041                                "Package " + packageName + " requires unavailable static shared"
10042                                        + " library; failing!");
10043                    }
10044
10045                    String expectedCertDigest = requiredCertDigests[i];
10046                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10047                                libPkg.mSignatures[0]);
10048                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10049                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10050                                "Package " + packageName + " requires differently signed" +
10051                                        " static shared library; failing!");
10052                    }
10053                }
10054
10055                if (outUsedLibraries == null) {
10056                    outUsedLibraries = new ArraySet<>();
10057                }
10058                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10059            }
10060        }
10061        return outUsedLibraries;
10062    }
10063
10064    private static boolean hasString(List<String> list, List<String> which) {
10065        if (list == null) {
10066            return false;
10067        }
10068        for (int i=list.size()-1; i>=0; i--) {
10069            for (int j=which.size()-1; j>=0; j--) {
10070                if (which.get(j).equals(list.get(i))) {
10071                    return true;
10072                }
10073            }
10074        }
10075        return false;
10076    }
10077
10078    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10079            PackageParser.Package changingPkg) {
10080        ArrayList<PackageParser.Package> res = null;
10081        for (PackageParser.Package pkg : mPackages.values()) {
10082            if (changingPkg != null
10083                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10084                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10085                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10086                            changingPkg.staticSharedLibName)) {
10087                return null;
10088            }
10089            if (res == null) {
10090                res = new ArrayList<>();
10091            }
10092            res.add(pkg);
10093            try {
10094                updateSharedLibrariesLPr(pkg, changingPkg);
10095            } catch (PackageManagerException e) {
10096                // If a system app update or an app and a required lib missing we
10097                // delete the package and for updated system apps keep the data as
10098                // it is better for the user to reinstall than to be in an limbo
10099                // state. Also libs disappearing under an app should never happen
10100                // - just in case.
10101                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10102                    final int flags = pkg.isUpdatedSystemApp()
10103                            ? PackageManager.DELETE_KEEP_DATA : 0;
10104                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10105                            flags , null, true, null);
10106                }
10107                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10108            }
10109        }
10110        return res;
10111    }
10112
10113    /**
10114     * Derive the value of the {@code cpuAbiOverride} based on the provided
10115     * value and an optional stored value from the package settings.
10116     */
10117    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10118        String cpuAbiOverride = null;
10119
10120        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10121            cpuAbiOverride = null;
10122        } else if (abiOverride != null) {
10123            cpuAbiOverride = abiOverride;
10124        } else if (settings != null) {
10125            cpuAbiOverride = settings.cpuAbiOverrideString;
10126        }
10127
10128        return cpuAbiOverride;
10129    }
10130
10131    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10132            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10133                    throws PackageManagerException {
10134        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10135        // If the package has children and this is the first dive in the function
10136        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10137        // whether all packages (parent and children) would be successfully scanned
10138        // before the actual scan since scanning mutates internal state and we want
10139        // to atomically install the package and its children.
10140        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10141            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10142                scanFlags |= SCAN_CHECK_ONLY;
10143            }
10144        } else {
10145            scanFlags &= ~SCAN_CHECK_ONLY;
10146        }
10147
10148        final PackageParser.Package scannedPkg;
10149        try {
10150            // Scan the parent
10151            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10152            // Scan the children
10153            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10154            for (int i = 0; i < childCount; i++) {
10155                PackageParser.Package childPkg = pkg.childPackages.get(i);
10156                scanPackageLI(childPkg, policyFlags,
10157                        scanFlags, currentTime, user);
10158            }
10159        } finally {
10160            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10161        }
10162
10163        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10164            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10165        }
10166
10167        return scannedPkg;
10168    }
10169
10170    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10171            int scanFlags, long currentTime, @Nullable UserHandle user)
10172                    throws PackageManagerException {
10173        boolean success = false;
10174        try {
10175            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10176                    currentTime, user);
10177            success = true;
10178            return res;
10179        } finally {
10180            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10181                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10182                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10183                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10184                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10185            }
10186        }
10187    }
10188
10189    /**
10190     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10191     */
10192    private static boolean apkHasCode(String fileName) {
10193        StrictJarFile jarFile = null;
10194        try {
10195            jarFile = new StrictJarFile(fileName,
10196                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10197            return jarFile.findEntry("classes.dex") != null;
10198        } catch (IOException ignore) {
10199        } finally {
10200            try {
10201                if (jarFile != null) {
10202                    jarFile.close();
10203                }
10204            } catch (IOException ignore) {}
10205        }
10206        return false;
10207    }
10208
10209    /**
10210     * Enforces code policy for the package. This ensures that if an APK has
10211     * declared hasCode="true" in its manifest that the APK actually contains
10212     * code.
10213     *
10214     * @throws PackageManagerException If bytecode could not be found when it should exist
10215     */
10216    private static void assertCodePolicy(PackageParser.Package pkg)
10217            throws PackageManagerException {
10218        final boolean shouldHaveCode =
10219                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10220        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10221            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10222                    "Package " + pkg.baseCodePath + " code is missing");
10223        }
10224
10225        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10226            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10227                final boolean splitShouldHaveCode =
10228                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10229                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10230                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10231                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10232                }
10233            }
10234        }
10235    }
10236
10237    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10238            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10239                    throws PackageManagerException {
10240        if (DEBUG_PACKAGE_SCANNING) {
10241            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10242                Log.d(TAG, "Scanning package " + pkg.packageName);
10243        }
10244
10245        applyPolicy(pkg, policyFlags);
10246
10247        assertPackageIsValid(pkg, policyFlags, scanFlags);
10248
10249        // Initialize package source and resource directories
10250        final File scanFile = new File(pkg.codePath);
10251        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10252        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10253
10254        SharedUserSetting suid = null;
10255        PackageSetting pkgSetting = null;
10256
10257        // Getting the package setting may have a side-effect, so if we
10258        // are only checking if scan would succeed, stash a copy of the
10259        // old setting to restore at the end.
10260        PackageSetting nonMutatedPs = null;
10261
10262        // We keep references to the derived CPU Abis from settings in oder to reuse
10263        // them in the case where we're not upgrading or booting for the first time.
10264        String primaryCpuAbiFromSettings = null;
10265        String secondaryCpuAbiFromSettings = null;
10266
10267        // writer
10268        synchronized (mPackages) {
10269            if (pkg.mSharedUserId != null) {
10270                // SIDE EFFECTS; may potentially allocate a new shared user
10271                suid = mSettings.getSharedUserLPw(
10272                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10273                if (DEBUG_PACKAGE_SCANNING) {
10274                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10275                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10276                                + "): packages=" + suid.packages);
10277                }
10278            }
10279
10280            // Check if we are renaming from an original package name.
10281            PackageSetting origPackage = null;
10282            String realName = null;
10283            if (pkg.mOriginalPackages != null) {
10284                // This package may need to be renamed to a previously
10285                // installed name.  Let's check on that...
10286                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10287                if (pkg.mOriginalPackages.contains(renamed)) {
10288                    // This package had originally been installed as the
10289                    // original name, and we have already taken care of
10290                    // transitioning to the new one.  Just update the new
10291                    // one to continue using the old name.
10292                    realName = pkg.mRealPackage;
10293                    if (!pkg.packageName.equals(renamed)) {
10294                        // Callers into this function may have already taken
10295                        // care of renaming the package; only do it here if
10296                        // it is not already done.
10297                        pkg.setPackageName(renamed);
10298                    }
10299                } else {
10300                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10301                        if ((origPackage = mSettings.getPackageLPr(
10302                                pkg.mOriginalPackages.get(i))) != null) {
10303                            // We do have the package already installed under its
10304                            // original name...  should we use it?
10305                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10306                                // New package is not compatible with original.
10307                                origPackage = null;
10308                                continue;
10309                            } else if (origPackage.sharedUser != null) {
10310                                // Make sure uid is compatible between packages.
10311                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10312                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10313                                            + " to " + pkg.packageName + ": old uid "
10314                                            + origPackage.sharedUser.name
10315                                            + " differs from " + pkg.mSharedUserId);
10316                                    origPackage = null;
10317                                    continue;
10318                                }
10319                                // TODO: Add case when shared user id is added [b/28144775]
10320                            } else {
10321                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10322                                        + pkg.packageName + " to old name " + origPackage.name);
10323                            }
10324                            break;
10325                        }
10326                    }
10327                }
10328            }
10329
10330            if (mTransferedPackages.contains(pkg.packageName)) {
10331                Slog.w(TAG, "Package " + pkg.packageName
10332                        + " was transferred to another, but its .apk remains");
10333            }
10334
10335            // See comments in nonMutatedPs declaration
10336            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10337                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10338                if (foundPs != null) {
10339                    nonMutatedPs = new PackageSetting(foundPs);
10340                }
10341            }
10342
10343            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10344                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10345                if (foundPs != null) {
10346                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10347                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10348                }
10349            }
10350
10351            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10352            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10353                PackageManagerService.reportSettingsProblem(Log.WARN,
10354                        "Package " + pkg.packageName + " shared user changed from "
10355                                + (pkgSetting.sharedUser != null
10356                                        ? pkgSetting.sharedUser.name : "<nothing>")
10357                                + " to "
10358                                + (suid != null ? suid.name : "<nothing>")
10359                                + "; replacing with new");
10360                pkgSetting = null;
10361            }
10362            final PackageSetting oldPkgSetting =
10363                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10364            final PackageSetting disabledPkgSetting =
10365                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10366
10367            String[] usesStaticLibraries = null;
10368            if (pkg.usesStaticLibraries != null) {
10369                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10370                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10371            }
10372
10373            if (pkgSetting == null) {
10374                final String parentPackageName = (pkg.parentPackage != null)
10375                        ? pkg.parentPackage.packageName : null;
10376                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10377                // REMOVE SharedUserSetting from method; update in a separate call
10378                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10379                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10380                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10381                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10382                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10383                        true /*allowInstall*/, instantApp, parentPackageName,
10384                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10385                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10386                // SIDE EFFECTS; updates system state; move elsewhere
10387                if (origPackage != null) {
10388                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10389                }
10390                mSettings.addUserToSettingLPw(pkgSetting);
10391            } else {
10392                // REMOVE SharedUserSetting from method; update in a separate call.
10393                //
10394                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10395                // secondaryCpuAbi are not known at this point so we always update them
10396                // to null here, only to reset them at a later point.
10397                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10398                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10399                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10400                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10401                        UserManagerService.getInstance(), usesStaticLibraries,
10402                        pkg.usesStaticLibrariesVersions);
10403            }
10404            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10405            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10406
10407            // SIDE EFFECTS; modifies system state; move elsewhere
10408            if (pkgSetting.origPackage != null) {
10409                // If we are first transitioning from an original package,
10410                // fix up the new package's name now.  We need to do this after
10411                // looking up the package under its new name, so getPackageLP
10412                // can take care of fiddling things correctly.
10413                pkg.setPackageName(origPackage.name);
10414
10415                // File a report about this.
10416                String msg = "New package " + pkgSetting.realName
10417                        + " renamed to replace old package " + pkgSetting.name;
10418                reportSettingsProblem(Log.WARN, msg);
10419
10420                // Make a note of it.
10421                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10422                    mTransferedPackages.add(origPackage.name);
10423                }
10424
10425                // No longer need to retain this.
10426                pkgSetting.origPackage = null;
10427            }
10428
10429            // SIDE EFFECTS; modifies system state; move elsewhere
10430            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10431                // Make a note of it.
10432                mTransferedPackages.add(pkg.packageName);
10433            }
10434
10435            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10436                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10437            }
10438
10439            if ((scanFlags & SCAN_BOOTING) == 0
10440                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10441                // Check all shared libraries and map to their actual file path.
10442                // We only do this here for apps not on a system dir, because those
10443                // are the only ones that can fail an install due to this.  We
10444                // will take care of the system apps by updating all of their
10445                // library paths after the scan is done. Also during the initial
10446                // scan don't update any libs as we do this wholesale after all
10447                // apps are scanned to avoid dependency based scanning.
10448                updateSharedLibrariesLPr(pkg, null);
10449            }
10450
10451            if (mFoundPolicyFile) {
10452                SELinuxMMAC.assignSeInfoValue(pkg);
10453            }
10454            pkg.applicationInfo.uid = pkgSetting.appId;
10455            pkg.mExtras = pkgSetting;
10456
10457
10458            // Static shared libs have same package with different versions where
10459            // we internally use a synthetic package name to allow multiple versions
10460            // of the same package, therefore we need to compare signatures against
10461            // the package setting for the latest library version.
10462            PackageSetting signatureCheckPs = pkgSetting;
10463            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10464                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10465                if (libraryEntry != null) {
10466                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10467                }
10468            }
10469
10470            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10471                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10472                    // We just determined the app is signed correctly, so bring
10473                    // over the latest parsed certs.
10474                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10475                } else {
10476                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10477                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10478                                "Package " + pkg.packageName + " upgrade keys do not match the "
10479                                + "previously installed version");
10480                    } else {
10481                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10482                        String msg = "System package " + pkg.packageName
10483                                + " signature changed; retaining data.";
10484                        reportSettingsProblem(Log.WARN, msg);
10485                    }
10486                }
10487            } else {
10488                try {
10489                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10490                    verifySignaturesLP(signatureCheckPs, pkg);
10491                    // We just determined the app is signed correctly, so bring
10492                    // over the latest parsed certs.
10493                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10494                } catch (PackageManagerException e) {
10495                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10496                        throw e;
10497                    }
10498                    // The signature has changed, but this package is in the system
10499                    // image...  let's recover!
10500                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10501                    // However...  if this package is part of a shared user, but it
10502                    // doesn't match the signature of the shared user, let's fail.
10503                    // What this means is that you can't change the signatures
10504                    // associated with an overall shared user, which doesn't seem all
10505                    // that unreasonable.
10506                    if (signatureCheckPs.sharedUser != null) {
10507                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10508                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10509                            throw new PackageManagerException(
10510                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10511                                    "Signature mismatch for shared user: "
10512                                            + pkgSetting.sharedUser);
10513                        }
10514                    }
10515                    // File a report about this.
10516                    String msg = "System package " + pkg.packageName
10517                            + " signature changed; retaining data.";
10518                    reportSettingsProblem(Log.WARN, msg);
10519                }
10520            }
10521
10522            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10523                // This package wants to adopt ownership of permissions from
10524                // another package.
10525                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10526                    final String origName = pkg.mAdoptPermissions.get(i);
10527                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10528                    if (orig != null) {
10529                        if (verifyPackageUpdateLPr(orig, pkg)) {
10530                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10531                                    + pkg.packageName);
10532                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10533                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10534                        }
10535                    }
10536                }
10537            }
10538        }
10539
10540        pkg.applicationInfo.processName = fixProcessName(
10541                pkg.applicationInfo.packageName,
10542                pkg.applicationInfo.processName);
10543
10544        if (pkg != mPlatformPackage) {
10545            // Get all of our default paths setup
10546            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10547        }
10548
10549        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10550
10551        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10552            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10553                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10554                derivePackageAbi(
10555                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
10556                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10557
10558                // Some system apps still use directory structure for native libraries
10559                // in which case we might end up not detecting abi solely based on apk
10560                // structure. Try to detect abi based on directory structure.
10561                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10562                        pkg.applicationInfo.primaryCpuAbi == null) {
10563                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10564                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10565                }
10566            } else {
10567                // This is not a first boot or an upgrade, don't bother deriving the
10568                // ABI during the scan. Instead, trust the value that was stored in the
10569                // package setting.
10570                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10571                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10572
10573                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10574
10575                if (DEBUG_ABI_SELECTION) {
10576                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10577                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10578                        pkg.applicationInfo.secondaryCpuAbi);
10579                }
10580            }
10581        } else {
10582            if ((scanFlags & SCAN_MOVE) != 0) {
10583                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10584                // but we already have this packages package info in the PackageSetting. We just
10585                // use that and derive the native library path based on the new codepath.
10586                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10587                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10588            }
10589
10590            // Set native library paths again. For moves, the path will be updated based on the
10591            // ABIs we've determined above. For non-moves, the path will be updated based on the
10592            // ABIs we determined during compilation, but the path will depend on the final
10593            // package path (after the rename away from the stage path).
10594            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10595        }
10596
10597        // This is a special case for the "system" package, where the ABI is
10598        // dictated by the zygote configuration (and init.rc). We should keep track
10599        // of this ABI so that we can deal with "normal" applications that run under
10600        // the same UID correctly.
10601        if (mPlatformPackage == pkg) {
10602            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10603                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10604        }
10605
10606        // If there's a mismatch between the abi-override in the package setting
10607        // and the abiOverride specified for the install. Warn about this because we
10608        // would've already compiled the app without taking the package setting into
10609        // account.
10610        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10611            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10612                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10613                        " for package " + pkg.packageName);
10614            }
10615        }
10616
10617        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10618        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10619        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10620
10621        // Copy the derived override back to the parsed package, so that we can
10622        // update the package settings accordingly.
10623        pkg.cpuAbiOverride = cpuAbiOverride;
10624
10625        if (DEBUG_ABI_SELECTION) {
10626            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10627                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10628                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10629        }
10630
10631        // Push the derived path down into PackageSettings so we know what to
10632        // clean up at uninstall time.
10633        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10634
10635        if (DEBUG_ABI_SELECTION) {
10636            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10637                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10638                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10639        }
10640
10641        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10642        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10643            // We don't do this here during boot because we can do it all
10644            // at once after scanning all existing packages.
10645            //
10646            // We also do this *before* we perform dexopt on this package, so that
10647            // we can avoid redundant dexopts, and also to make sure we've got the
10648            // code and package path correct.
10649            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10650        }
10651
10652        if (mFactoryTest && pkg.requestedPermissions.contains(
10653                android.Manifest.permission.FACTORY_TEST)) {
10654            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10655        }
10656
10657        if (isSystemApp(pkg)) {
10658            pkgSetting.isOrphaned = true;
10659        }
10660
10661        // Take care of first install / last update times.
10662        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10663        if (currentTime != 0) {
10664            if (pkgSetting.firstInstallTime == 0) {
10665                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10666            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10667                pkgSetting.lastUpdateTime = currentTime;
10668            }
10669        } else if (pkgSetting.firstInstallTime == 0) {
10670            // We need *something*.  Take time time stamp of the file.
10671            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10672        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10673            if (scanFileTime != pkgSetting.timeStamp) {
10674                // A package on the system image has changed; consider this
10675                // to be an update.
10676                pkgSetting.lastUpdateTime = scanFileTime;
10677            }
10678        }
10679        pkgSetting.setTimeStamp(scanFileTime);
10680
10681        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10682            if (nonMutatedPs != null) {
10683                synchronized (mPackages) {
10684                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10685                }
10686            }
10687        } else {
10688            final int userId = user == null ? 0 : user.getIdentifier();
10689            // Modify state for the given package setting
10690            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10691                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10692            if (pkgSetting.getInstantApp(userId)) {
10693                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10694            }
10695        }
10696        return pkg;
10697    }
10698
10699    /**
10700     * Applies policy to the parsed package based upon the given policy flags.
10701     * Ensures the package is in a good state.
10702     * <p>
10703     * Implementation detail: This method must NOT have any side effect. It would
10704     * ideally be static, but, it requires locks to read system state.
10705     */
10706    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10707        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10708            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10709            if (pkg.applicationInfo.isDirectBootAware()) {
10710                // we're direct boot aware; set for all components
10711                for (PackageParser.Service s : pkg.services) {
10712                    s.info.encryptionAware = s.info.directBootAware = true;
10713                }
10714                for (PackageParser.Provider p : pkg.providers) {
10715                    p.info.encryptionAware = p.info.directBootAware = true;
10716                }
10717                for (PackageParser.Activity a : pkg.activities) {
10718                    a.info.encryptionAware = a.info.directBootAware = true;
10719                }
10720                for (PackageParser.Activity r : pkg.receivers) {
10721                    r.info.encryptionAware = r.info.directBootAware = true;
10722                }
10723            }
10724        } else {
10725            // Only allow system apps to be flagged as core apps.
10726            pkg.coreApp = false;
10727            // clear flags not applicable to regular apps
10728            pkg.applicationInfo.privateFlags &=
10729                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10730            pkg.applicationInfo.privateFlags &=
10731                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10732        }
10733        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10734
10735        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10736            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10737        }
10738
10739        if (!isSystemApp(pkg)) {
10740            // Only system apps can use these features.
10741            pkg.mOriginalPackages = null;
10742            pkg.mRealPackage = null;
10743            pkg.mAdoptPermissions = null;
10744        }
10745    }
10746
10747    /**
10748     * Asserts the parsed package is valid according to the given policy. If the
10749     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10750     * <p>
10751     * Implementation detail: This method must NOT have any side effects. It would
10752     * ideally be static, but, it requires locks to read system state.
10753     *
10754     * @throws PackageManagerException If the package fails any of the validation checks
10755     */
10756    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10757            throws PackageManagerException {
10758        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10759            assertCodePolicy(pkg);
10760        }
10761
10762        if (pkg.applicationInfo.getCodePath() == null ||
10763                pkg.applicationInfo.getResourcePath() == null) {
10764            // Bail out. The resource and code paths haven't been set.
10765            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10766                    "Code and resource paths haven't been set correctly");
10767        }
10768
10769        // Make sure we're not adding any bogus keyset info
10770        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10771        ksms.assertScannedPackageValid(pkg);
10772
10773        synchronized (mPackages) {
10774            // The special "android" package can only be defined once
10775            if (pkg.packageName.equals("android")) {
10776                if (mAndroidApplication != null) {
10777                    Slog.w(TAG, "*************************************************");
10778                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10779                    Slog.w(TAG, " codePath=" + pkg.codePath);
10780                    Slog.w(TAG, "*************************************************");
10781                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10782                            "Core android package being redefined.  Skipping.");
10783                }
10784            }
10785
10786            // A package name must be unique; don't allow duplicates
10787            if (mPackages.containsKey(pkg.packageName)) {
10788                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10789                        "Application package " + pkg.packageName
10790                        + " already installed.  Skipping duplicate.");
10791            }
10792
10793            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10794                // Static libs have a synthetic package name containing the version
10795                // but we still want the base name to be unique.
10796                if (mPackages.containsKey(pkg.manifestPackageName)) {
10797                    throw new PackageManagerException(
10798                            "Duplicate static shared lib provider package");
10799                }
10800
10801                // Static shared libraries should have at least O target SDK
10802                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10803                    throw new PackageManagerException(
10804                            "Packages declaring static-shared libs must target O SDK or higher");
10805                }
10806
10807                // Package declaring static a shared lib cannot be instant apps
10808                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10809                    throw new PackageManagerException(
10810                            "Packages declaring static-shared libs cannot be instant apps");
10811                }
10812
10813                // Package declaring static a shared lib cannot be renamed since the package
10814                // name is synthetic and apps can't code around package manager internals.
10815                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10816                    throw new PackageManagerException(
10817                            "Packages declaring static-shared libs cannot be renamed");
10818                }
10819
10820                // Package declaring static a shared lib cannot declare child packages
10821                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10822                    throw new PackageManagerException(
10823                            "Packages declaring static-shared libs cannot have child packages");
10824                }
10825
10826                // Package declaring static a shared lib cannot declare dynamic libs
10827                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10828                    throw new PackageManagerException(
10829                            "Packages declaring static-shared libs cannot declare dynamic libs");
10830                }
10831
10832                // Package declaring static a shared lib cannot declare shared users
10833                if (pkg.mSharedUserId != null) {
10834                    throw new PackageManagerException(
10835                            "Packages declaring static-shared libs cannot declare shared users");
10836                }
10837
10838                // Static shared libs cannot declare activities
10839                if (!pkg.activities.isEmpty()) {
10840                    throw new PackageManagerException(
10841                            "Static shared libs cannot declare activities");
10842                }
10843
10844                // Static shared libs cannot declare services
10845                if (!pkg.services.isEmpty()) {
10846                    throw new PackageManagerException(
10847                            "Static shared libs cannot declare services");
10848                }
10849
10850                // Static shared libs cannot declare providers
10851                if (!pkg.providers.isEmpty()) {
10852                    throw new PackageManagerException(
10853                            "Static shared libs cannot declare content providers");
10854                }
10855
10856                // Static shared libs cannot declare receivers
10857                if (!pkg.receivers.isEmpty()) {
10858                    throw new PackageManagerException(
10859                            "Static shared libs cannot declare broadcast receivers");
10860                }
10861
10862                // Static shared libs cannot declare permission groups
10863                if (!pkg.permissionGroups.isEmpty()) {
10864                    throw new PackageManagerException(
10865                            "Static shared libs cannot declare permission groups");
10866                }
10867
10868                // Static shared libs cannot declare permissions
10869                if (!pkg.permissions.isEmpty()) {
10870                    throw new PackageManagerException(
10871                            "Static shared libs cannot declare permissions");
10872                }
10873
10874                // Static shared libs cannot declare protected broadcasts
10875                if (pkg.protectedBroadcasts != null) {
10876                    throw new PackageManagerException(
10877                            "Static shared libs cannot declare protected broadcasts");
10878                }
10879
10880                // Static shared libs cannot be overlay targets
10881                if (pkg.mOverlayTarget != null) {
10882                    throw new PackageManagerException(
10883                            "Static shared libs cannot be overlay targets");
10884                }
10885
10886                // The version codes must be ordered as lib versions
10887                int minVersionCode = Integer.MIN_VALUE;
10888                int maxVersionCode = Integer.MAX_VALUE;
10889
10890                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10891                        pkg.staticSharedLibName);
10892                if (versionedLib != null) {
10893                    final int versionCount = versionedLib.size();
10894                    for (int i = 0; i < versionCount; i++) {
10895                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10896                        final int libVersionCode = libInfo.getDeclaringPackage()
10897                                .getVersionCode();
10898                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10899                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10900                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10901                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10902                        } else {
10903                            minVersionCode = maxVersionCode = libVersionCode;
10904                            break;
10905                        }
10906                    }
10907                }
10908                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10909                    throw new PackageManagerException("Static shared"
10910                            + " lib version codes must be ordered as lib versions");
10911                }
10912            }
10913
10914            // Only privileged apps and updated privileged apps can add child packages.
10915            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10916                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10917                    throw new PackageManagerException("Only privileged apps can add child "
10918                            + "packages. Ignoring package " + pkg.packageName);
10919                }
10920                final int childCount = pkg.childPackages.size();
10921                for (int i = 0; i < childCount; i++) {
10922                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10923                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10924                            childPkg.packageName)) {
10925                        throw new PackageManagerException("Can't override child of "
10926                                + "another disabled app. Ignoring package " + pkg.packageName);
10927                    }
10928                }
10929            }
10930
10931            // If we're only installing presumed-existing packages, require that the
10932            // scanned APK is both already known and at the path previously established
10933            // for it.  Previously unknown packages we pick up normally, but if we have an
10934            // a priori expectation about this package's install presence, enforce it.
10935            // With a singular exception for new system packages. When an OTA contains
10936            // a new system package, we allow the codepath to change from a system location
10937            // to the user-installed location. If we don't allow this change, any newer,
10938            // user-installed version of the application will be ignored.
10939            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10940                if (mExpectingBetter.containsKey(pkg.packageName)) {
10941                    logCriticalInfo(Log.WARN,
10942                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10943                } else {
10944                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10945                    if (known != null) {
10946                        if (DEBUG_PACKAGE_SCANNING) {
10947                            Log.d(TAG, "Examining " + pkg.codePath
10948                                    + " and requiring known paths " + known.codePathString
10949                                    + " & " + known.resourcePathString);
10950                        }
10951                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10952                                || !pkg.applicationInfo.getResourcePath().equals(
10953                                        known.resourcePathString)) {
10954                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10955                                    "Application package " + pkg.packageName
10956                                    + " found at " + pkg.applicationInfo.getCodePath()
10957                                    + " but expected at " + known.codePathString
10958                                    + "; ignoring.");
10959                        }
10960                    }
10961                }
10962            }
10963
10964            // Verify that this new package doesn't have any content providers
10965            // that conflict with existing packages.  Only do this if the
10966            // package isn't already installed, since we don't want to break
10967            // things that are installed.
10968            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10969                final int N = pkg.providers.size();
10970                int i;
10971                for (i=0; i<N; i++) {
10972                    PackageParser.Provider p = pkg.providers.get(i);
10973                    if (p.info.authority != null) {
10974                        String names[] = p.info.authority.split(";");
10975                        for (int j = 0; j < names.length; j++) {
10976                            if (mProvidersByAuthority.containsKey(names[j])) {
10977                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10978                                final String otherPackageName =
10979                                        ((other != null && other.getComponentName() != null) ?
10980                                                other.getComponentName().getPackageName() : "?");
10981                                throw new PackageManagerException(
10982                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10983                                        "Can't install because provider name " + names[j]
10984                                                + " (in package " + pkg.applicationInfo.packageName
10985                                                + ") is already used by " + otherPackageName);
10986                            }
10987                        }
10988                    }
10989                }
10990            }
10991        }
10992    }
10993
10994    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10995            int type, String declaringPackageName, int declaringVersionCode) {
10996        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10997        if (versionedLib == null) {
10998            versionedLib = new SparseArray<>();
10999            mSharedLibraries.put(name, versionedLib);
11000            if (type == SharedLibraryInfo.TYPE_STATIC) {
11001                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11002            }
11003        } else if (versionedLib.indexOfKey(version) >= 0) {
11004            return false;
11005        }
11006        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11007                version, type, declaringPackageName, declaringVersionCode);
11008        versionedLib.put(version, libEntry);
11009        return true;
11010    }
11011
11012    private boolean removeSharedLibraryLPw(String name, int version) {
11013        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11014        if (versionedLib == null) {
11015            return false;
11016        }
11017        final int libIdx = versionedLib.indexOfKey(version);
11018        if (libIdx < 0) {
11019            return false;
11020        }
11021        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11022        versionedLib.remove(version);
11023        if (versionedLib.size() <= 0) {
11024            mSharedLibraries.remove(name);
11025            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11026                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11027                        .getPackageName());
11028            }
11029        }
11030        return true;
11031    }
11032
11033    /**
11034     * Adds a scanned package to the system. When this method is finished, the package will
11035     * be available for query, resolution, etc...
11036     */
11037    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11038            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11039        final String pkgName = pkg.packageName;
11040        if (mCustomResolverComponentName != null &&
11041                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11042            setUpCustomResolverActivity(pkg);
11043        }
11044
11045        if (pkg.packageName.equals("android")) {
11046            synchronized (mPackages) {
11047                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11048                    // Set up information for our fall-back user intent resolution activity.
11049                    mPlatformPackage = pkg;
11050                    pkg.mVersionCode = mSdkVersion;
11051                    mAndroidApplication = pkg.applicationInfo;
11052                    if (!mResolverReplaced) {
11053                        mResolveActivity.applicationInfo = mAndroidApplication;
11054                        mResolveActivity.name = ResolverActivity.class.getName();
11055                        mResolveActivity.packageName = mAndroidApplication.packageName;
11056                        mResolveActivity.processName = "system:ui";
11057                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11058                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11059                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11060                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11061                        mResolveActivity.exported = true;
11062                        mResolveActivity.enabled = true;
11063                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11064                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11065                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11066                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11067                                | ActivityInfo.CONFIG_ORIENTATION
11068                                | ActivityInfo.CONFIG_KEYBOARD
11069                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11070                        mResolveInfo.activityInfo = mResolveActivity;
11071                        mResolveInfo.priority = 0;
11072                        mResolveInfo.preferredOrder = 0;
11073                        mResolveInfo.match = 0;
11074                        mResolveComponentName = new ComponentName(
11075                                mAndroidApplication.packageName, mResolveActivity.name);
11076                    }
11077                }
11078            }
11079        }
11080
11081        ArrayList<PackageParser.Package> clientLibPkgs = null;
11082        // writer
11083        synchronized (mPackages) {
11084            boolean hasStaticSharedLibs = false;
11085
11086            // Any app can add new static shared libraries
11087            if (pkg.staticSharedLibName != null) {
11088                // Static shared libs don't allow renaming as they have synthetic package
11089                // names to allow install of multiple versions, so use name from manifest.
11090                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11091                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11092                        pkg.manifestPackageName, pkg.mVersionCode)) {
11093                    hasStaticSharedLibs = true;
11094                } else {
11095                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11096                                + pkg.staticSharedLibName + " already exists; skipping");
11097                }
11098                // Static shared libs cannot be updated once installed since they
11099                // use synthetic package name which includes the version code, so
11100                // not need to update other packages's shared lib dependencies.
11101            }
11102
11103            if (!hasStaticSharedLibs
11104                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11105                // Only system apps can add new dynamic shared libraries.
11106                if (pkg.libraryNames != null) {
11107                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11108                        String name = pkg.libraryNames.get(i);
11109                        boolean allowed = false;
11110                        if (pkg.isUpdatedSystemApp()) {
11111                            // New library entries can only be added through the
11112                            // system image.  This is important to get rid of a lot
11113                            // of nasty edge cases: for example if we allowed a non-
11114                            // system update of the app to add a library, then uninstalling
11115                            // the update would make the library go away, and assumptions
11116                            // we made such as through app install filtering would now
11117                            // have allowed apps on the device which aren't compatible
11118                            // with it.  Better to just have the restriction here, be
11119                            // conservative, and create many fewer cases that can negatively
11120                            // impact the user experience.
11121                            final PackageSetting sysPs = mSettings
11122                                    .getDisabledSystemPkgLPr(pkg.packageName);
11123                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11124                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11125                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11126                                        allowed = true;
11127                                        break;
11128                                    }
11129                                }
11130                            }
11131                        } else {
11132                            allowed = true;
11133                        }
11134                        if (allowed) {
11135                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11136                                    SharedLibraryInfo.VERSION_UNDEFINED,
11137                                    SharedLibraryInfo.TYPE_DYNAMIC,
11138                                    pkg.packageName, pkg.mVersionCode)) {
11139                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11140                                        + name + " already exists; skipping");
11141                            }
11142                        } else {
11143                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11144                                    + name + " that is not declared on system image; skipping");
11145                        }
11146                    }
11147
11148                    if ((scanFlags & SCAN_BOOTING) == 0) {
11149                        // If we are not booting, we need to update any applications
11150                        // that are clients of our shared library.  If we are booting,
11151                        // this will all be done once the scan is complete.
11152                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11153                    }
11154                }
11155            }
11156        }
11157
11158        if ((scanFlags & SCAN_BOOTING) != 0) {
11159            // No apps can run during boot scan, so they don't need to be frozen
11160        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11161            // Caller asked to not kill app, so it's probably not frozen
11162        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11163            // Caller asked us to ignore frozen check for some reason; they
11164            // probably didn't know the package name
11165        } else {
11166            // We're doing major surgery on this package, so it better be frozen
11167            // right now to keep it from launching
11168            checkPackageFrozen(pkgName);
11169        }
11170
11171        // Also need to kill any apps that are dependent on the library.
11172        if (clientLibPkgs != null) {
11173            for (int i=0; i<clientLibPkgs.size(); i++) {
11174                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11175                killApplication(clientPkg.applicationInfo.packageName,
11176                        clientPkg.applicationInfo.uid, "update lib");
11177            }
11178        }
11179
11180        // writer
11181        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11182
11183        synchronized (mPackages) {
11184            // We don't expect installation to fail beyond this point
11185
11186            // Add the new setting to mSettings
11187            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11188            // Add the new setting to mPackages
11189            mPackages.put(pkg.applicationInfo.packageName, pkg);
11190            // Make sure we don't accidentally delete its data.
11191            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11192            while (iter.hasNext()) {
11193                PackageCleanItem item = iter.next();
11194                if (pkgName.equals(item.packageName)) {
11195                    iter.remove();
11196                }
11197            }
11198
11199            // Add the package's KeySets to the global KeySetManagerService
11200            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11201            ksms.addScannedPackageLPw(pkg);
11202
11203            int N = pkg.providers.size();
11204            StringBuilder r = null;
11205            int i;
11206            for (i=0; i<N; i++) {
11207                PackageParser.Provider p = pkg.providers.get(i);
11208                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11209                        p.info.processName);
11210                mProviders.addProvider(p);
11211                p.syncable = p.info.isSyncable;
11212                if (p.info.authority != null) {
11213                    String names[] = p.info.authority.split(";");
11214                    p.info.authority = null;
11215                    for (int j = 0; j < names.length; j++) {
11216                        if (j == 1 && p.syncable) {
11217                            // We only want the first authority for a provider to possibly be
11218                            // syncable, so if we already added this provider using a different
11219                            // authority clear the syncable flag. We copy the provider before
11220                            // changing it because the mProviders object contains a reference
11221                            // to a provider that we don't want to change.
11222                            // Only do this for the second authority since the resulting provider
11223                            // object can be the same for all future authorities for this provider.
11224                            p = new PackageParser.Provider(p);
11225                            p.syncable = false;
11226                        }
11227                        if (!mProvidersByAuthority.containsKey(names[j])) {
11228                            mProvidersByAuthority.put(names[j], p);
11229                            if (p.info.authority == null) {
11230                                p.info.authority = names[j];
11231                            } else {
11232                                p.info.authority = p.info.authority + ";" + names[j];
11233                            }
11234                            if (DEBUG_PACKAGE_SCANNING) {
11235                                if (chatty)
11236                                    Log.d(TAG, "Registered content provider: " + names[j]
11237                                            + ", className = " + p.info.name + ", isSyncable = "
11238                                            + p.info.isSyncable);
11239                            }
11240                        } else {
11241                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11242                            Slog.w(TAG, "Skipping provider name " + names[j] +
11243                                    " (in package " + pkg.applicationInfo.packageName +
11244                                    "): name already used by "
11245                                    + ((other != null && other.getComponentName() != null)
11246                                            ? other.getComponentName().getPackageName() : "?"));
11247                        }
11248                    }
11249                }
11250                if (chatty) {
11251                    if (r == null) {
11252                        r = new StringBuilder(256);
11253                    } else {
11254                        r.append(' ');
11255                    }
11256                    r.append(p.info.name);
11257                }
11258            }
11259            if (r != null) {
11260                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11261            }
11262
11263            N = pkg.services.size();
11264            r = null;
11265            for (i=0; i<N; i++) {
11266                PackageParser.Service s = pkg.services.get(i);
11267                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11268                        s.info.processName);
11269                mServices.addService(s);
11270                if (chatty) {
11271                    if (r == null) {
11272                        r = new StringBuilder(256);
11273                    } else {
11274                        r.append(' ');
11275                    }
11276                    r.append(s.info.name);
11277                }
11278            }
11279            if (r != null) {
11280                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11281            }
11282
11283            N = pkg.receivers.size();
11284            r = null;
11285            for (i=0; i<N; i++) {
11286                PackageParser.Activity a = pkg.receivers.get(i);
11287                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11288                        a.info.processName);
11289                mReceivers.addActivity(a, "receiver");
11290                if (chatty) {
11291                    if (r == null) {
11292                        r = new StringBuilder(256);
11293                    } else {
11294                        r.append(' ');
11295                    }
11296                    r.append(a.info.name);
11297                }
11298            }
11299            if (r != null) {
11300                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11301            }
11302
11303            N = pkg.activities.size();
11304            r = null;
11305            for (i=0; i<N; i++) {
11306                PackageParser.Activity a = pkg.activities.get(i);
11307                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11308                        a.info.processName);
11309                mActivities.addActivity(a, "activity");
11310                if (chatty) {
11311                    if (r == null) {
11312                        r = new StringBuilder(256);
11313                    } else {
11314                        r.append(' ');
11315                    }
11316                    r.append(a.info.name);
11317                }
11318            }
11319            if (r != null) {
11320                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11321            }
11322
11323            N = pkg.permissionGroups.size();
11324            r = null;
11325            for (i=0; i<N; i++) {
11326                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11327                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11328                final String curPackageName = cur == null ? null : cur.info.packageName;
11329                // Dont allow ephemeral apps to define new permission groups.
11330                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11331                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11332                            + pg.info.packageName
11333                            + " ignored: instant apps cannot define new permission groups.");
11334                    continue;
11335                }
11336                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11337                if (cur == null || isPackageUpdate) {
11338                    mPermissionGroups.put(pg.info.name, pg);
11339                    if (chatty) {
11340                        if (r == null) {
11341                            r = new StringBuilder(256);
11342                        } else {
11343                            r.append(' ');
11344                        }
11345                        if (isPackageUpdate) {
11346                            r.append("UPD:");
11347                        }
11348                        r.append(pg.info.name);
11349                    }
11350                } else {
11351                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11352                            + pg.info.packageName + " ignored: original from "
11353                            + cur.info.packageName);
11354                    if (chatty) {
11355                        if (r == null) {
11356                            r = new StringBuilder(256);
11357                        } else {
11358                            r.append(' ');
11359                        }
11360                        r.append("DUP:");
11361                        r.append(pg.info.name);
11362                    }
11363                }
11364            }
11365            if (r != null) {
11366                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11367            }
11368
11369            N = pkg.permissions.size();
11370            r = null;
11371            for (i=0; i<N; i++) {
11372                PackageParser.Permission p = pkg.permissions.get(i);
11373
11374                // Dont allow ephemeral apps to define new permissions.
11375                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11376                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11377                            + p.info.packageName
11378                            + " ignored: instant apps cannot define new permissions.");
11379                    continue;
11380                }
11381
11382                // Assume by default that we did not install this permission into the system.
11383                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11384
11385                // Now that permission groups have a special meaning, we ignore permission
11386                // groups for legacy apps to prevent unexpected behavior. In particular,
11387                // permissions for one app being granted to someone just because they happen
11388                // to be in a group defined by another app (before this had no implications).
11389                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11390                    p.group = mPermissionGroups.get(p.info.group);
11391                    // Warn for a permission in an unknown group.
11392                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11393                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11394                                + p.info.packageName + " in an unknown group " + p.info.group);
11395                    }
11396                }
11397
11398                ArrayMap<String, BasePermission> permissionMap =
11399                        p.tree ? mSettings.mPermissionTrees
11400                                : mSettings.mPermissions;
11401                BasePermission bp = permissionMap.get(p.info.name);
11402
11403                // Allow system apps to redefine non-system permissions
11404                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11405                    final boolean currentOwnerIsSystem = (bp.perm != null
11406                            && isSystemApp(bp.perm.owner));
11407                    if (isSystemApp(p.owner)) {
11408                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11409                            // It's a built-in permission and no owner, take ownership now
11410                            bp.packageSetting = pkgSetting;
11411                            bp.perm = p;
11412                            bp.uid = pkg.applicationInfo.uid;
11413                            bp.sourcePackage = p.info.packageName;
11414                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11415                        } else if (!currentOwnerIsSystem) {
11416                            String msg = "New decl " + p.owner + " of permission  "
11417                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11418                            reportSettingsProblem(Log.WARN, msg);
11419                            bp = null;
11420                        }
11421                    }
11422                }
11423
11424                if (bp == null) {
11425                    bp = new BasePermission(p.info.name, p.info.packageName,
11426                            BasePermission.TYPE_NORMAL);
11427                    permissionMap.put(p.info.name, bp);
11428                }
11429
11430                if (bp.perm == null) {
11431                    if (bp.sourcePackage == null
11432                            || bp.sourcePackage.equals(p.info.packageName)) {
11433                        BasePermission tree = findPermissionTreeLP(p.info.name);
11434                        if (tree == null
11435                                || tree.sourcePackage.equals(p.info.packageName)) {
11436                            bp.packageSetting = pkgSetting;
11437                            bp.perm = p;
11438                            bp.uid = pkg.applicationInfo.uid;
11439                            bp.sourcePackage = p.info.packageName;
11440                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11441                            if (chatty) {
11442                                if (r == null) {
11443                                    r = new StringBuilder(256);
11444                                } else {
11445                                    r.append(' ');
11446                                }
11447                                r.append(p.info.name);
11448                            }
11449                        } else {
11450                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11451                                    + p.info.packageName + " ignored: base tree "
11452                                    + tree.name + " is from package "
11453                                    + tree.sourcePackage);
11454                        }
11455                    } else {
11456                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11457                                + p.info.packageName + " ignored: original from "
11458                                + bp.sourcePackage);
11459                    }
11460                } else if (chatty) {
11461                    if (r == null) {
11462                        r = new StringBuilder(256);
11463                    } else {
11464                        r.append(' ');
11465                    }
11466                    r.append("DUP:");
11467                    r.append(p.info.name);
11468                }
11469                if (bp.perm == p) {
11470                    bp.protectionLevel = p.info.protectionLevel;
11471                }
11472            }
11473
11474            if (r != null) {
11475                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11476            }
11477
11478            N = pkg.instrumentation.size();
11479            r = null;
11480            for (i=0; i<N; i++) {
11481                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11482                a.info.packageName = pkg.applicationInfo.packageName;
11483                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11484                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11485                a.info.splitNames = pkg.splitNames;
11486                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11487                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11488                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11489                a.info.dataDir = pkg.applicationInfo.dataDir;
11490                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11491                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11492                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11493                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11494                mInstrumentation.put(a.getComponentName(), a);
11495                if (chatty) {
11496                    if (r == null) {
11497                        r = new StringBuilder(256);
11498                    } else {
11499                        r.append(' ');
11500                    }
11501                    r.append(a.info.name);
11502                }
11503            }
11504            if (r != null) {
11505                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11506            }
11507
11508            if (pkg.protectedBroadcasts != null) {
11509                N = pkg.protectedBroadcasts.size();
11510                for (i=0; i<N; i++) {
11511                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11512                }
11513            }
11514        }
11515
11516        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11517    }
11518
11519    /**
11520     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11521     * is derived purely on the basis of the contents of {@code scanFile} and
11522     * {@code cpuAbiOverride}.
11523     *
11524     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11525     */
11526    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11527                                 String cpuAbiOverride, boolean extractLibs,
11528                                 File appLib32InstallDir)
11529            throws PackageManagerException {
11530        // Give ourselves some initial paths; we'll come back for another
11531        // pass once we've determined ABI below.
11532        setNativeLibraryPaths(pkg, appLib32InstallDir);
11533
11534        // We would never need to extract libs for forward-locked and external packages,
11535        // since the container service will do it for us. We shouldn't attempt to
11536        // extract libs from system app when it was not updated.
11537        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11538                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11539            extractLibs = false;
11540        }
11541
11542        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11543        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11544
11545        NativeLibraryHelper.Handle handle = null;
11546        try {
11547            handle = NativeLibraryHelper.Handle.create(pkg);
11548            // TODO(multiArch): This can be null for apps that didn't go through the
11549            // usual installation process. We can calculate it again, like we
11550            // do during install time.
11551            //
11552            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11553            // unnecessary.
11554            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11555
11556            // Null out the abis so that they can be recalculated.
11557            pkg.applicationInfo.primaryCpuAbi = null;
11558            pkg.applicationInfo.secondaryCpuAbi = null;
11559            if (isMultiArch(pkg.applicationInfo)) {
11560                // Warn if we've set an abiOverride for multi-lib packages..
11561                // By definition, we need to copy both 32 and 64 bit libraries for
11562                // such packages.
11563                if (pkg.cpuAbiOverride != null
11564                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11565                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11566                }
11567
11568                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11569                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11570                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11571                    if (extractLibs) {
11572                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11573                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11574                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11575                                useIsaSpecificSubdirs);
11576                    } else {
11577                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11578                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11579                    }
11580                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11581                }
11582
11583                maybeThrowExceptionForMultiArchCopy(
11584                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11585
11586                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11587                    if (extractLibs) {
11588                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11589                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11590                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11591                                useIsaSpecificSubdirs);
11592                    } else {
11593                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11594                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11595                    }
11596                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11597                }
11598
11599                maybeThrowExceptionForMultiArchCopy(
11600                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11601
11602                if (abi64 >= 0) {
11603                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11604                }
11605
11606                if (abi32 >= 0) {
11607                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11608                    if (abi64 >= 0) {
11609                        if (pkg.use32bitAbi) {
11610                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11611                            pkg.applicationInfo.primaryCpuAbi = abi;
11612                        } else {
11613                            pkg.applicationInfo.secondaryCpuAbi = abi;
11614                        }
11615                    } else {
11616                        pkg.applicationInfo.primaryCpuAbi = abi;
11617                    }
11618                }
11619
11620            } else {
11621                String[] abiList = (cpuAbiOverride != null) ?
11622                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11623
11624                // Enable gross and lame hacks for apps that are built with old
11625                // SDK tools. We must scan their APKs for renderscript bitcode and
11626                // not launch them if it's present. Don't bother checking on devices
11627                // that don't have 64 bit support.
11628                boolean needsRenderScriptOverride = false;
11629                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11630                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11631                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11632                    needsRenderScriptOverride = true;
11633                }
11634
11635                final int copyRet;
11636                if (extractLibs) {
11637                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11638                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11639                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11640                } else {
11641                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11642                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11643                }
11644                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11645
11646                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11647                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11648                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11649                }
11650
11651                if (copyRet >= 0) {
11652                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11653                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11654                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11655                } else if (needsRenderScriptOverride) {
11656                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11657                }
11658            }
11659        } catch (IOException ioe) {
11660            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11661        } finally {
11662            IoUtils.closeQuietly(handle);
11663        }
11664
11665        // Now that we've calculated the ABIs and determined if it's an internal app,
11666        // we will go ahead and populate the nativeLibraryPath.
11667        setNativeLibraryPaths(pkg, appLib32InstallDir);
11668    }
11669
11670    /**
11671     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11672     * i.e, so that all packages can be run inside a single process if required.
11673     *
11674     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11675     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11676     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11677     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11678     * updating a package that belongs to a shared user.
11679     *
11680     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11681     * adds unnecessary complexity.
11682     */
11683    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11684            PackageParser.Package scannedPackage) {
11685        String requiredInstructionSet = null;
11686        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11687            requiredInstructionSet = VMRuntime.getInstructionSet(
11688                     scannedPackage.applicationInfo.primaryCpuAbi);
11689        }
11690
11691        PackageSetting requirer = null;
11692        for (PackageSetting ps : packagesForUser) {
11693            // If packagesForUser contains scannedPackage, we skip it. This will happen
11694            // when scannedPackage is an update of an existing package. Without this check,
11695            // we will never be able to change the ABI of any package belonging to a shared
11696            // user, even if it's compatible with other packages.
11697            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11698                if (ps.primaryCpuAbiString == null) {
11699                    continue;
11700                }
11701
11702                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11703                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11704                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11705                    // this but there's not much we can do.
11706                    String errorMessage = "Instruction set mismatch, "
11707                            + ((requirer == null) ? "[caller]" : requirer)
11708                            + " requires " + requiredInstructionSet + " whereas " + ps
11709                            + " requires " + instructionSet;
11710                    Slog.w(TAG, errorMessage);
11711                }
11712
11713                if (requiredInstructionSet == null) {
11714                    requiredInstructionSet = instructionSet;
11715                    requirer = ps;
11716                }
11717            }
11718        }
11719
11720        if (requiredInstructionSet != null) {
11721            String adjustedAbi;
11722            if (requirer != null) {
11723                // requirer != null implies that either scannedPackage was null or that scannedPackage
11724                // did not require an ABI, in which case we have to adjust scannedPackage to match
11725                // the ABI of the set (which is the same as requirer's ABI)
11726                adjustedAbi = requirer.primaryCpuAbiString;
11727                if (scannedPackage != null) {
11728                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11729                }
11730            } else {
11731                // requirer == null implies that we're updating all ABIs in the set to
11732                // match scannedPackage.
11733                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11734            }
11735
11736            for (PackageSetting ps : packagesForUser) {
11737                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11738                    if (ps.primaryCpuAbiString != null) {
11739                        continue;
11740                    }
11741
11742                    ps.primaryCpuAbiString = adjustedAbi;
11743                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11744                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11745                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11746                        if (DEBUG_ABI_SELECTION) {
11747                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11748                                    + " (requirer="
11749                                    + (requirer != null ? requirer.pkg : "null")
11750                                    + ", scannedPackage="
11751                                    + (scannedPackage != null ? scannedPackage : "null")
11752                                    + ")");
11753                        }
11754                        try {
11755                            mInstaller.rmdex(ps.codePathString,
11756                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11757                        } catch (InstallerException ignored) {
11758                        }
11759                    }
11760                }
11761            }
11762        }
11763    }
11764
11765    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11766        synchronized (mPackages) {
11767            mResolverReplaced = true;
11768            // Set up information for custom user intent resolution activity.
11769            mResolveActivity.applicationInfo = pkg.applicationInfo;
11770            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11771            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11772            mResolveActivity.processName = pkg.applicationInfo.packageName;
11773            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11774            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11775                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11776            mResolveActivity.theme = 0;
11777            mResolveActivity.exported = true;
11778            mResolveActivity.enabled = true;
11779            mResolveInfo.activityInfo = mResolveActivity;
11780            mResolveInfo.priority = 0;
11781            mResolveInfo.preferredOrder = 0;
11782            mResolveInfo.match = 0;
11783            mResolveComponentName = mCustomResolverComponentName;
11784            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11785                    mResolveComponentName);
11786        }
11787    }
11788
11789    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11790        if (installerActivity == null) {
11791            if (DEBUG_EPHEMERAL) {
11792                Slog.d(TAG, "Clear ephemeral installer activity");
11793            }
11794            mInstantAppInstallerActivity = null;
11795            return;
11796        }
11797
11798        if (DEBUG_EPHEMERAL) {
11799            Slog.d(TAG, "Set ephemeral installer activity: "
11800                    + installerActivity.getComponentName());
11801        }
11802        // Set up information for ephemeral installer activity
11803        mInstantAppInstallerActivity = installerActivity;
11804        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11805                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11806        mInstantAppInstallerActivity.exported = true;
11807        mInstantAppInstallerActivity.enabled = true;
11808        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11809        mInstantAppInstallerInfo.priority = 0;
11810        mInstantAppInstallerInfo.preferredOrder = 1;
11811        mInstantAppInstallerInfo.isDefault = true;
11812        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11813                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11814    }
11815
11816    private static String calculateBundledApkRoot(final String codePathString) {
11817        final File codePath = new File(codePathString);
11818        final File codeRoot;
11819        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11820            codeRoot = Environment.getRootDirectory();
11821        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11822            codeRoot = Environment.getOemDirectory();
11823        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11824            codeRoot = Environment.getVendorDirectory();
11825        } else {
11826            // Unrecognized code path; take its top real segment as the apk root:
11827            // e.g. /something/app/blah.apk => /something
11828            try {
11829                File f = codePath.getCanonicalFile();
11830                File parent = f.getParentFile();    // non-null because codePath is a file
11831                File tmp;
11832                while ((tmp = parent.getParentFile()) != null) {
11833                    f = parent;
11834                    parent = tmp;
11835                }
11836                codeRoot = f;
11837                Slog.w(TAG, "Unrecognized code path "
11838                        + codePath + " - using " + codeRoot);
11839            } catch (IOException e) {
11840                // Can't canonicalize the code path -- shenanigans?
11841                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11842                return Environment.getRootDirectory().getPath();
11843            }
11844        }
11845        return codeRoot.getPath();
11846    }
11847
11848    /**
11849     * Derive and set the location of native libraries for the given package,
11850     * which varies depending on where and how the package was installed.
11851     */
11852    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11853        final ApplicationInfo info = pkg.applicationInfo;
11854        final String codePath = pkg.codePath;
11855        final File codeFile = new File(codePath);
11856        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11857        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11858
11859        info.nativeLibraryRootDir = null;
11860        info.nativeLibraryRootRequiresIsa = false;
11861        info.nativeLibraryDir = null;
11862        info.secondaryNativeLibraryDir = null;
11863
11864        if (isApkFile(codeFile)) {
11865            // Monolithic install
11866            if (bundledApp) {
11867                // If "/system/lib64/apkname" exists, assume that is the per-package
11868                // native library directory to use; otherwise use "/system/lib/apkname".
11869                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11870                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11871                        getPrimaryInstructionSet(info));
11872
11873                // This is a bundled system app so choose the path based on the ABI.
11874                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11875                // is just the default path.
11876                final String apkName = deriveCodePathName(codePath);
11877                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11878                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11879                        apkName).getAbsolutePath();
11880
11881                if (info.secondaryCpuAbi != null) {
11882                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11883                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11884                            secondaryLibDir, apkName).getAbsolutePath();
11885                }
11886            } else if (asecApp) {
11887                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11888                        .getAbsolutePath();
11889            } else {
11890                final String apkName = deriveCodePathName(codePath);
11891                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11892                        .getAbsolutePath();
11893            }
11894
11895            info.nativeLibraryRootRequiresIsa = false;
11896            info.nativeLibraryDir = info.nativeLibraryRootDir;
11897        } else {
11898            // Cluster install
11899            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11900            info.nativeLibraryRootRequiresIsa = true;
11901
11902            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11903                    getPrimaryInstructionSet(info)).getAbsolutePath();
11904
11905            if (info.secondaryCpuAbi != null) {
11906                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11907                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11908            }
11909        }
11910    }
11911
11912    /**
11913     * Calculate the abis and roots for a bundled app. These can uniquely
11914     * be determined from the contents of the system partition, i.e whether
11915     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11916     * of this information, and instead assume that the system was built
11917     * sensibly.
11918     */
11919    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11920                                           PackageSetting pkgSetting) {
11921        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11922
11923        // If "/system/lib64/apkname" exists, assume that is the per-package
11924        // native library directory to use; otherwise use "/system/lib/apkname".
11925        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11926        setBundledAppAbi(pkg, apkRoot, apkName);
11927        // pkgSetting might be null during rescan following uninstall of updates
11928        // to a bundled app, so accommodate that possibility.  The settings in
11929        // that case will be established later from the parsed package.
11930        //
11931        // If the settings aren't null, sync them up with what we've just derived.
11932        // note that apkRoot isn't stored in the package settings.
11933        if (pkgSetting != null) {
11934            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11935            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11936        }
11937    }
11938
11939    /**
11940     * Deduces the ABI of a bundled app and sets the relevant fields on the
11941     * parsed pkg object.
11942     *
11943     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11944     *        under which system libraries are installed.
11945     * @param apkName the name of the installed package.
11946     */
11947    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11948        final File codeFile = new File(pkg.codePath);
11949
11950        final boolean has64BitLibs;
11951        final boolean has32BitLibs;
11952        if (isApkFile(codeFile)) {
11953            // Monolithic install
11954            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11955            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11956        } else {
11957            // Cluster install
11958            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11959            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11960                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11961                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11962                has64BitLibs = (new File(rootDir, isa)).exists();
11963            } else {
11964                has64BitLibs = false;
11965            }
11966            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11967                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11968                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11969                has32BitLibs = (new File(rootDir, isa)).exists();
11970            } else {
11971                has32BitLibs = false;
11972            }
11973        }
11974
11975        if (has64BitLibs && !has32BitLibs) {
11976            // The package has 64 bit libs, but not 32 bit libs. Its primary
11977            // ABI should be 64 bit. We can safely assume here that the bundled
11978            // native libraries correspond to the most preferred ABI in the list.
11979
11980            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11981            pkg.applicationInfo.secondaryCpuAbi = null;
11982        } else if (has32BitLibs && !has64BitLibs) {
11983            // The package has 32 bit libs but not 64 bit libs. Its primary
11984            // ABI should be 32 bit.
11985
11986            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11987            pkg.applicationInfo.secondaryCpuAbi = null;
11988        } else if (has32BitLibs && has64BitLibs) {
11989            // The application has both 64 and 32 bit bundled libraries. We check
11990            // here that the app declares multiArch support, and warn if it doesn't.
11991            //
11992            // We will be lenient here and record both ABIs. The primary will be the
11993            // ABI that's higher on the list, i.e, a device that's configured to prefer
11994            // 64 bit apps will see a 64 bit primary ABI,
11995
11996            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11997                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11998            }
11999
12000            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12001                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12002                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12003            } else {
12004                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12005                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12006            }
12007        } else {
12008            pkg.applicationInfo.primaryCpuAbi = null;
12009            pkg.applicationInfo.secondaryCpuAbi = null;
12010        }
12011    }
12012
12013    private void killApplication(String pkgName, int appId, String reason) {
12014        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12015    }
12016
12017    private void killApplication(String pkgName, int appId, int userId, String reason) {
12018        // Request the ActivityManager to kill the process(only for existing packages)
12019        // so that we do not end up in a confused state while the user is still using the older
12020        // version of the application while the new one gets installed.
12021        final long token = Binder.clearCallingIdentity();
12022        try {
12023            IActivityManager am = ActivityManager.getService();
12024            if (am != null) {
12025                try {
12026                    am.killApplication(pkgName, appId, userId, reason);
12027                } catch (RemoteException e) {
12028                }
12029            }
12030        } finally {
12031            Binder.restoreCallingIdentity(token);
12032        }
12033    }
12034
12035    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12036        // Remove the parent package setting
12037        PackageSetting ps = (PackageSetting) pkg.mExtras;
12038        if (ps != null) {
12039            removePackageLI(ps, chatty);
12040        }
12041        // Remove the child package setting
12042        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12043        for (int i = 0; i < childCount; i++) {
12044            PackageParser.Package childPkg = pkg.childPackages.get(i);
12045            ps = (PackageSetting) childPkg.mExtras;
12046            if (ps != null) {
12047                removePackageLI(ps, chatty);
12048            }
12049        }
12050    }
12051
12052    void removePackageLI(PackageSetting ps, boolean chatty) {
12053        if (DEBUG_INSTALL) {
12054            if (chatty)
12055                Log.d(TAG, "Removing package " + ps.name);
12056        }
12057
12058        // writer
12059        synchronized (mPackages) {
12060            mPackages.remove(ps.name);
12061            final PackageParser.Package pkg = ps.pkg;
12062            if (pkg != null) {
12063                cleanPackageDataStructuresLILPw(pkg, chatty);
12064            }
12065        }
12066    }
12067
12068    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12069        if (DEBUG_INSTALL) {
12070            if (chatty)
12071                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12072        }
12073
12074        // writer
12075        synchronized (mPackages) {
12076            // Remove the parent package
12077            mPackages.remove(pkg.applicationInfo.packageName);
12078            cleanPackageDataStructuresLILPw(pkg, chatty);
12079
12080            // Remove the child packages
12081            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12082            for (int i = 0; i < childCount; i++) {
12083                PackageParser.Package childPkg = pkg.childPackages.get(i);
12084                mPackages.remove(childPkg.applicationInfo.packageName);
12085                cleanPackageDataStructuresLILPw(childPkg, chatty);
12086            }
12087        }
12088    }
12089
12090    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12091        int N = pkg.providers.size();
12092        StringBuilder r = null;
12093        int i;
12094        for (i=0; i<N; i++) {
12095            PackageParser.Provider p = pkg.providers.get(i);
12096            mProviders.removeProvider(p);
12097            if (p.info.authority == null) {
12098
12099                /* There was another ContentProvider with this authority when
12100                 * this app was installed so this authority is null,
12101                 * Ignore it as we don't have to unregister the provider.
12102                 */
12103                continue;
12104            }
12105            String names[] = p.info.authority.split(";");
12106            for (int j = 0; j < names.length; j++) {
12107                if (mProvidersByAuthority.get(names[j]) == p) {
12108                    mProvidersByAuthority.remove(names[j]);
12109                    if (DEBUG_REMOVE) {
12110                        if (chatty)
12111                            Log.d(TAG, "Unregistered content provider: " + names[j]
12112                                    + ", className = " + p.info.name + ", isSyncable = "
12113                                    + p.info.isSyncable);
12114                    }
12115                }
12116            }
12117            if (DEBUG_REMOVE && chatty) {
12118                if (r == null) {
12119                    r = new StringBuilder(256);
12120                } else {
12121                    r.append(' ');
12122                }
12123                r.append(p.info.name);
12124            }
12125        }
12126        if (r != null) {
12127            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12128        }
12129
12130        N = pkg.services.size();
12131        r = null;
12132        for (i=0; i<N; i++) {
12133            PackageParser.Service s = pkg.services.get(i);
12134            mServices.removeService(s);
12135            if (chatty) {
12136                if (r == null) {
12137                    r = new StringBuilder(256);
12138                } else {
12139                    r.append(' ');
12140                }
12141                r.append(s.info.name);
12142            }
12143        }
12144        if (r != null) {
12145            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12146        }
12147
12148        N = pkg.receivers.size();
12149        r = null;
12150        for (i=0; i<N; i++) {
12151            PackageParser.Activity a = pkg.receivers.get(i);
12152            mReceivers.removeActivity(a, "receiver");
12153            if (DEBUG_REMOVE && chatty) {
12154                if (r == null) {
12155                    r = new StringBuilder(256);
12156                } else {
12157                    r.append(' ');
12158                }
12159                r.append(a.info.name);
12160            }
12161        }
12162        if (r != null) {
12163            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12164        }
12165
12166        N = pkg.activities.size();
12167        r = null;
12168        for (i=0; i<N; i++) {
12169            PackageParser.Activity a = pkg.activities.get(i);
12170            mActivities.removeActivity(a, "activity");
12171            if (DEBUG_REMOVE && chatty) {
12172                if (r == null) {
12173                    r = new StringBuilder(256);
12174                } else {
12175                    r.append(' ');
12176                }
12177                r.append(a.info.name);
12178            }
12179        }
12180        if (r != null) {
12181            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12182        }
12183
12184        N = pkg.permissions.size();
12185        r = null;
12186        for (i=0; i<N; i++) {
12187            PackageParser.Permission p = pkg.permissions.get(i);
12188            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12189            if (bp == null) {
12190                bp = mSettings.mPermissionTrees.get(p.info.name);
12191            }
12192            if (bp != null && bp.perm == p) {
12193                bp.perm = null;
12194                if (DEBUG_REMOVE && chatty) {
12195                    if (r == null) {
12196                        r = new StringBuilder(256);
12197                    } else {
12198                        r.append(' ');
12199                    }
12200                    r.append(p.info.name);
12201                }
12202            }
12203            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12204                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12205                if (appOpPkgs != null) {
12206                    appOpPkgs.remove(pkg.packageName);
12207                }
12208            }
12209        }
12210        if (r != null) {
12211            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12212        }
12213
12214        N = pkg.requestedPermissions.size();
12215        r = null;
12216        for (i=0; i<N; i++) {
12217            String perm = pkg.requestedPermissions.get(i);
12218            BasePermission bp = mSettings.mPermissions.get(perm);
12219            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12220                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12221                if (appOpPkgs != null) {
12222                    appOpPkgs.remove(pkg.packageName);
12223                    if (appOpPkgs.isEmpty()) {
12224                        mAppOpPermissionPackages.remove(perm);
12225                    }
12226                }
12227            }
12228        }
12229        if (r != null) {
12230            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12231        }
12232
12233        N = pkg.instrumentation.size();
12234        r = null;
12235        for (i=0; i<N; i++) {
12236            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12237            mInstrumentation.remove(a.getComponentName());
12238            if (DEBUG_REMOVE && chatty) {
12239                if (r == null) {
12240                    r = new StringBuilder(256);
12241                } else {
12242                    r.append(' ');
12243                }
12244                r.append(a.info.name);
12245            }
12246        }
12247        if (r != null) {
12248            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12249        }
12250
12251        r = null;
12252        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12253            // Only system apps can hold shared libraries.
12254            if (pkg.libraryNames != null) {
12255                for (i = 0; i < pkg.libraryNames.size(); i++) {
12256                    String name = pkg.libraryNames.get(i);
12257                    if (removeSharedLibraryLPw(name, 0)) {
12258                        if (DEBUG_REMOVE && chatty) {
12259                            if (r == null) {
12260                                r = new StringBuilder(256);
12261                            } else {
12262                                r.append(' ');
12263                            }
12264                            r.append(name);
12265                        }
12266                    }
12267                }
12268            }
12269        }
12270
12271        r = null;
12272
12273        // Any package can hold static shared libraries.
12274        if (pkg.staticSharedLibName != null) {
12275            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12276                if (DEBUG_REMOVE && chatty) {
12277                    if (r == null) {
12278                        r = new StringBuilder(256);
12279                    } else {
12280                        r.append(' ');
12281                    }
12282                    r.append(pkg.staticSharedLibName);
12283                }
12284            }
12285        }
12286
12287        if (r != null) {
12288            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12289        }
12290    }
12291
12292    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12293        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12294            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12295                return true;
12296            }
12297        }
12298        return false;
12299    }
12300
12301    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12302    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12303    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12304
12305    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12306        // Update the parent permissions
12307        updatePermissionsLPw(pkg.packageName, pkg, flags);
12308        // Update the child permissions
12309        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12310        for (int i = 0; i < childCount; i++) {
12311            PackageParser.Package childPkg = pkg.childPackages.get(i);
12312            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12313        }
12314    }
12315
12316    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12317            int flags) {
12318        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12319        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12320    }
12321
12322    private void updatePermissionsLPw(String changingPkg,
12323            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12324        // Make sure there are no dangling permission trees.
12325        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12326        while (it.hasNext()) {
12327            final BasePermission bp = it.next();
12328            if (bp.packageSetting == null) {
12329                // We may not yet have parsed the package, so just see if
12330                // we still know about its settings.
12331                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12332            }
12333            if (bp.packageSetting == null) {
12334                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12335                        + " from package " + bp.sourcePackage);
12336                it.remove();
12337            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12338                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12339                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12340                            + " from package " + bp.sourcePackage);
12341                    flags |= UPDATE_PERMISSIONS_ALL;
12342                    it.remove();
12343                }
12344            }
12345        }
12346
12347        // Make sure all dynamic permissions have been assigned to a package,
12348        // and make sure there are no dangling permissions.
12349        it = mSettings.mPermissions.values().iterator();
12350        while (it.hasNext()) {
12351            final BasePermission bp = it.next();
12352            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12353                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12354                        + bp.name + " pkg=" + bp.sourcePackage
12355                        + " info=" + bp.pendingInfo);
12356                if (bp.packageSetting == null && bp.pendingInfo != null) {
12357                    final BasePermission tree = findPermissionTreeLP(bp.name);
12358                    if (tree != null && tree.perm != null) {
12359                        bp.packageSetting = tree.packageSetting;
12360                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12361                                new PermissionInfo(bp.pendingInfo));
12362                        bp.perm.info.packageName = tree.perm.info.packageName;
12363                        bp.perm.info.name = bp.name;
12364                        bp.uid = tree.uid;
12365                    }
12366                }
12367            }
12368            if (bp.packageSetting == null) {
12369                // We may not yet have parsed the package, so just see if
12370                // we still know about its settings.
12371                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12372            }
12373            if (bp.packageSetting == null) {
12374                Slog.w(TAG, "Removing dangling permission: " + bp.name
12375                        + " from package " + bp.sourcePackage);
12376                it.remove();
12377            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12378                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12379                    Slog.i(TAG, "Removing old permission: " + bp.name
12380                            + " from package " + bp.sourcePackage);
12381                    flags |= UPDATE_PERMISSIONS_ALL;
12382                    it.remove();
12383                }
12384            }
12385        }
12386
12387        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12388        // Now update the permissions for all packages, in particular
12389        // replace the granted permissions of the system packages.
12390        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12391            for (PackageParser.Package pkg : mPackages.values()) {
12392                if (pkg != pkgInfo) {
12393                    // Only replace for packages on requested volume
12394                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12395                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12396                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12397                    grantPermissionsLPw(pkg, replace, changingPkg);
12398                }
12399            }
12400        }
12401
12402        if (pkgInfo != null) {
12403            // Only replace for packages on requested volume
12404            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12405            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12406                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12407            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12408        }
12409        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12410    }
12411
12412    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12413            String packageOfInterest) {
12414        // IMPORTANT: There are two types of permissions: install and runtime.
12415        // Install time permissions are granted when the app is installed to
12416        // all device users and users added in the future. Runtime permissions
12417        // are granted at runtime explicitly to specific users. Normal and signature
12418        // protected permissions are install time permissions. Dangerous permissions
12419        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12420        // otherwise they are runtime permissions. This function does not manage
12421        // runtime permissions except for the case an app targeting Lollipop MR1
12422        // being upgraded to target a newer SDK, in which case dangerous permissions
12423        // are transformed from install time to runtime ones.
12424
12425        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12426        if (ps == null) {
12427            return;
12428        }
12429
12430        PermissionsState permissionsState = ps.getPermissionsState();
12431        PermissionsState origPermissions = permissionsState;
12432
12433        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12434
12435        boolean runtimePermissionsRevoked = false;
12436        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12437
12438        boolean changedInstallPermission = false;
12439
12440        if (replace) {
12441            ps.installPermissionsFixed = false;
12442            if (!ps.isSharedUser()) {
12443                origPermissions = new PermissionsState(permissionsState);
12444                permissionsState.reset();
12445            } else {
12446                // We need to know only about runtime permission changes since the
12447                // calling code always writes the install permissions state but
12448                // the runtime ones are written only if changed. The only cases of
12449                // changed runtime permissions here are promotion of an install to
12450                // runtime and revocation of a runtime from a shared user.
12451                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12452                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12453                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12454                    runtimePermissionsRevoked = true;
12455                }
12456            }
12457        }
12458
12459        permissionsState.setGlobalGids(mGlobalGids);
12460
12461        final int N = pkg.requestedPermissions.size();
12462        for (int i=0; i<N; i++) {
12463            final String name = pkg.requestedPermissions.get(i);
12464            final BasePermission bp = mSettings.mPermissions.get(name);
12465            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12466                    >= Build.VERSION_CODES.M;
12467
12468            if (DEBUG_INSTALL) {
12469                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12470            }
12471
12472            if (bp == null || bp.packageSetting == null) {
12473                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12474                    if (DEBUG_PERMISSIONS) {
12475                        Slog.i(TAG, "Unknown permission " + name
12476                                + " in package " + pkg.packageName);
12477                    }
12478                }
12479                continue;
12480            }
12481
12482
12483            // Limit ephemeral apps to ephemeral allowed permissions.
12484            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12485                if (DEBUG_PERMISSIONS) {
12486                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12487                            + pkg.packageName);
12488                }
12489                continue;
12490            }
12491
12492            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12493                if (DEBUG_PERMISSIONS) {
12494                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12495                            + pkg.packageName);
12496                }
12497                continue;
12498            }
12499
12500            final String perm = bp.name;
12501            boolean allowedSig = false;
12502            int grant = GRANT_DENIED;
12503
12504            // Keep track of app op permissions.
12505            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12506                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12507                if (pkgs == null) {
12508                    pkgs = new ArraySet<>();
12509                    mAppOpPermissionPackages.put(bp.name, pkgs);
12510                }
12511                pkgs.add(pkg.packageName);
12512            }
12513
12514            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12515            switch (level) {
12516                case PermissionInfo.PROTECTION_NORMAL: {
12517                    // For all apps normal permissions are install time ones.
12518                    grant = GRANT_INSTALL;
12519                } break;
12520
12521                case PermissionInfo.PROTECTION_DANGEROUS: {
12522                    // If a permission review is required for legacy apps we represent
12523                    // their permissions as always granted runtime ones since we need
12524                    // to keep the review required permission flag per user while an
12525                    // install permission's state is shared across all users.
12526                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12527                        // For legacy apps dangerous permissions are install time ones.
12528                        grant = GRANT_INSTALL;
12529                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12530                        // For legacy apps that became modern, install becomes runtime.
12531                        grant = GRANT_UPGRADE;
12532                    } else if (mPromoteSystemApps
12533                            && isSystemApp(ps)
12534                            && mExistingSystemPackages.contains(ps.name)) {
12535                        // For legacy system apps, install becomes runtime.
12536                        // We cannot check hasInstallPermission() for system apps since those
12537                        // permissions were granted implicitly and not persisted pre-M.
12538                        grant = GRANT_UPGRADE;
12539                    } else {
12540                        // For modern apps keep runtime permissions unchanged.
12541                        grant = GRANT_RUNTIME;
12542                    }
12543                } break;
12544
12545                case PermissionInfo.PROTECTION_SIGNATURE: {
12546                    // For all apps signature permissions are install time ones.
12547                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12548                    if (allowedSig) {
12549                        grant = GRANT_INSTALL;
12550                    }
12551                } break;
12552            }
12553
12554            if (DEBUG_PERMISSIONS) {
12555                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12556            }
12557
12558            if (grant != GRANT_DENIED) {
12559                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12560                    // If this is an existing, non-system package, then
12561                    // we can't add any new permissions to it.
12562                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12563                        // Except...  if this is a permission that was added
12564                        // to the platform (note: need to only do this when
12565                        // updating the platform).
12566                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12567                            grant = GRANT_DENIED;
12568                        }
12569                    }
12570                }
12571
12572                switch (grant) {
12573                    case GRANT_INSTALL: {
12574                        // Revoke this as runtime permission to handle the case of
12575                        // a runtime permission being downgraded to an install one.
12576                        // Also in permission review mode we keep dangerous permissions
12577                        // for legacy apps
12578                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12579                            if (origPermissions.getRuntimePermissionState(
12580                                    bp.name, userId) != null) {
12581                                // Revoke the runtime permission and clear the flags.
12582                                origPermissions.revokeRuntimePermission(bp, userId);
12583                                origPermissions.updatePermissionFlags(bp, userId,
12584                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12585                                // If we revoked a permission permission, we have to write.
12586                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12587                                        changedRuntimePermissionUserIds, userId);
12588                            }
12589                        }
12590                        // Grant an install permission.
12591                        if (permissionsState.grantInstallPermission(bp) !=
12592                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12593                            changedInstallPermission = true;
12594                        }
12595                    } break;
12596
12597                    case GRANT_RUNTIME: {
12598                        // Grant previously granted runtime permissions.
12599                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12600                            PermissionState permissionState = origPermissions
12601                                    .getRuntimePermissionState(bp.name, userId);
12602                            int flags = permissionState != null
12603                                    ? permissionState.getFlags() : 0;
12604                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12605                                // Don't propagate the permission in a permission review mode if
12606                                // the former was revoked, i.e. marked to not propagate on upgrade.
12607                                // Note that in a permission review mode install permissions are
12608                                // represented as constantly granted runtime ones since we need to
12609                                // keep a per user state associated with the permission. Also the
12610                                // revoke on upgrade flag is no longer applicable and is reset.
12611                                final boolean revokeOnUpgrade = (flags & PackageManager
12612                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12613                                if (revokeOnUpgrade) {
12614                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12615                                    // Since we changed the flags, we have to write.
12616                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12617                                            changedRuntimePermissionUserIds, userId);
12618                                }
12619                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12620                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12621                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12622                                        // If we cannot put the permission as it was,
12623                                        // we have to write.
12624                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12625                                                changedRuntimePermissionUserIds, userId);
12626                                    }
12627                                }
12628
12629                                // If the app supports runtime permissions no need for a review.
12630                                if (mPermissionReviewRequired
12631                                        && appSupportsRuntimePermissions
12632                                        && (flags & PackageManager
12633                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12634                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12635                                    // Since we changed the flags, we have to write.
12636                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12637                                            changedRuntimePermissionUserIds, userId);
12638                                }
12639                            } else if (mPermissionReviewRequired
12640                                    && !appSupportsRuntimePermissions) {
12641                                // For legacy apps that need a permission review, every new
12642                                // runtime permission is granted but it is pending a review.
12643                                // We also need to review only platform defined runtime
12644                                // permissions as these are the only ones the platform knows
12645                                // how to disable the API to simulate revocation as legacy
12646                                // apps don't expect to run with revoked permissions.
12647                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12648                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12649                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12650                                        // We changed the flags, hence have to write.
12651                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12652                                                changedRuntimePermissionUserIds, userId);
12653                                    }
12654                                }
12655                                if (permissionsState.grantRuntimePermission(bp, userId)
12656                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12657                                    // We changed the permission, hence have to write.
12658                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12659                                            changedRuntimePermissionUserIds, userId);
12660                                }
12661                            }
12662                            // Propagate the permission flags.
12663                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12664                        }
12665                    } break;
12666
12667                    case GRANT_UPGRADE: {
12668                        // Grant runtime permissions for a previously held install permission.
12669                        PermissionState permissionState = origPermissions
12670                                .getInstallPermissionState(bp.name);
12671                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12672
12673                        if (origPermissions.revokeInstallPermission(bp)
12674                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12675                            // We will be transferring the permission flags, so clear them.
12676                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12677                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12678                            changedInstallPermission = true;
12679                        }
12680
12681                        // If the permission is not to be promoted to runtime we ignore it and
12682                        // also its other flags as they are not applicable to install permissions.
12683                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12684                            for (int userId : currentUserIds) {
12685                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12686                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12687                                    // Transfer the permission flags.
12688                                    permissionsState.updatePermissionFlags(bp, userId,
12689                                            flags, flags);
12690                                    // If we granted the permission, we have to write.
12691                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12692                                            changedRuntimePermissionUserIds, userId);
12693                                }
12694                            }
12695                        }
12696                    } break;
12697
12698                    default: {
12699                        if (packageOfInterest == null
12700                                || packageOfInterest.equals(pkg.packageName)) {
12701                            if (DEBUG_PERMISSIONS) {
12702                                Slog.i(TAG, "Not granting permission " + perm
12703                                        + " to package " + pkg.packageName
12704                                        + " because it was previously installed without");
12705                            }
12706                        }
12707                    } break;
12708                }
12709            } else {
12710                if (permissionsState.revokeInstallPermission(bp) !=
12711                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12712                    // Also drop the permission flags.
12713                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12714                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12715                    changedInstallPermission = true;
12716                    Slog.i(TAG, "Un-granting permission " + perm
12717                            + " from package " + pkg.packageName
12718                            + " (protectionLevel=" + bp.protectionLevel
12719                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12720                            + ")");
12721                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12722                    // Don't print warning for app op permissions, since it is fine for them
12723                    // not to be granted, there is a UI for the user to decide.
12724                    if (DEBUG_PERMISSIONS
12725                            && (packageOfInterest == null
12726                                    || packageOfInterest.equals(pkg.packageName))) {
12727                        Slog.i(TAG, "Not granting permission " + perm
12728                                + " to package " + pkg.packageName
12729                                + " (protectionLevel=" + bp.protectionLevel
12730                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12731                                + ")");
12732                    }
12733                }
12734            }
12735        }
12736
12737        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12738                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12739            // This is the first that we have heard about this package, so the
12740            // permissions we have now selected are fixed until explicitly
12741            // changed.
12742            ps.installPermissionsFixed = true;
12743        }
12744
12745        // Persist the runtime permissions state for users with changes. If permissions
12746        // were revoked because no app in the shared user declares them we have to
12747        // write synchronously to avoid losing runtime permissions state.
12748        for (int userId : changedRuntimePermissionUserIds) {
12749            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12750        }
12751    }
12752
12753    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12754        boolean allowed = false;
12755        final int NP = PackageParser.NEW_PERMISSIONS.length;
12756        for (int ip=0; ip<NP; ip++) {
12757            final PackageParser.NewPermissionInfo npi
12758                    = PackageParser.NEW_PERMISSIONS[ip];
12759            if (npi.name.equals(perm)
12760                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12761                allowed = true;
12762                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12763                        + pkg.packageName);
12764                break;
12765            }
12766        }
12767        return allowed;
12768    }
12769
12770    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12771            BasePermission bp, PermissionsState origPermissions) {
12772        boolean privilegedPermission = (bp.protectionLevel
12773                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12774        boolean privappPermissionsDisable =
12775                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12776        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12777        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12778        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12779                && !platformPackage && platformPermission) {
12780            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12781                    .getPrivAppPermissions(pkg.packageName);
12782            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12783            if (!whitelisted) {
12784                Slog.w(TAG, "Privileged permission " + perm + " for package "
12785                        + pkg.packageName + " - not in privapp-permissions whitelist");
12786                // Only report violations for apps on system image
12787                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12788                    if (mPrivappPermissionsViolations == null) {
12789                        mPrivappPermissionsViolations = new ArraySet<>();
12790                    }
12791                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12792                }
12793                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12794                    return false;
12795                }
12796            }
12797        }
12798        boolean allowed = (compareSignatures(
12799                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12800                        == PackageManager.SIGNATURE_MATCH)
12801                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12802                        == PackageManager.SIGNATURE_MATCH);
12803        if (!allowed && privilegedPermission) {
12804            if (isSystemApp(pkg)) {
12805                // For updated system applications, a system permission
12806                // is granted only if it had been defined by the original application.
12807                if (pkg.isUpdatedSystemApp()) {
12808                    final PackageSetting sysPs = mSettings
12809                            .getDisabledSystemPkgLPr(pkg.packageName);
12810                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12811                        // If the original was granted this permission, we take
12812                        // that grant decision as read and propagate it to the
12813                        // update.
12814                        if (sysPs.isPrivileged()) {
12815                            allowed = true;
12816                        }
12817                    } else {
12818                        // The system apk may have been updated with an older
12819                        // version of the one on the data partition, but which
12820                        // granted a new system permission that it didn't have
12821                        // before.  In this case we do want to allow the app to
12822                        // now get the new permission if the ancestral apk is
12823                        // privileged to get it.
12824                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12825                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12826                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12827                                    allowed = true;
12828                                    break;
12829                                }
12830                            }
12831                        }
12832                        // Also if a privileged parent package on the system image or any of
12833                        // its children requested a privileged permission, the updated child
12834                        // packages can also get the permission.
12835                        if (pkg.parentPackage != null) {
12836                            final PackageSetting disabledSysParentPs = mSettings
12837                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12838                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12839                                    && disabledSysParentPs.isPrivileged()) {
12840                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12841                                    allowed = true;
12842                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12843                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12844                                    for (int i = 0; i < count; i++) {
12845                                        PackageParser.Package disabledSysChildPkg =
12846                                                disabledSysParentPs.pkg.childPackages.get(i);
12847                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12848                                                perm)) {
12849                                            allowed = true;
12850                                            break;
12851                                        }
12852                                    }
12853                                }
12854                            }
12855                        }
12856                    }
12857                } else {
12858                    allowed = isPrivilegedApp(pkg);
12859                }
12860            }
12861        }
12862        if (!allowed) {
12863            if (!allowed && (bp.protectionLevel
12864                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12865                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12866                // If this was a previously normal/dangerous permission that got moved
12867                // to a system permission as part of the runtime permission redesign, then
12868                // we still want to blindly grant it to old apps.
12869                allowed = true;
12870            }
12871            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12872                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12873                // If this permission is to be granted to the system installer and
12874                // this app is an installer, then it gets the permission.
12875                allowed = true;
12876            }
12877            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12878                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12879                // If this permission is to be granted to the system verifier and
12880                // this app is a verifier, then it gets the permission.
12881                allowed = true;
12882            }
12883            if (!allowed && (bp.protectionLevel
12884                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12885                    && isSystemApp(pkg)) {
12886                // Any pre-installed system app is allowed to get this permission.
12887                allowed = true;
12888            }
12889            if (!allowed && (bp.protectionLevel
12890                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12891                // For development permissions, a development permission
12892                // is granted only if it was already granted.
12893                allowed = origPermissions.hasInstallPermission(perm);
12894            }
12895            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12896                    && pkg.packageName.equals(mSetupWizardPackage)) {
12897                // If this permission is to be granted to the system setup wizard and
12898                // this app is a setup wizard, then it gets the permission.
12899                allowed = true;
12900            }
12901        }
12902        return allowed;
12903    }
12904
12905    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12906        final int permCount = pkg.requestedPermissions.size();
12907        for (int j = 0; j < permCount; j++) {
12908            String requestedPermission = pkg.requestedPermissions.get(j);
12909            if (permission.equals(requestedPermission)) {
12910                return true;
12911            }
12912        }
12913        return false;
12914    }
12915
12916    final class ActivityIntentResolver
12917            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12918        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12919                boolean defaultOnly, int userId) {
12920            if (!sUserManager.exists(userId)) return null;
12921            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12922            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12923        }
12924
12925        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12926                int userId) {
12927            if (!sUserManager.exists(userId)) return null;
12928            mFlags = flags;
12929            return super.queryIntent(intent, resolvedType,
12930                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12931                    userId);
12932        }
12933
12934        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12935                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12936            if (!sUserManager.exists(userId)) return null;
12937            if (packageActivities == null) {
12938                return null;
12939            }
12940            mFlags = flags;
12941            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12942            final int N = packageActivities.size();
12943            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12944                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12945
12946            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12947            for (int i = 0; i < N; ++i) {
12948                intentFilters = packageActivities.get(i).intents;
12949                if (intentFilters != null && intentFilters.size() > 0) {
12950                    PackageParser.ActivityIntentInfo[] array =
12951                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12952                    intentFilters.toArray(array);
12953                    listCut.add(array);
12954                }
12955            }
12956            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12957        }
12958
12959        /**
12960         * Finds a privileged activity that matches the specified activity names.
12961         */
12962        private PackageParser.Activity findMatchingActivity(
12963                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12964            for (PackageParser.Activity sysActivity : activityList) {
12965                if (sysActivity.info.name.equals(activityInfo.name)) {
12966                    return sysActivity;
12967                }
12968                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12969                    return sysActivity;
12970                }
12971                if (sysActivity.info.targetActivity != null) {
12972                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12973                        return sysActivity;
12974                    }
12975                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12976                        return sysActivity;
12977                    }
12978                }
12979            }
12980            return null;
12981        }
12982
12983        public class IterGenerator<E> {
12984            public Iterator<E> generate(ActivityIntentInfo info) {
12985                return null;
12986            }
12987        }
12988
12989        public class ActionIterGenerator extends IterGenerator<String> {
12990            @Override
12991            public Iterator<String> generate(ActivityIntentInfo info) {
12992                return info.actionsIterator();
12993            }
12994        }
12995
12996        public class CategoriesIterGenerator extends IterGenerator<String> {
12997            @Override
12998            public Iterator<String> generate(ActivityIntentInfo info) {
12999                return info.categoriesIterator();
13000            }
13001        }
13002
13003        public class SchemesIterGenerator extends IterGenerator<String> {
13004            @Override
13005            public Iterator<String> generate(ActivityIntentInfo info) {
13006                return info.schemesIterator();
13007            }
13008        }
13009
13010        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13011            @Override
13012            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13013                return info.authoritiesIterator();
13014            }
13015        }
13016
13017        /**
13018         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13019         * MODIFIED. Do not pass in a list that should not be changed.
13020         */
13021        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13022                IterGenerator<T> generator, Iterator<T> searchIterator) {
13023            // loop through the set of actions; every one must be found in the intent filter
13024            while (searchIterator.hasNext()) {
13025                // we must have at least one filter in the list to consider a match
13026                if (intentList.size() == 0) {
13027                    break;
13028                }
13029
13030                final T searchAction = searchIterator.next();
13031
13032                // loop through the set of intent filters
13033                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13034                while (intentIter.hasNext()) {
13035                    final ActivityIntentInfo intentInfo = intentIter.next();
13036                    boolean selectionFound = false;
13037
13038                    // loop through the intent filter's selection criteria; at least one
13039                    // of them must match the searched criteria
13040                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13041                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13042                        final T intentSelection = intentSelectionIter.next();
13043                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13044                            selectionFound = true;
13045                            break;
13046                        }
13047                    }
13048
13049                    // the selection criteria wasn't found in this filter's set; this filter
13050                    // is not a potential match
13051                    if (!selectionFound) {
13052                        intentIter.remove();
13053                    }
13054                }
13055            }
13056        }
13057
13058        private boolean isProtectedAction(ActivityIntentInfo filter) {
13059            final Iterator<String> actionsIter = filter.actionsIterator();
13060            while (actionsIter != null && actionsIter.hasNext()) {
13061                final String filterAction = actionsIter.next();
13062                if (PROTECTED_ACTIONS.contains(filterAction)) {
13063                    return true;
13064                }
13065            }
13066            return false;
13067        }
13068
13069        /**
13070         * Adjusts the priority of the given intent filter according to policy.
13071         * <p>
13072         * <ul>
13073         * <li>The priority for non privileged applications is capped to '0'</li>
13074         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13075         * <li>The priority for unbundled updates to privileged applications is capped to the
13076         *      priority defined on the system partition</li>
13077         * </ul>
13078         * <p>
13079         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13080         * allowed to obtain any priority on any action.
13081         */
13082        private void adjustPriority(
13083                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13084            // nothing to do; priority is fine as-is
13085            if (intent.getPriority() <= 0) {
13086                return;
13087            }
13088
13089            final ActivityInfo activityInfo = intent.activity.info;
13090            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13091
13092            final boolean privilegedApp =
13093                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13094            if (!privilegedApp) {
13095                // non-privileged applications can never define a priority >0
13096                if (DEBUG_FILTERS) {
13097                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13098                            + " package: " + applicationInfo.packageName
13099                            + " activity: " + intent.activity.className
13100                            + " origPrio: " + intent.getPriority());
13101                }
13102                intent.setPriority(0);
13103                return;
13104            }
13105
13106            if (systemActivities == null) {
13107                // the system package is not disabled; we're parsing the system partition
13108                if (isProtectedAction(intent)) {
13109                    if (mDeferProtectedFilters) {
13110                        // We can't deal with these just yet. No component should ever obtain a
13111                        // >0 priority for a protected actions, with ONE exception -- the setup
13112                        // wizard. The setup wizard, however, cannot be known until we're able to
13113                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13114                        // until all intent filters have been processed. Chicken, meet egg.
13115                        // Let the filter temporarily have a high priority and rectify the
13116                        // priorities after all system packages have been scanned.
13117                        mProtectedFilters.add(intent);
13118                        if (DEBUG_FILTERS) {
13119                            Slog.i(TAG, "Protected action; save for later;"
13120                                    + " package: " + applicationInfo.packageName
13121                                    + " activity: " + intent.activity.className
13122                                    + " origPrio: " + intent.getPriority());
13123                        }
13124                        return;
13125                    } else {
13126                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13127                            Slog.i(TAG, "No setup wizard;"
13128                                + " All protected intents capped to priority 0");
13129                        }
13130                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13131                            if (DEBUG_FILTERS) {
13132                                Slog.i(TAG, "Found setup wizard;"
13133                                    + " allow priority " + intent.getPriority() + ";"
13134                                    + " package: " + intent.activity.info.packageName
13135                                    + " activity: " + intent.activity.className
13136                                    + " priority: " + intent.getPriority());
13137                            }
13138                            // setup wizard gets whatever it wants
13139                            return;
13140                        }
13141                        if (DEBUG_FILTERS) {
13142                            Slog.i(TAG, "Protected action; cap priority to 0;"
13143                                    + " package: " + intent.activity.info.packageName
13144                                    + " activity: " + intent.activity.className
13145                                    + " origPrio: " + intent.getPriority());
13146                        }
13147                        intent.setPriority(0);
13148                        return;
13149                    }
13150                }
13151                // privileged apps on the system image get whatever priority they request
13152                return;
13153            }
13154
13155            // privileged app unbundled update ... try to find the same activity
13156            final PackageParser.Activity foundActivity =
13157                    findMatchingActivity(systemActivities, activityInfo);
13158            if (foundActivity == null) {
13159                // this is a new activity; it cannot obtain >0 priority
13160                if (DEBUG_FILTERS) {
13161                    Slog.i(TAG, "New activity; cap priority to 0;"
13162                            + " package: " + applicationInfo.packageName
13163                            + " activity: " + intent.activity.className
13164                            + " origPrio: " + intent.getPriority());
13165                }
13166                intent.setPriority(0);
13167                return;
13168            }
13169
13170            // found activity, now check for filter equivalence
13171
13172            // a shallow copy is enough; we modify the list, not its contents
13173            final List<ActivityIntentInfo> intentListCopy =
13174                    new ArrayList<>(foundActivity.intents);
13175            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13176
13177            // find matching action subsets
13178            final Iterator<String> actionsIterator = intent.actionsIterator();
13179            if (actionsIterator != null) {
13180                getIntentListSubset(
13181                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13182                if (intentListCopy.size() == 0) {
13183                    // no more intents to match; we're not equivalent
13184                    if (DEBUG_FILTERS) {
13185                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13186                                + " package: " + applicationInfo.packageName
13187                                + " activity: " + intent.activity.className
13188                                + " origPrio: " + intent.getPriority());
13189                    }
13190                    intent.setPriority(0);
13191                    return;
13192                }
13193            }
13194
13195            // find matching category subsets
13196            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13197            if (categoriesIterator != null) {
13198                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13199                        categoriesIterator);
13200                if (intentListCopy.size() == 0) {
13201                    // no more intents to match; we're not equivalent
13202                    if (DEBUG_FILTERS) {
13203                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13204                                + " package: " + applicationInfo.packageName
13205                                + " activity: " + intent.activity.className
13206                                + " origPrio: " + intent.getPriority());
13207                    }
13208                    intent.setPriority(0);
13209                    return;
13210                }
13211            }
13212
13213            // find matching schemes subsets
13214            final Iterator<String> schemesIterator = intent.schemesIterator();
13215            if (schemesIterator != null) {
13216                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13217                        schemesIterator);
13218                if (intentListCopy.size() == 0) {
13219                    // no more intents to match; we're not equivalent
13220                    if (DEBUG_FILTERS) {
13221                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13222                                + " package: " + applicationInfo.packageName
13223                                + " activity: " + intent.activity.className
13224                                + " origPrio: " + intent.getPriority());
13225                    }
13226                    intent.setPriority(0);
13227                    return;
13228                }
13229            }
13230
13231            // find matching authorities subsets
13232            final Iterator<IntentFilter.AuthorityEntry>
13233                    authoritiesIterator = intent.authoritiesIterator();
13234            if (authoritiesIterator != null) {
13235                getIntentListSubset(intentListCopy,
13236                        new AuthoritiesIterGenerator(),
13237                        authoritiesIterator);
13238                if (intentListCopy.size() == 0) {
13239                    // no more intents to match; we're not equivalent
13240                    if (DEBUG_FILTERS) {
13241                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13242                                + " package: " + applicationInfo.packageName
13243                                + " activity: " + intent.activity.className
13244                                + " origPrio: " + intent.getPriority());
13245                    }
13246                    intent.setPriority(0);
13247                    return;
13248                }
13249            }
13250
13251            // we found matching filter(s); app gets the max priority of all intents
13252            int cappedPriority = 0;
13253            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13254                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13255            }
13256            if (intent.getPriority() > cappedPriority) {
13257                if (DEBUG_FILTERS) {
13258                    Slog.i(TAG, "Found matching filter(s);"
13259                            + " cap priority to " + cappedPriority + ";"
13260                            + " package: " + applicationInfo.packageName
13261                            + " activity: " + intent.activity.className
13262                            + " origPrio: " + intent.getPriority());
13263                }
13264                intent.setPriority(cappedPriority);
13265                return;
13266            }
13267            // all this for nothing; the requested priority was <= what was on the system
13268        }
13269
13270        public final void addActivity(PackageParser.Activity a, String type) {
13271            mActivities.put(a.getComponentName(), a);
13272            if (DEBUG_SHOW_INFO)
13273                Log.v(
13274                TAG, "  " + type + " " +
13275                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13276            if (DEBUG_SHOW_INFO)
13277                Log.v(TAG, "    Class=" + a.info.name);
13278            final int NI = a.intents.size();
13279            for (int j=0; j<NI; j++) {
13280                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13281                if ("activity".equals(type)) {
13282                    final PackageSetting ps =
13283                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13284                    final List<PackageParser.Activity> systemActivities =
13285                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13286                    adjustPriority(systemActivities, intent);
13287                }
13288                if (DEBUG_SHOW_INFO) {
13289                    Log.v(TAG, "    IntentFilter:");
13290                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13291                }
13292                if (!intent.debugCheck()) {
13293                    Log.w(TAG, "==> For Activity " + a.info.name);
13294                }
13295                addFilter(intent);
13296            }
13297        }
13298
13299        public final void removeActivity(PackageParser.Activity a, String type) {
13300            mActivities.remove(a.getComponentName());
13301            if (DEBUG_SHOW_INFO) {
13302                Log.v(TAG, "  " + type + " "
13303                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13304                                : a.info.name) + ":");
13305                Log.v(TAG, "    Class=" + a.info.name);
13306            }
13307            final int NI = a.intents.size();
13308            for (int j=0; j<NI; j++) {
13309                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13310                if (DEBUG_SHOW_INFO) {
13311                    Log.v(TAG, "    IntentFilter:");
13312                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13313                }
13314                removeFilter(intent);
13315            }
13316        }
13317
13318        @Override
13319        protected boolean allowFilterResult(
13320                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13321            ActivityInfo filterAi = filter.activity.info;
13322            for (int i=dest.size()-1; i>=0; i--) {
13323                ActivityInfo destAi = dest.get(i).activityInfo;
13324                if (destAi.name == filterAi.name
13325                        && destAi.packageName == filterAi.packageName) {
13326                    return false;
13327                }
13328            }
13329            return true;
13330        }
13331
13332        @Override
13333        protected ActivityIntentInfo[] newArray(int size) {
13334            return new ActivityIntentInfo[size];
13335        }
13336
13337        @Override
13338        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13339            if (!sUserManager.exists(userId)) return true;
13340            PackageParser.Package p = filter.activity.owner;
13341            if (p != null) {
13342                PackageSetting ps = (PackageSetting)p.mExtras;
13343                if (ps != null) {
13344                    // System apps are never considered stopped for purposes of
13345                    // filtering, because there may be no way for the user to
13346                    // actually re-launch them.
13347                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13348                            && ps.getStopped(userId);
13349                }
13350            }
13351            return false;
13352        }
13353
13354        @Override
13355        protected boolean isPackageForFilter(String packageName,
13356                PackageParser.ActivityIntentInfo info) {
13357            return packageName.equals(info.activity.owner.packageName);
13358        }
13359
13360        @Override
13361        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13362                int match, int userId) {
13363            if (!sUserManager.exists(userId)) return null;
13364            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13365                return null;
13366            }
13367            final PackageParser.Activity activity = info.activity;
13368            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13369            if (ps == null) {
13370                return null;
13371            }
13372            final PackageUserState userState = ps.readUserState(userId);
13373            ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId);
13374            if (ai == null) {
13375                return null;
13376            }
13377            final boolean matchExplicitlyVisibleOnly =
13378                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13379            final boolean matchVisibleToInstantApp =
13380                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13381            final boolean componentVisible =
13382                    matchVisibleToInstantApp
13383                    && info.isVisibleToInstantApp()
13384                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13385            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13386            // throw out filters that aren't visible to ephemeral apps
13387            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13388                return null;
13389            }
13390            // throw out instant app filters if we're not explicitly requesting them
13391            if (!matchInstantApp && userState.instantApp) {
13392                return null;
13393            }
13394            // throw out instant app filters if updates are available; will trigger
13395            // instant app resolution
13396            if (userState.instantApp && ps.isUpdateAvailable()) {
13397                return null;
13398            }
13399            final ResolveInfo res = new ResolveInfo();
13400            res.activityInfo = ai;
13401            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13402                res.filter = info;
13403            }
13404            if (info != null) {
13405                res.handleAllWebDataURI = info.handleAllWebDataURI();
13406            }
13407            res.priority = info.getPriority();
13408            res.preferredOrder = activity.owner.mPreferredOrder;
13409            //System.out.println("Result: " + res.activityInfo.className +
13410            //                   " = " + res.priority);
13411            res.match = match;
13412            res.isDefault = info.hasDefault;
13413            res.labelRes = info.labelRes;
13414            res.nonLocalizedLabel = info.nonLocalizedLabel;
13415            if (userNeedsBadging(userId)) {
13416                res.noResourceId = true;
13417            } else {
13418                res.icon = info.icon;
13419            }
13420            res.iconResourceId = info.icon;
13421            res.system = res.activityInfo.applicationInfo.isSystemApp();
13422            res.isInstantAppAvailable = userState.instantApp;
13423            return res;
13424        }
13425
13426        @Override
13427        protected void sortResults(List<ResolveInfo> results) {
13428            Collections.sort(results, mResolvePrioritySorter);
13429        }
13430
13431        @Override
13432        protected void dumpFilter(PrintWriter out, String prefix,
13433                PackageParser.ActivityIntentInfo filter) {
13434            out.print(prefix); out.print(
13435                    Integer.toHexString(System.identityHashCode(filter.activity)));
13436                    out.print(' ');
13437                    filter.activity.printComponentShortName(out);
13438                    out.print(" filter ");
13439                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13440        }
13441
13442        @Override
13443        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13444            return filter.activity;
13445        }
13446
13447        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13448            PackageParser.Activity activity = (PackageParser.Activity)label;
13449            out.print(prefix); out.print(
13450                    Integer.toHexString(System.identityHashCode(activity)));
13451                    out.print(' ');
13452                    activity.printComponentShortName(out);
13453            if (count > 1) {
13454                out.print(" ("); out.print(count); out.print(" filters)");
13455            }
13456            out.println();
13457        }
13458
13459        // Keys are String (activity class name), values are Activity.
13460        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13461                = new ArrayMap<ComponentName, PackageParser.Activity>();
13462        private int mFlags;
13463    }
13464
13465    private final class ServiceIntentResolver
13466            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13467        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13468                boolean defaultOnly, int userId) {
13469            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13470            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13471        }
13472
13473        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13474                int userId) {
13475            if (!sUserManager.exists(userId)) return null;
13476            mFlags = flags;
13477            return super.queryIntent(intent, resolvedType,
13478                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13479                    userId);
13480        }
13481
13482        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13483                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13484            if (!sUserManager.exists(userId)) return null;
13485            if (packageServices == null) {
13486                return null;
13487            }
13488            mFlags = flags;
13489            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13490            final int N = packageServices.size();
13491            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13492                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13493
13494            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13495            for (int i = 0; i < N; ++i) {
13496                intentFilters = packageServices.get(i).intents;
13497                if (intentFilters != null && intentFilters.size() > 0) {
13498                    PackageParser.ServiceIntentInfo[] array =
13499                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13500                    intentFilters.toArray(array);
13501                    listCut.add(array);
13502                }
13503            }
13504            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13505        }
13506
13507        public final void addService(PackageParser.Service s) {
13508            mServices.put(s.getComponentName(), s);
13509            if (DEBUG_SHOW_INFO) {
13510                Log.v(TAG, "  "
13511                        + (s.info.nonLocalizedLabel != null
13512                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13513                Log.v(TAG, "    Class=" + s.info.name);
13514            }
13515            final int NI = s.intents.size();
13516            int j;
13517            for (j=0; j<NI; j++) {
13518                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13519                if (DEBUG_SHOW_INFO) {
13520                    Log.v(TAG, "    IntentFilter:");
13521                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13522                }
13523                if (!intent.debugCheck()) {
13524                    Log.w(TAG, "==> For Service " + s.info.name);
13525                }
13526                addFilter(intent);
13527            }
13528        }
13529
13530        public final void removeService(PackageParser.Service s) {
13531            mServices.remove(s.getComponentName());
13532            if (DEBUG_SHOW_INFO) {
13533                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13534                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13535                Log.v(TAG, "    Class=" + s.info.name);
13536            }
13537            final int NI = s.intents.size();
13538            int j;
13539            for (j=0; j<NI; j++) {
13540                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13541                if (DEBUG_SHOW_INFO) {
13542                    Log.v(TAG, "    IntentFilter:");
13543                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13544                }
13545                removeFilter(intent);
13546            }
13547        }
13548
13549        @Override
13550        protected boolean allowFilterResult(
13551                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13552            ServiceInfo filterSi = filter.service.info;
13553            for (int i=dest.size()-1; i>=0; i--) {
13554                ServiceInfo destAi = dest.get(i).serviceInfo;
13555                if (destAi.name == filterSi.name
13556                        && destAi.packageName == filterSi.packageName) {
13557                    return false;
13558                }
13559            }
13560            return true;
13561        }
13562
13563        @Override
13564        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13565            return new PackageParser.ServiceIntentInfo[size];
13566        }
13567
13568        @Override
13569        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13570            if (!sUserManager.exists(userId)) return true;
13571            PackageParser.Package p = filter.service.owner;
13572            if (p != null) {
13573                PackageSetting ps = (PackageSetting)p.mExtras;
13574                if (ps != null) {
13575                    // System apps are never considered stopped for purposes of
13576                    // filtering, because there may be no way for the user to
13577                    // actually re-launch them.
13578                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13579                            && ps.getStopped(userId);
13580                }
13581            }
13582            return false;
13583        }
13584
13585        @Override
13586        protected boolean isPackageForFilter(String packageName,
13587                PackageParser.ServiceIntentInfo info) {
13588            return packageName.equals(info.service.owner.packageName);
13589        }
13590
13591        @Override
13592        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13593                int match, int userId) {
13594            if (!sUserManager.exists(userId)) return null;
13595            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13596            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13597                return null;
13598            }
13599            final PackageParser.Service service = info.service;
13600            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13601            if (ps == null) {
13602                return null;
13603            }
13604            final PackageUserState userState = ps.readUserState(userId);
13605            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13606                    userState, userId);
13607            if (si == null) {
13608                return null;
13609            }
13610            final boolean matchVisibleToInstantApp =
13611                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13612            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13613            // throw out filters that aren't visible to ephemeral apps
13614            if (matchVisibleToInstantApp
13615                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13616                return null;
13617            }
13618            // throw out ephemeral filters if we're not explicitly requesting them
13619            if (!isInstantApp && userState.instantApp) {
13620                return null;
13621            }
13622            // throw out instant app filters if updates are available; will trigger
13623            // instant app resolution
13624            if (userState.instantApp && ps.isUpdateAvailable()) {
13625                return null;
13626            }
13627            final ResolveInfo res = new ResolveInfo();
13628            res.serviceInfo = si;
13629            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13630                res.filter = filter;
13631            }
13632            res.priority = info.getPriority();
13633            res.preferredOrder = service.owner.mPreferredOrder;
13634            res.match = match;
13635            res.isDefault = info.hasDefault;
13636            res.labelRes = info.labelRes;
13637            res.nonLocalizedLabel = info.nonLocalizedLabel;
13638            res.icon = info.icon;
13639            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13640            return res;
13641        }
13642
13643        @Override
13644        protected void sortResults(List<ResolveInfo> results) {
13645            Collections.sort(results, mResolvePrioritySorter);
13646        }
13647
13648        @Override
13649        protected void dumpFilter(PrintWriter out, String prefix,
13650                PackageParser.ServiceIntentInfo filter) {
13651            out.print(prefix); out.print(
13652                    Integer.toHexString(System.identityHashCode(filter.service)));
13653                    out.print(' ');
13654                    filter.service.printComponentShortName(out);
13655                    out.print(" filter ");
13656                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13657        }
13658
13659        @Override
13660        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13661            return filter.service;
13662        }
13663
13664        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13665            PackageParser.Service service = (PackageParser.Service)label;
13666            out.print(prefix); out.print(
13667                    Integer.toHexString(System.identityHashCode(service)));
13668                    out.print(' ');
13669                    service.printComponentShortName(out);
13670            if (count > 1) {
13671                out.print(" ("); out.print(count); out.print(" filters)");
13672            }
13673            out.println();
13674        }
13675
13676//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13677//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13678//            final List<ResolveInfo> retList = Lists.newArrayList();
13679//            while (i.hasNext()) {
13680//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13681//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13682//                    retList.add(resolveInfo);
13683//                }
13684//            }
13685//            return retList;
13686//        }
13687
13688        // Keys are String (activity class name), values are Activity.
13689        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13690                = new ArrayMap<ComponentName, PackageParser.Service>();
13691        private int mFlags;
13692    }
13693
13694    private final class ProviderIntentResolver
13695            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13696        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13697                boolean defaultOnly, int userId) {
13698            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13699            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13700        }
13701
13702        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13703                int userId) {
13704            if (!sUserManager.exists(userId))
13705                return null;
13706            mFlags = flags;
13707            return super.queryIntent(intent, resolvedType,
13708                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13709                    userId);
13710        }
13711
13712        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13713                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13714            if (!sUserManager.exists(userId))
13715                return null;
13716            if (packageProviders == null) {
13717                return null;
13718            }
13719            mFlags = flags;
13720            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13721            final int N = packageProviders.size();
13722            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13723                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13724
13725            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13726            for (int i = 0; i < N; ++i) {
13727                intentFilters = packageProviders.get(i).intents;
13728                if (intentFilters != null && intentFilters.size() > 0) {
13729                    PackageParser.ProviderIntentInfo[] array =
13730                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13731                    intentFilters.toArray(array);
13732                    listCut.add(array);
13733                }
13734            }
13735            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13736        }
13737
13738        public final void addProvider(PackageParser.Provider p) {
13739            if (mProviders.containsKey(p.getComponentName())) {
13740                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13741                return;
13742            }
13743
13744            mProviders.put(p.getComponentName(), p);
13745            if (DEBUG_SHOW_INFO) {
13746                Log.v(TAG, "  "
13747                        + (p.info.nonLocalizedLabel != null
13748                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13749                Log.v(TAG, "    Class=" + p.info.name);
13750            }
13751            final int NI = p.intents.size();
13752            int j;
13753            for (j = 0; j < NI; j++) {
13754                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13755                if (DEBUG_SHOW_INFO) {
13756                    Log.v(TAG, "    IntentFilter:");
13757                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13758                }
13759                if (!intent.debugCheck()) {
13760                    Log.w(TAG, "==> For Provider " + p.info.name);
13761                }
13762                addFilter(intent);
13763            }
13764        }
13765
13766        public final void removeProvider(PackageParser.Provider p) {
13767            mProviders.remove(p.getComponentName());
13768            if (DEBUG_SHOW_INFO) {
13769                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13770                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13771                Log.v(TAG, "    Class=" + p.info.name);
13772            }
13773            final int NI = p.intents.size();
13774            int j;
13775            for (j = 0; j < NI; j++) {
13776                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13777                if (DEBUG_SHOW_INFO) {
13778                    Log.v(TAG, "    IntentFilter:");
13779                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13780                }
13781                removeFilter(intent);
13782            }
13783        }
13784
13785        @Override
13786        protected boolean allowFilterResult(
13787                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13788            ProviderInfo filterPi = filter.provider.info;
13789            for (int i = dest.size() - 1; i >= 0; i--) {
13790                ProviderInfo destPi = dest.get(i).providerInfo;
13791                if (destPi.name == filterPi.name
13792                        && destPi.packageName == filterPi.packageName) {
13793                    return false;
13794                }
13795            }
13796            return true;
13797        }
13798
13799        @Override
13800        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13801            return new PackageParser.ProviderIntentInfo[size];
13802        }
13803
13804        @Override
13805        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13806            if (!sUserManager.exists(userId))
13807                return true;
13808            PackageParser.Package p = filter.provider.owner;
13809            if (p != null) {
13810                PackageSetting ps = (PackageSetting) p.mExtras;
13811                if (ps != null) {
13812                    // System apps are never considered stopped for purposes of
13813                    // filtering, because there may be no way for the user to
13814                    // actually re-launch them.
13815                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13816                            && ps.getStopped(userId);
13817                }
13818            }
13819            return false;
13820        }
13821
13822        @Override
13823        protected boolean isPackageForFilter(String packageName,
13824                PackageParser.ProviderIntentInfo info) {
13825            return packageName.equals(info.provider.owner.packageName);
13826        }
13827
13828        @Override
13829        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13830                int match, int userId) {
13831            if (!sUserManager.exists(userId))
13832                return null;
13833            final PackageParser.ProviderIntentInfo info = filter;
13834            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13835                return null;
13836            }
13837            final PackageParser.Provider provider = info.provider;
13838            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13839            if (ps == null) {
13840                return null;
13841            }
13842            final PackageUserState userState = ps.readUserState(userId);
13843            final boolean matchVisibleToInstantApp =
13844                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13845            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13846            // throw out filters that aren't visible to instant applications
13847            if (matchVisibleToInstantApp
13848                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13849                return null;
13850            }
13851            // throw out instant application filters if we're not explicitly requesting them
13852            if (!isInstantApp && userState.instantApp) {
13853                return null;
13854            }
13855            // throw out instant application filters if updates are available; will trigger
13856            // instant application resolution
13857            if (userState.instantApp && ps.isUpdateAvailable()) {
13858                return null;
13859            }
13860            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13861                    userState, userId);
13862            if (pi == null) {
13863                return null;
13864            }
13865            final ResolveInfo res = new ResolveInfo();
13866            res.providerInfo = pi;
13867            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13868                res.filter = filter;
13869            }
13870            res.priority = info.getPriority();
13871            res.preferredOrder = provider.owner.mPreferredOrder;
13872            res.match = match;
13873            res.isDefault = info.hasDefault;
13874            res.labelRes = info.labelRes;
13875            res.nonLocalizedLabel = info.nonLocalizedLabel;
13876            res.icon = info.icon;
13877            res.system = res.providerInfo.applicationInfo.isSystemApp();
13878            return res;
13879        }
13880
13881        @Override
13882        protected void sortResults(List<ResolveInfo> results) {
13883            Collections.sort(results, mResolvePrioritySorter);
13884        }
13885
13886        @Override
13887        protected void dumpFilter(PrintWriter out, String prefix,
13888                PackageParser.ProviderIntentInfo filter) {
13889            out.print(prefix);
13890            out.print(
13891                    Integer.toHexString(System.identityHashCode(filter.provider)));
13892            out.print(' ');
13893            filter.provider.printComponentShortName(out);
13894            out.print(" filter ");
13895            out.println(Integer.toHexString(System.identityHashCode(filter)));
13896        }
13897
13898        @Override
13899        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13900            return filter.provider;
13901        }
13902
13903        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13904            PackageParser.Provider provider = (PackageParser.Provider)label;
13905            out.print(prefix); out.print(
13906                    Integer.toHexString(System.identityHashCode(provider)));
13907                    out.print(' ');
13908                    provider.printComponentShortName(out);
13909            if (count > 1) {
13910                out.print(" ("); out.print(count); out.print(" filters)");
13911            }
13912            out.println();
13913        }
13914
13915        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13916                = new ArrayMap<ComponentName, PackageParser.Provider>();
13917        private int mFlags;
13918    }
13919
13920    static final class EphemeralIntentResolver
13921            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13922        /**
13923         * The result that has the highest defined order. Ordering applies on a
13924         * per-package basis. Mapping is from package name to Pair of order and
13925         * EphemeralResolveInfo.
13926         * <p>
13927         * NOTE: This is implemented as a field variable for convenience and efficiency.
13928         * By having a field variable, we're able to track filter ordering as soon as
13929         * a non-zero order is defined. Otherwise, multiple loops across the result set
13930         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13931         * this needs to be contained entirely within {@link #filterResults}.
13932         */
13933        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13934
13935        @Override
13936        protected AuxiliaryResolveInfo[] newArray(int size) {
13937            return new AuxiliaryResolveInfo[size];
13938        }
13939
13940        @Override
13941        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13942            return true;
13943        }
13944
13945        @Override
13946        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13947                int userId) {
13948            if (!sUserManager.exists(userId)) {
13949                return null;
13950            }
13951            final String packageName = responseObj.resolveInfo.getPackageName();
13952            final Integer order = responseObj.getOrder();
13953            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13954                    mOrderResult.get(packageName);
13955            // ordering is enabled and this item's order isn't high enough
13956            if (lastOrderResult != null && lastOrderResult.first >= order) {
13957                return null;
13958            }
13959            final InstantAppResolveInfo res = responseObj.resolveInfo;
13960            if (order > 0) {
13961                // non-zero order, enable ordering
13962                mOrderResult.put(packageName, new Pair<>(order, res));
13963            }
13964            return responseObj;
13965        }
13966
13967        @Override
13968        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13969            // only do work if ordering is enabled [most of the time it won't be]
13970            if (mOrderResult.size() == 0) {
13971                return;
13972            }
13973            int resultSize = results.size();
13974            for (int i = 0; i < resultSize; i++) {
13975                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13976                final String packageName = info.getPackageName();
13977                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13978                if (savedInfo == null) {
13979                    // package doesn't having ordering
13980                    continue;
13981                }
13982                if (savedInfo.second == info) {
13983                    // circled back to the highest ordered item; remove from order list
13984                    mOrderResult.remove(savedInfo);
13985                    if (mOrderResult.size() == 0) {
13986                        // no more ordered items
13987                        break;
13988                    }
13989                    continue;
13990                }
13991                // item has a worse order, remove it from the result list
13992                results.remove(i);
13993                resultSize--;
13994                i--;
13995            }
13996        }
13997    }
13998
13999    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14000            new Comparator<ResolveInfo>() {
14001        public int compare(ResolveInfo r1, ResolveInfo r2) {
14002            int v1 = r1.priority;
14003            int v2 = r2.priority;
14004            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14005            if (v1 != v2) {
14006                return (v1 > v2) ? -1 : 1;
14007            }
14008            v1 = r1.preferredOrder;
14009            v2 = r2.preferredOrder;
14010            if (v1 != v2) {
14011                return (v1 > v2) ? -1 : 1;
14012            }
14013            if (r1.isDefault != r2.isDefault) {
14014                return r1.isDefault ? -1 : 1;
14015            }
14016            v1 = r1.match;
14017            v2 = r2.match;
14018            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14019            if (v1 != v2) {
14020                return (v1 > v2) ? -1 : 1;
14021            }
14022            if (r1.system != r2.system) {
14023                return r1.system ? -1 : 1;
14024            }
14025            if (r1.activityInfo != null) {
14026                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14027            }
14028            if (r1.serviceInfo != null) {
14029                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14030            }
14031            if (r1.providerInfo != null) {
14032                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14033            }
14034            return 0;
14035        }
14036    };
14037
14038    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14039            new Comparator<ProviderInfo>() {
14040        public int compare(ProviderInfo p1, ProviderInfo p2) {
14041            final int v1 = p1.initOrder;
14042            final int v2 = p2.initOrder;
14043            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14044        }
14045    };
14046
14047    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14048            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14049            final int[] userIds) {
14050        mHandler.post(new Runnable() {
14051            @Override
14052            public void run() {
14053                try {
14054                    final IActivityManager am = ActivityManager.getService();
14055                    if (am == null) return;
14056                    final int[] resolvedUserIds;
14057                    if (userIds == null) {
14058                        resolvedUserIds = am.getRunningUserIds();
14059                    } else {
14060                        resolvedUserIds = userIds;
14061                    }
14062                    for (int id : resolvedUserIds) {
14063                        final Intent intent = new Intent(action,
14064                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14065                        if (extras != null) {
14066                            intent.putExtras(extras);
14067                        }
14068                        if (targetPkg != null) {
14069                            intent.setPackage(targetPkg);
14070                        }
14071                        // Modify the UID when posting to other users
14072                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14073                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14074                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14075                            intent.putExtra(Intent.EXTRA_UID, uid);
14076                        }
14077                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14078                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14079                        if (DEBUG_BROADCASTS) {
14080                            RuntimeException here = new RuntimeException("here");
14081                            here.fillInStackTrace();
14082                            Slog.d(TAG, "Sending to user " + id + ": "
14083                                    + intent.toShortString(false, true, false, false)
14084                                    + " " + intent.getExtras(), here);
14085                        }
14086                        am.broadcastIntent(null, intent, null, finishedReceiver,
14087                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14088                                null, finishedReceiver != null, false, id);
14089                    }
14090                } catch (RemoteException ex) {
14091                }
14092            }
14093        });
14094    }
14095
14096    /**
14097     * Check if the external storage media is available. This is true if there
14098     * is a mounted external storage medium or if the external storage is
14099     * emulated.
14100     */
14101    private boolean isExternalMediaAvailable() {
14102        return mMediaMounted || Environment.isExternalStorageEmulated();
14103    }
14104
14105    @Override
14106    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14107        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14108            return null;
14109        }
14110        // writer
14111        synchronized (mPackages) {
14112            if (!isExternalMediaAvailable()) {
14113                // If the external storage is no longer mounted at this point,
14114                // the caller may not have been able to delete all of this
14115                // packages files and can not delete any more.  Bail.
14116                return null;
14117            }
14118            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14119            if (lastPackage != null) {
14120                pkgs.remove(lastPackage);
14121            }
14122            if (pkgs.size() > 0) {
14123                return pkgs.get(0);
14124            }
14125        }
14126        return null;
14127    }
14128
14129    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14130        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14131                userId, andCode ? 1 : 0, packageName);
14132        if (mSystemReady) {
14133            msg.sendToTarget();
14134        } else {
14135            if (mPostSystemReadyMessages == null) {
14136                mPostSystemReadyMessages = new ArrayList<>();
14137            }
14138            mPostSystemReadyMessages.add(msg);
14139        }
14140    }
14141
14142    void startCleaningPackages() {
14143        // reader
14144        if (!isExternalMediaAvailable()) {
14145            return;
14146        }
14147        synchronized (mPackages) {
14148            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14149                return;
14150            }
14151        }
14152        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14153        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14154        IActivityManager am = ActivityManager.getService();
14155        if (am != null) {
14156            int dcsUid = -1;
14157            synchronized (mPackages) {
14158                if (!mDefaultContainerWhitelisted) {
14159                    mDefaultContainerWhitelisted = true;
14160                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14161                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14162                }
14163            }
14164            try {
14165                if (dcsUid > 0) {
14166                    am.backgroundWhitelistUid(dcsUid);
14167                }
14168                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14169                        UserHandle.USER_SYSTEM);
14170            } catch (RemoteException e) {
14171            }
14172        }
14173    }
14174
14175    @Override
14176    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14177            int installFlags, String installerPackageName, int userId) {
14178        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14179
14180        final int callingUid = Binder.getCallingUid();
14181        enforceCrossUserPermission(callingUid, userId,
14182                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14183
14184        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14185            try {
14186                if (observer != null) {
14187                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14188                }
14189            } catch (RemoteException re) {
14190            }
14191            return;
14192        }
14193
14194        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14195            installFlags |= PackageManager.INSTALL_FROM_ADB;
14196
14197        } else {
14198            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14199            // about installerPackageName.
14200
14201            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14202            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14203        }
14204
14205        UserHandle user;
14206        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14207            user = UserHandle.ALL;
14208        } else {
14209            user = new UserHandle(userId);
14210        }
14211
14212        // Only system components can circumvent runtime permissions when installing.
14213        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14214                && mContext.checkCallingOrSelfPermission(Manifest.permission
14215                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14216            throw new SecurityException("You need the "
14217                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14218                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14219        }
14220
14221        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14222                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14223            throw new IllegalArgumentException(
14224                    "New installs into ASEC containers no longer supported");
14225        }
14226
14227        final File originFile = new File(originPath);
14228        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14229
14230        final Message msg = mHandler.obtainMessage(INIT_COPY);
14231        final VerificationInfo verificationInfo = new VerificationInfo(
14232                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14233        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14234                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14235                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14236                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14237        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14238        msg.obj = params;
14239
14240        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14241                System.identityHashCode(msg.obj));
14242        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14243                System.identityHashCode(msg.obj));
14244
14245        mHandler.sendMessage(msg);
14246    }
14247
14248
14249    /**
14250     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14251     * it is acting on behalf on an enterprise or the user).
14252     *
14253     * Note that the ordering of the conditionals in this method is important. The checks we perform
14254     * are as follows, in this order:
14255     *
14256     * 1) If the install is being performed by a system app, we can trust the app to have set the
14257     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14258     *    what it is.
14259     * 2) If the install is being performed by a device or profile owner app, the install reason
14260     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14261     *    set the install reason correctly. If the app targets an older SDK version where install
14262     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14263     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14264     * 3) In all other cases, the install is being performed by a regular app that is neither part
14265     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14266     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14267     *    set to enterprise policy and if so, change it to unknown instead.
14268     */
14269    private int fixUpInstallReason(String installerPackageName, int installerUid,
14270            int installReason) {
14271        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14272                == PERMISSION_GRANTED) {
14273            // If the install is being performed by a system app, we trust that app to have set the
14274            // install reason correctly.
14275            return installReason;
14276        }
14277
14278        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14279            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14280        if (dpm != null) {
14281            ComponentName owner = null;
14282            try {
14283                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14284                if (owner == null) {
14285                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14286                }
14287            } catch (RemoteException e) {
14288            }
14289            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14290                // If the install is being performed by a device or profile owner, the install
14291                // reason should be enterprise policy.
14292                return PackageManager.INSTALL_REASON_POLICY;
14293            }
14294        }
14295
14296        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14297            // If the install is being performed by a regular app (i.e. neither system app nor
14298            // device or profile owner), we have no reason to believe that the app is acting on
14299            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14300            // change it to unknown instead.
14301            return PackageManager.INSTALL_REASON_UNKNOWN;
14302        }
14303
14304        // If the install is being performed by a regular app and the install reason was set to any
14305        // value but enterprise policy, leave the install reason unchanged.
14306        return installReason;
14307    }
14308
14309    void installStage(String packageName, File stagedDir, String stagedCid,
14310            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14311            String installerPackageName, int installerUid, UserHandle user,
14312            Certificate[][] certificates) {
14313        if (DEBUG_EPHEMERAL) {
14314            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14315                Slog.d(TAG, "Ephemeral install of " + packageName);
14316            }
14317        }
14318        final VerificationInfo verificationInfo = new VerificationInfo(
14319                sessionParams.originatingUri, sessionParams.referrerUri,
14320                sessionParams.originatingUid, installerUid);
14321
14322        final OriginInfo origin;
14323        if (stagedDir != null) {
14324            origin = OriginInfo.fromStagedFile(stagedDir);
14325        } else {
14326            origin = OriginInfo.fromStagedContainer(stagedCid);
14327        }
14328
14329        final Message msg = mHandler.obtainMessage(INIT_COPY);
14330        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14331                sessionParams.installReason);
14332        final InstallParams params = new InstallParams(origin, null, observer,
14333                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14334                verificationInfo, user, sessionParams.abiOverride,
14335                sessionParams.grantedRuntimePermissions, certificates, installReason);
14336        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14337        msg.obj = params;
14338
14339        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14340                System.identityHashCode(msg.obj));
14341        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14342                System.identityHashCode(msg.obj));
14343
14344        mHandler.sendMessage(msg);
14345    }
14346
14347    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14348            int userId) {
14349        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14350        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14351
14352        // Send a session commit broadcast
14353        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14354        info.installReason = pkgSetting.getInstallReason(userId);
14355        info.appPackageName = packageName;
14356        sendSessionCommitBroadcast(info, userId);
14357    }
14358
14359    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14360        if (ArrayUtils.isEmpty(userIds)) {
14361            return;
14362        }
14363        Bundle extras = new Bundle(1);
14364        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14365        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14366
14367        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14368                packageName, extras, 0, null, null, userIds);
14369        if (isSystem) {
14370            mHandler.post(() -> {
14371                        for (int userId : userIds) {
14372                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14373                        }
14374                    }
14375            );
14376        }
14377    }
14378
14379    /**
14380     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14381     * automatically without needing an explicit launch.
14382     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14383     */
14384    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14385        // If user is not running, the app didn't miss any broadcast
14386        if (!mUserManagerInternal.isUserRunning(userId)) {
14387            return;
14388        }
14389        final IActivityManager am = ActivityManager.getService();
14390        try {
14391            // Deliver LOCKED_BOOT_COMPLETED first
14392            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14393                    .setPackage(packageName);
14394            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14395            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14396                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14397
14398            // Deliver BOOT_COMPLETED only if user is unlocked
14399            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14400                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14401                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14402                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14403            }
14404        } catch (RemoteException e) {
14405            throw e.rethrowFromSystemServer();
14406        }
14407    }
14408
14409    @Override
14410    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14411            int userId) {
14412        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14413        PackageSetting pkgSetting;
14414        final int callingUid = Binder.getCallingUid();
14415        enforceCrossUserPermission(callingUid, userId,
14416                true /* requireFullPermission */, true /* checkShell */,
14417                "setApplicationHiddenSetting for user " + userId);
14418
14419        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14420            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14421            return false;
14422        }
14423
14424        long callingId = Binder.clearCallingIdentity();
14425        try {
14426            boolean sendAdded = false;
14427            boolean sendRemoved = false;
14428            // writer
14429            synchronized (mPackages) {
14430                pkgSetting = mSettings.mPackages.get(packageName);
14431                if (pkgSetting == null) {
14432                    return false;
14433                }
14434                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14435                    return false;
14436                }
14437                // Do not allow "android" is being disabled
14438                if ("android".equals(packageName)) {
14439                    Slog.w(TAG, "Cannot hide package: android");
14440                    return false;
14441                }
14442                // Cannot hide static shared libs as they are considered
14443                // a part of the using app (emulating static linking). Also
14444                // static libs are installed always on internal storage.
14445                PackageParser.Package pkg = mPackages.get(packageName);
14446                if (pkg != null && pkg.staticSharedLibName != null) {
14447                    Slog.w(TAG, "Cannot hide package: " + packageName
14448                            + " providing static shared library: "
14449                            + pkg.staticSharedLibName);
14450                    return false;
14451                }
14452                // Only allow protected packages to hide themselves.
14453                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14454                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14455                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14456                    return false;
14457                }
14458
14459                if (pkgSetting.getHidden(userId) != hidden) {
14460                    pkgSetting.setHidden(hidden, userId);
14461                    mSettings.writePackageRestrictionsLPr(userId);
14462                    if (hidden) {
14463                        sendRemoved = true;
14464                    } else {
14465                        sendAdded = true;
14466                    }
14467                }
14468            }
14469            if (sendAdded) {
14470                sendPackageAddedForUser(packageName, pkgSetting, userId);
14471                return true;
14472            }
14473            if (sendRemoved) {
14474                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14475                        "hiding pkg");
14476                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14477                return true;
14478            }
14479        } finally {
14480            Binder.restoreCallingIdentity(callingId);
14481        }
14482        return false;
14483    }
14484
14485    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14486            int userId) {
14487        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14488        info.removedPackage = packageName;
14489        info.installerPackageName = pkgSetting.installerPackageName;
14490        info.removedUsers = new int[] {userId};
14491        info.broadcastUsers = new int[] {userId};
14492        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14493        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14494    }
14495
14496    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14497        if (pkgList.length > 0) {
14498            Bundle extras = new Bundle(1);
14499            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14500
14501            sendPackageBroadcast(
14502                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14503                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14504                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14505                    new int[] {userId});
14506        }
14507    }
14508
14509    /**
14510     * Returns true if application is not found or there was an error. Otherwise it returns
14511     * the hidden state of the package for the given user.
14512     */
14513    @Override
14514    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14515        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14516        final int callingUid = Binder.getCallingUid();
14517        enforceCrossUserPermission(callingUid, userId,
14518                true /* requireFullPermission */, false /* checkShell */,
14519                "getApplicationHidden for user " + userId);
14520        PackageSetting ps;
14521        long callingId = Binder.clearCallingIdentity();
14522        try {
14523            // writer
14524            synchronized (mPackages) {
14525                ps = mSettings.mPackages.get(packageName);
14526                if (ps == null) {
14527                    return true;
14528                }
14529                if (filterAppAccessLPr(ps, callingUid, userId)) {
14530                    return true;
14531                }
14532                return ps.getHidden(userId);
14533            }
14534        } finally {
14535            Binder.restoreCallingIdentity(callingId);
14536        }
14537    }
14538
14539    /**
14540     * @hide
14541     */
14542    @Override
14543    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14544            int installReason) {
14545        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14546                null);
14547        PackageSetting pkgSetting;
14548        final int callingUid = Binder.getCallingUid();
14549        enforceCrossUserPermission(callingUid, userId,
14550                true /* requireFullPermission */, true /* checkShell */,
14551                "installExistingPackage for user " + userId);
14552        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14553            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14554        }
14555
14556        long callingId = Binder.clearCallingIdentity();
14557        try {
14558            boolean installed = false;
14559            final boolean instantApp =
14560                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14561            final boolean fullApp =
14562                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14563
14564            // writer
14565            synchronized (mPackages) {
14566                pkgSetting = mSettings.mPackages.get(packageName);
14567                if (pkgSetting == null) {
14568                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14569                }
14570                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14571                    // only allow the existing package to be used if it's installed as a full
14572                    // application for at least one user
14573                    boolean installAllowed = false;
14574                    for (int checkUserId : sUserManager.getUserIds()) {
14575                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14576                        if (installAllowed) {
14577                            break;
14578                        }
14579                    }
14580                    if (!installAllowed) {
14581                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14582                    }
14583                }
14584                if (!pkgSetting.getInstalled(userId)) {
14585                    pkgSetting.setInstalled(true, userId);
14586                    pkgSetting.setHidden(false, userId);
14587                    pkgSetting.setInstallReason(installReason, userId);
14588                    mSettings.writePackageRestrictionsLPr(userId);
14589                    mSettings.writeKernelMappingLPr(pkgSetting);
14590                    installed = true;
14591                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14592                    // upgrade app from instant to full; we don't allow app downgrade
14593                    installed = true;
14594                }
14595                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14596            }
14597
14598            if (installed) {
14599                if (pkgSetting.pkg != null) {
14600                    synchronized (mInstallLock) {
14601                        // We don't need to freeze for a brand new install
14602                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14603                    }
14604                }
14605                sendPackageAddedForUser(packageName, pkgSetting, userId);
14606                synchronized (mPackages) {
14607                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14608                }
14609            }
14610        } finally {
14611            Binder.restoreCallingIdentity(callingId);
14612        }
14613
14614        return PackageManager.INSTALL_SUCCEEDED;
14615    }
14616
14617    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14618            boolean instantApp, boolean fullApp) {
14619        // no state specified; do nothing
14620        if (!instantApp && !fullApp) {
14621            return;
14622        }
14623        if (userId != UserHandle.USER_ALL) {
14624            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14625                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14626            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14627                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14628            }
14629        } else {
14630            for (int currentUserId : sUserManager.getUserIds()) {
14631                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14632                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14633                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14634                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14635                }
14636            }
14637        }
14638    }
14639
14640    boolean isUserRestricted(int userId, String restrictionKey) {
14641        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14642        if (restrictions.getBoolean(restrictionKey, false)) {
14643            Log.w(TAG, "User is restricted: " + restrictionKey);
14644            return true;
14645        }
14646        return false;
14647    }
14648
14649    @Override
14650    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14651            int userId) {
14652        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14653        final int callingUid = Binder.getCallingUid();
14654        enforceCrossUserPermission(callingUid, userId,
14655                true /* requireFullPermission */, true /* checkShell */,
14656                "setPackagesSuspended for user " + userId);
14657
14658        if (ArrayUtils.isEmpty(packageNames)) {
14659            return packageNames;
14660        }
14661
14662        // List of package names for whom the suspended state has changed.
14663        List<String> changedPackages = new ArrayList<>(packageNames.length);
14664        // List of package names for whom the suspended state is not set as requested in this
14665        // method.
14666        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14667        long callingId = Binder.clearCallingIdentity();
14668        try {
14669            for (int i = 0; i < packageNames.length; i++) {
14670                String packageName = packageNames[i];
14671                boolean changed = false;
14672                final int appId;
14673                synchronized (mPackages) {
14674                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14675                    if (pkgSetting == null
14676                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14677                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14678                                + "\". Skipping suspending/un-suspending.");
14679                        unactionedPackages.add(packageName);
14680                        continue;
14681                    }
14682                    appId = pkgSetting.appId;
14683                    if (pkgSetting.getSuspended(userId) != suspended) {
14684                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14685                            unactionedPackages.add(packageName);
14686                            continue;
14687                        }
14688                        pkgSetting.setSuspended(suspended, userId);
14689                        mSettings.writePackageRestrictionsLPr(userId);
14690                        changed = true;
14691                        changedPackages.add(packageName);
14692                    }
14693                }
14694
14695                if (changed && suspended) {
14696                    killApplication(packageName, UserHandle.getUid(userId, appId),
14697                            "suspending package");
14698                }
14699            }
14700        } finally {
14701            Binder.restoreCallingIdentity(callingId);
14702        }
14703
14704        if (!changedPackages.isEmpty()) {
14705            sendPackagesSuspendedForUser(changedPackages.toArray(
14706                    new String[changedPackages.size()]), userId, suspended);
14707        }
14708
14709        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14710    }
14711
14712    @Override
14713    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14714        final int callingUid = Binder.getCallingUid();
14715        enforceCrossUserPermission(callingUid, userId,
14716                true /* requireFullPermission */, false /* checkShell */,
14717                "isPackageSuspendedForUser for user " + userId);
14718        synchronized (mPackages) {
14719            final PackageSetting ps = mSettings.mPackages.get(packageName);
14720            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14721                throw new IllegalArgumentException("Unknown target package: " + packageName);
14722            }
14723            return ps.getSuspended(userId);
14724        }
14725    }
14726
14727    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14728        if (isPackageDeviceAdmin(packageName, userId)) {
14729            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14730                    + "\": has an active device admin");
14731            return false;
14732        }
14733
14734        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14735        if (packageName.equals(activeLauncherPackageName)) {
14736            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14737                    + "\": contains the active launcher");
14738            return false;
14739        }
14740
14741        if (packageName.equals(mRequiredInstallerPackage)) {
14742            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14743                    + "\": required for package installation");
14744            return false;
14745        }
14746
14747        if (packageName.equals(mRequiredUninstallerPackage)) {
14748            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14749                    + "\": required for package uninstallation");
14750            return false;
14751        }
14752
14753        if (packageName.equals(mRequiredVerifierPackage)) {
14754            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14755                    + "\": required for package verification");
14756            return false;
14757        }
14758
14759        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14760            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14761                    + "\": is the default dialer");
14762            return false;
14763        }
14764
14765        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14766            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14767                    + "\": protected package");
14768            return false;
14769        }
14770
14771        // Cannot suspend static shared libs as they are considered
14772        // a part of the using app (emulating static linking). Also
14773        // static libs are installed always on internal storage.
14774        PackageParser.Package pkg = mPackages.get(packageName);
14775        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14776            Slog.w(TAG, "Cannot suspend package: " + packageName
14777                    + " providing static shared library: "
14778                    + pkg.staticSharedLibName);
14779            return false;
14780        }
14781
14782        return true;
14783    }
14784
14785    private String getActiveLauncherPackageName(int userId) {
14786        Intent intent = new Intent(Intent.ACTION_MAIN);
14787        intent.addCategory(Intent.CATEGORY_HOME);
14788        ResolveInfo resolveInfo = resolveIntent(
14789                intent,
14790                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14791                PackageManager.MATCH_DEFAULT_ONLY,
14792                userId);
14793
14794        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14795    }
14796
14797    private String getDefaultDialerPackageName(int userId) {
14798        synchronized (mPackages) {
14799            return mSettings.getDefaultDialerPackageNameLPw(userId);
14800        }
14801    }
14802
14803    @Override
14804    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14805        mContext.enforceCallingOrSelfPermission(
14806                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14807                "Only package verification agents can verify applications");
14808
14809        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14810        final PackageVerificationResponse response = new PackageVerificationResponse(
14811                verificationCode, Binder.getCallingUid());
14812        msg.arg1 = id;
14813        msg.obj = response;
14814        mHandler.sendMessage(msg);
14815    }
14816
14817    @Override
14818    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14819            long millisecondsToDelay) {
14820        mContext.enforceCallingOrSelfPermission(
14821                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14822                "Only package verification agents can extend verification timeouts");
14823
14824        final PackageVerificationState state = mPendingVerification.get(id);
14825        final PackageVerificationResponse response = new PackageVerificationResponse(
14826                verificationCodeAtTimeout, Binder.getCallingUid());
14827
14828        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14829            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14830        }
14831        if (millisecondsToDelay < 0) {
14832            millisecondsToDelay = 0;
14833        }
14834        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14835                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14836            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14837        }
14838
14839        if ((state != null) && !state.timeoutExtended()) {
14840            state.extendTimeout();
14841
14842            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14843            msg.arg1 = id;
14844            msg.obj = response;
14845            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14846        }
14847    }
14848
14849    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14850            int verificationCode, UserHandle user) {
14851        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14852        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14853        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14854        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14855        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14856
14857        mContext.sendBroadcastAsUser(intent, user,
14858                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14859    }
14860
14861    private ComponentName matchComponentForVerifier(String packageName,
14862            List<ResolveInfo> receivers) {
14863        ActivityInfo targetReceiver = null;
14864
14865        final int NR = receivers.size();
14866        for (int i = 0; i < NR; i++) {
14867            final ResolveInfo info = receivers.get(i);
14868            if (info.activityInfo == null) {
14869                continue;
14870            }
14871
14872            if (packageName.equals(info.activityInfo.packageName)) {
14873                targetReceiver = info.activityInfo;
14874                break;
14875            }
14876        }
14877
14878        if (targetReceiver == null) {
14879            return null;
14880        }
14881
14882        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14883    }
14884
14885    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14886            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14887        if (pkgInfo.verifiers.length == 0) {
14888            return null;
14889        }
14890
14891        final int N = pkgInfo.verifiers.length;
14892        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14893        for (int i = 0; i < N; i++) {
14894            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14895
14896            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14897                    receivers);
14898            if (comp == null) {
14899                continue;
14900            }
14901
14902            final int verifierUid = getUidForVerifier(verifierInfo);
14903            if (verifierUid == -1) {
14904                continue;
14905            }
14906
14907            if (DEBUG_VERIFY) {
14908                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14909                        + " with the correct signature");
14910            }
14911            sufficientVerifiers.add(comp);
14912            verificationState.addSufficientVerifier(verifierUid);
14913        }
14914
14915        return sufficientVerifiers;
14916    }
14917
14918    private int getUidForVerifier(VerifierInfo verifierInfo) {
14919        synchronized (mPackages) {
14920            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14921            if (pkg == null) {
14922                return -1;
14923            } else if (pkg.mSignatures.length != 1) {
14924                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14925                        + " has more than one signature; ignoring");
14926                return -1;
14927            }
14928
14929            /*
14930             * If the public key of the package's signature does not match
14931             * our expected public key, then this is a different package and
14932             * we should skip.
14933             */
14934
14935            final byte[] expectedPublicKey;
14936            try {
14937                final Signature verifierSig = pkg.mSignatures[0];
14938                final PublicKey publicKey = verifierSig.getPublicKey();
14939                expectedPublicKey = publicKey.getEncoded();
14940            } catch (CertificateException e) {
14941                return -1;
14942            }
14943
14944            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14945
14946            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14947                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14948                        + " does not have the expected public key; ignoring");
14949                return -1;
14950            }
14951
14952            return pkg.applicationInfo.uid;
14953        }
14954    }
14955
14956    @Override
14957    public void finishPackageInstall(int token, boolean didLaunch) {
14958        enforceSystemOrRoot("Only the system is allowed to finish installs");
14959
14960        if (DEBUG_INSTALL) {
14961            Slog.v(TAG, "BM finishing package install for " + token);
14962        }
14963        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14964
14965        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14966        mHandler.sendMessage(msg);
14967    }
14968
14969    /**
14970     * Get the verification agent timeout.  Used for both the APK verifier and the
14971     * intent filter verifier.
14972     *
14973     * @return verification timeout in milliseconds
14974     */
14975    private long getVerificationTimeout() {
14976        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14977                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14978                DEFAULT_VERIFICATION_TIMEOUT);
14979    }
14980
14981    /**
14982     * Get the default verification agent response code.
14983     *
14984     * @return default verification response code
14985     */
14986    private int getDefaultVerificationResponse(UserHandle user) {
14987        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14988            return PackageManager.VERIFICATION_REJECT;
14989        }
14990        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14991                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14992                DEFAULT_VERIFICATION_RESPONSE);
14993    }
14994
14995    /**
14996     * Check whether or not package verification has been enabled.
14997     *
14998     * @return true if verification should be performed
14999     */
15000    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15001        if (!DEFAULT_VERIFY_ENABLE) {
15002            return false;
15003        }
15004
15005        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15006
15007        // Check if installing from ADB
15008        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15009            // Do not run verification in a test harness environment
15010            if (ActivityManager.isRunningInTestHarness()) {
15011                return false;
15012            }
15013            if (ensureVerifyAppsEnabled) {
15014                return true;
15015            }
15016            // Check if the developer does not want package verification for ADB installs
15017            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15018                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15019                return false;
15020            }
15021        } else {
15022            // only when not installed from ADB, skip verification for instant apps when
15023            // the installer and verifier are the same.
15024            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15025                if (mInstantAppInstallerActivity != null
15026                        && mInstantAppInstallerActivity.packageName.equals(
15027                                mRequiredVerifierPackage)) {
15028                    try {
15029                        mContext.getSystemService(AppOpsManager.class)
15030                                .checkPackage(installerUid, mRequiredVerifierPackage);
15031                        if (DEBUG_VERIFY) {
15032                            Slog.i(TAG, "disable verification for instant app");
15033                        }
15034                        return false;
15035                    } catch (SecurityException ignore) { }
15036                }
15037            }
15038        }
15039
15040        if (ensureVerifyAppsEnabled) {
15041            return true;
15042        }
15043
15044        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15045                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15046    }
15047
15048    @Override
15049    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15050            throws RemoteException {
15051        mContext.enforceCallingOrSelfPermission(
15052                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15053                "Only intentfilter verification agents can verify applications");
15054
15055        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15056        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15057                Binder.getCallingUid(), verificationCode, failedDomains);
15058        msg.arg1 = id;
15059        msg.obj = response;
15060        mHandler.sendMessage(msg);
15061    }
15062
15063    @Override
15064    public int getIntentVerificationStatus(String packageName, int userId) {
15065        final int callingUid = Binder.getCallingUid();
15066        if (getInstantAppPackageName(callingUid) != null) {
15067            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15068        }
15069        synchronized (mPackages) {
15070            final PackageSetting ps = mSettings.mPackages.get(packageName);
15071            if (ps == null
15072                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15073                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15074            }
15075            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15076        }
15077    }
15078
15079    @Override
15080    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15081        mContext.enforceCallingOrSelfPermission(
15082                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15083
15084        boolean result = false;
15085        synchronized (mPackages) {
15086            final PackageSetting ps = mSettings.mPackages.get(packageName);
15087            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15088                return false;
15089            }
15090            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15091        }
15092        if (result) {
15093            scheduleWritePackageRestrictionsLocked(userId);
15094        }
15095        return result;
15096    }
15097
15098    @Override
15099    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15100            String packageName) {
15101        final int callingUid = Binder.getCallingUid();
15102        if (getInstantAppPackageName(callingUid) != null) {
15103            return ParceledListSlice.emptyList();
15104        }
15105        synchronized (mPackages) {
15106            final PackageSetting ps = mSettings.mPackages.get(packageName);
15107            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15108                return ParceledListSlice.emptyList();
15109            }
15110            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15111        }
15112    }
15113
15114    @Override
15115    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15116        if (TextUtils.isEmpty(packageName)) {
15117            return ParceledListSlice.emptyList();
15118        }
15119        final int callingUid = Binder.getCallingUid();
15120        final int callingUserId = UserHandle.getUserId(callingUid);
15121        synchronized (mPackages) {
15122            PackageParser.Package pkg = mPackages.get(packageName);
15123            if (pkg == null || pkg.activities == null) {
15124                return ParceledListSlice.emptyList();
15125            }
15126            if (pkg.mExtras == null) {
15127                return ParceledListSlice.emptyList();
15128            }
15129            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15130            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15131                return ParceledListSlice.emptyList();
15132            }
15133            final int count = pkg.activities.size();
15134            ArrayList<IntentFilter> result = new ArrayList<>();
15135            for (int n=0; n<count; n++) {
15136                PackageParser.Activity activity = pkg.activities.get(n);
15137                if (activity.intents != null && activity.intents.size() > 0) {
15138                    result.addAll(activity.intents);
15139                }
15140            }
15141            return new ParceledListSlice<>(result);
15142        }
15143    }
15144
15145    @Override
15146    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15147        mContext.enforceCallingOrSelfPermission(
15148                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15149
15150        synchronized (mPackages) {
15151            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15152            if (packageName != null) {
15153                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15154                        packageName, userId);
15155            }
15156            return result;
15157        }
15158    }
15159
15160    @Override
15161    public String getDefaultBrowserPackageName(int userId) {
15162        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15163            return null;
15164        }
15165        synchronized (mPackages) {
15166            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15167        }
15168    }
15169
15170    /**
15171     * Get the "allow unknown sources" setting.
15172     *
15173     * @return the current "allow unknown sources" setting
15174     */
15175    private int getUnknownSourcesSettings() {
15176        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15177                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15178                -1);
15179    }
15180
15181    @Override
15182    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15183        final int callingUid = Binder.getCallingUid();
15184        if (getInstantAppPackageName(callingUid) != null) {
15185            return;
15186        }
15187        // writer
15188        synchronized (mPackages) {
15189            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15190            if (targetPackageSetting == null
15191                    || filterAppAccessLPr(
15192                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15193                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15194            }
15195
15196            PackageSetting installerPackageSetting;
15197            if (installerPackageName != null) {
15198                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15199                if (installerPackageSetting == null) {
15200                    throw new IllegalArgumentException("Unknown installer package: "
15201                            + installerPackageName);
15202                }
15203            } else {
15204                installerPackageSetting = null;
15205            }
15206
15207            Signature[] callerSignature;
15208            Object obj = mSettings.getUserIdLPr(callingUid);
15209            if (obj != null) {
15210                if (obj instanceof SharedUserSetting) {
15211                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15212                } else if (obj instanceof PackageSetting) {
15213                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15214                } else {
15215                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15216                }
15217            } else {
15218                throw new SecurityException("Unknown calling UID: " + callingUid);
15219            }
15220
15221            // Verify: can't set installerPackageName to a package that is
15222            // not signed with the same cert as the caller.
15223            if (installerPackageSetting != null) {
15224                if (compareSignatures(callerSignature,
15225                        installerPackageSetting.signatures.mSignatures)
15226                        != PackageManager.SIGNATURE_MATCH) {
15227                    throw new SecurityException(
15228                            "Caller does not have same cert as new installer package "
15229                            + installerPackageName);
15230                }
15231            }
15232
15233            // Verify: if target already has an installer package, it must
15234            // be signed with the same cert as the caller.
15235            if (targetPackageSetting.installerPackageName != null) {
15236                PackageSetting setting = mSettings.mPackages.get(
15237                        targetPackageSetting.installerPackageName);
15238                // If the currently set package isn't valid, then it's always
15239                // okay to change it.
15240                if (setting != null) {
15241                    if (compareSignatures(callerSignature,
15242                            setting.signatures.mSignatures)
15243                            != PackageManager.SIGNATURE_MATCH) {
15244                        throw new SecurityException(
15245                                "Caller does not have same cert as old installer package "
15246                                + targetPackageSetting.installerPackageName);
15247                    }
15248                }
15249            }
15250
15251            // Okay!
15252            targetPackageSetting.installerPackageName = installerPackageName;
15253            if (installerPackageName != null) {
15254                mSettings.mInstallerPackages.add(installerPackageName);
15255            }
15256            scheduleWriteSettingsLocked();
15257        }
15258    }
15259
15260    @Override
15261    public void setApplicationCategoryHint(String packageName, int categoryHint,
15262            String callerPackageName) {
15263        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15264            throw new SecurityException("Instant applications don't have access to this method");
15265        }
15266        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15267                callerPackageName);
15268        synchronized (mPackages) {
15269            PackageSetting ps = mSettings.mPackages.get(packageName);
15270            if (ps == null) {
15271                throw new IllegalArgumentException("Unknown target package " + packageName);
15272            }
15273            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15274                throw new IllegalArgumentException("Unknown target package " + packageName);
15275            }
15276            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15277                throw new IllegalArgumentException("Calling package " + callerPackageName
15278                        + " is not installer for " + packageName);
15279            }
15280
15281            if (ps.categoryHint != categoryHint) {
15282                ps.categoryHint = categoryHint;
15283                scheduleWriteSettingsLocked();
15284            }
15285        }
15286    }
15287
15288    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15289        // Queue up an async operation since the package installation may take a little while.
15290        mHandler.post(new Runnable() {
15291            public void run() {
15292                mHandler.removeCallbacks(this);
15293                 // Result object to be returned
15294                PackageInstalledInfo res = new PackageInstalledInfo();
15295                res.setReturnCode(currentStatus);
15296                res.uid = -1;
15297                res.pkg = null;
15298                res.removedInfo = null;
15299                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15300                    args.doPreInstall(res.returnCode);
15301                    synchronized (mInstallLock) {
15302                        installPackageTracedLI(args, res);
15303                    }
15304                    args.doPostInstall(res.returnCode, res.uid);
15305                }
15306
15307                // A restore should be performed at this point if (a) the install
15308                // succeeded, (b) the operation is not an update, and (c) the new
15309                // package has not opted out of backup participation.
15310                final boolean update = res.removedInfo != null
15311                        && res.removedInfo.removedPackage != null;
15312                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15313                boolean doRestore = !update
15314                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15315
15316                // Set up the post-install work request bookkeeping.  This will be used
15317                // and cleaned up by the post-install event handling regardless of whether
15318                // there's a restore pass performed.  Token values are >= 1.
15319                int token;
15320                if (mNextInstallToken < 0) mNextInstallToken = 1;
15321                token = mNextInstallToken++;
15322
15323                PostInstallData data = new PostInstallData(args, res);
15324                mRunningInstalls.put(token, data);
15325                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15326
15327                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15328                    // Pass responsibility to the Backup Manager.  It will perform a
15329                    // restore if appropriate, then pass responsibility back to the
15330                    // Package Manager to run the post-install observer callbacks
15331                    // and broadcasts.
15332                    IBackupManager bm = IBackupManager.Stub.asInterface(
15333                            ServiceManager.getService(Context.BACKUP_SERVICE));
15334                    if (bm != null) {
15335                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15336                                + " to BM for possible restore");
15337                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15338                        try {
15339                            // TODO: http://b/22388012
15340                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15341                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15342                            } else {
15343                                doRestore = false;
15344                            }
15345                        } catch (RemoteException e) {
15346                            // can't happen; the backup manager is local
15347                        } catch (Exception e) {
15348                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15349                            doRestore = false;
15350                        }
15351                    } else {
15352                        Slog.e(TAG, "Backup Manager not found!");
15353                        doRestore = false;
15354                    }
15355                }
15356
15357                if (!doRestore) {
15358                    // No restore possible, or the Backup Manager was mysteriously not
15359                    // available -- just fire the post-install work request directly.
15360                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15361
15362                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15363
15364                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15365                    mHandler.sendMessage(msg);
15366                }
15367            }
15368        });
15369    }
15370
15371    /**
15372     * Callback from PackageSettings whenever an app is first transitioned out of the
15373     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15374     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15375     * here whether the app is the target of an ongoing install, and only send the
15376     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15377     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15378     * handling.
15379     */
15380    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15381        // Serialize this with the rest of the install-process message chain.  In the
15382        // restore-at-install case, this Runnable will necessarily run before the
15383        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15384        // are coherent.  In the non-restore case, the app has already completed install
15385        // and been launched through some other means, so it is not in a problematic
15386        // state for observers to see the FIRST_LAUNCH signal.
15387        mHandler.post(new Runnable() {
15388            @Override
15389            public void run() {
15390                for (int i = 0; i < mRunningInstalls.size(); i++) {
15391                    final PostInstallData data = mRunningInstalls.valueAt(i);
15392                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15393                        continue;
15394                    }
15395                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15396                        // right package; but is it for the right user?
15397                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15398                            if (userId == data.res.newUsers[uIndex]) {
15399                                if (DEBUG_BACKUP) {
15400                                    Slog.i(TAG, "Package " + pkgName
15401                                            + " being restored so deferring FIRST_LAUNCH");
15402                                }
15403                                return;
15404                            }
15405                        }
15406                    }
15407                }
15408                // didn't find it, so not being restored
15409                if (DEBUG_BACKUP) {
15410                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15411                }
15412                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15413            }
15414        });
15415    }
15416
15417    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15418        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15419                installerPkg, null, userIds);
15420    }
15421
15422    private abstract class HandlerParams {
15423        private static final int MAX_RETRIES = 4;
15424
15425        /**
15426         * Number of times startCopy() has been attempted and had a non-fatal
15427         * error.
15428         */
15429        private int mRetries = 0;
15430
15431        /** User handle for the user requesting the information or installation. */
15432        private final UserHandle mUser;
15433        String traceMethod;
15434        int traceCookie;
15435
15436        HandlerParams(UserHandle user) {
15437            mUser = user;
15438        }
15439
15440        UserHandle getUser() {
15441            return mUser;
15442        }
15443
15444        HandlerParams setTraceMethod(String traceMethod) {
15445            this.traceMethod = traceMethod;
15446            return this;
15447        }
15448
15449        HandlerParams setTraceCookie(int traceCookie) {
15450            this.traceCookie = traceCookie;
15451            return this;
15452        }
15453
15454        final boolean startCopy() {
15455            boolean res;
15456            try {
15457                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15458
15459                if (++mRetries > MAX_RETRIES) {
15460                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15461                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15462                    handleServiceError();
15463                    return false;
15464                } else {
15465                    handleStartCopy();
15466                    res = true;
15467                }
15468            } catch (RemoteException e) {
15469                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15470                mHandler.sendEmptyMessage(MCS_RECONNECT);
15471                res = false;
15472            }
15473            handleReturnCode();
15474            return res;
15475        }
15476
15477        final void serviceError() {
15478            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15479            handleServiceError();
15480            handleReturnCode();
15481        }
15482
15483        abstract void handleStartCopy() throws RemoteException;
15484        abstract void handleServiceError();
15485        abstract void handleReturnCode();
15486    }
15487
15488    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15489        for (File path : paths) {
15490            try {
15491                mcs.clearDirectory(path.getAbsolutePath());
15492            } catch (RemoteException e) {
15493            }
15494        }
15495    }
15496
15497    static class OriginInfo {
15498        /**
15499         * Location where install is coming from, before it has been
15500         * copied/renamed into place. This could be a single monolithic APK
15501         * file, or a cluster directory. This location may be untrusted.
15502         */
15503        final File file;
15504        final String cid;
15505
15506        /**
15507         * Flag indicating that {@link #file} or {@link #cid} has already been
15508         * staged, meaning downstream users don't need to defensively copy the
15509         * contents.
15510         */
15511        final boolean staged;
15512
15513        /**
15514         * Flag indicating that {@link #file} or {@link #cid} is an already
15515         * installed app that is being moved.
15516         */
15517        final boolean existing;
15518
15519        final String resolvedPath;
15520        final File resolvedFile;
15521
15522        static OriginInfo fromNothing() {
15523            return new OriginInfo(null, null, false, false);
15524        }
15525
15526        static OriginInfo fromUntrustedFile(File file) {
15527            return new OriginInfo(file, null, false, false);
15528        }
15529
15530        static OriginInfo fromExistingFile(File file) {
15531            return new OriginInfo(file, null, false, true);
15532        }
15533
15534        static OriginInfo fromStagedFile(File file) {
15535            return new OriginInfo(file, null, true, false);
15536        }
15537
15538        static OriginInfo fromStagedContainer(String cid) {
15539            return new OriginInfo(null, cid, true, false);
15540        }
15541
15542        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15543            this.file = file;
15544            this.cid = cid;
15545            this.staged = staged;
15546            this.existing = existing;
15547
15548            if (cid != null) {
15549                resolvedPath = PackageHelper.getSdDir(cid);
15550                resolvedFile = new File(resolvedPath);
15551            } else if (file != null) {
15552                resolvedPath = file.getAbsolutePath();
15553                resolvedFile = file;
15554            } else {
15555                resolvedPath = null;
15556                resolvedFile = null;
15557            }
15558        }
15559    }
15560
15561    static class MoveInfo {
15562        final int moveId;
15563        final String fromUuid;
15564        final String toUuid;
15565        final String packageName;
15566        final String dataAppName;
15567        final int appId;
15568        final String seinfo;
15569        final int targetSdkVersion;
15570
15571        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15572                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15573            this.moveId = moveId;
15574            this.fromUuid = fromUuid;
15575            this.toUuid = toUuid;
15576            this.packageName = packageName;
15577            this.dataAppName = dataAppName;
15578            this.appId = appId;
15579            this.seinfo = seinfo;
15580            this.targetSdkVersion = targetSdkVersion;
15581        }
15582    }
15583
15584    static class VerificationInfo {
15585        /** A constant used to indicate that a uid value is not present. */
15586        public static final int NO_UID = -1;
15587
15588        /** URI referencing where the package was downloaded from. */
15589        final Uri originatingUri;
15590
15591        /** HTTP referrer URI associated with the originatingURI. */
15592        final Uri referrer;
15593
15594        /** UID of the application that the install request originated from. */
15595        final int originatingUid;
15596
15597        /** UID of application requesting the install */
15598        final int installerUid;
15599
15600        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15601            this.originatingUri = originatingUri;
15602            this.referrer = referrer;
15603            this.originatingUid = originatingUid;
15604            this.installerUid = installerUid;
15605        }
15606    }
15607
15608    class InstallParams extends HandlerParams {
15609        final OriginInfo origin;
15610        final MoveInfo move;
15611        final IPackageInstallObserver2 observer;
15612        int installFlags;
15613        final String installerPackageName;
15614        final String volumeUuid;
15615        private InstallArgs mArgs;
15616        private int mRet;
15617        final String packageAbiOverride;
15618        final String[] grantedRuntimePermissions;
15619        final VerificationInfo verificationInfo;
15620        final Certificate[][] certificates;
15621        final int installReason;
15622
15623        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15624                int installFlags, String installerPackageName, String volumeUuid,
15625                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15626                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15627            super(user);
15628            this.origin = origin;
15629            this.move = move;
15630            this.observer = observer;
15631            this.installFlags = installFlags;
15632            this.installerPackageName = installerPackageName;
15633            this.volumeUuid = volumeUuid;
15634            this.verificationInfo = verificationInfo;
15635            this.packageAbiOverride = packageAbiOverride;
15636            this.grantedRuntimePermissions = grantedPermissions;
15637            this.certificates = certificates;
15638            this.installReason = installReason;
15639        }
15640
15641        @Override
15642        public String toString() {
15643            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15644                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15645        }
15646
15647        private int installLocationPolicy(PackageInfoLite pkgLite) {
15648            String packageName = pkgLite.packageName;
15649            int installLocation = pkgLite.installLocation;
15650            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15651            // reader
15652            synchronized (mPackages) {
15653                // Currently installed package which the new package is attempting to replace or
15654                // null if no such package is installed.
15655                PackageParser.Package installedPkg = mPackages.get(packageName);
15656                // Package which currently owns the data which the new package will own if installed.
15657                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15658                // will be null whereas dataOwnerPkg will contain information about the package
15659                // which was uninstalled while keeping its data.
15660                PackageParser.Package dataOwnerPkg = installedPkg;
15661                if (dataOwnerPkg  == null) {
15662                    PackageSetting ps = mSettings.mPackages.get(packageName);
15663                    if (ps != null) {
15664                        dataOwnerPkg = ps.pkg;
15665                    }
15666                }
15667
15668                if (dataOwnerPkg != null) {
15669                    // If installed, the package will get access to data left on the device by its
15670                    // predecessor. As a security measure, this is permited only if this is not a
15671                    // version downgrade or if the predecessor package is marked as debuggable and
15672                    // a downgrade is explicitly requested.
15673                    //
15674                    // On debuggable platform builds, downgrades are permitted even for
15675                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15676                    // not offer security guarantees and thus it's OK to disable some security
15677                    // mechanisms to make debugging/testing easier on those builds. However, even on
15678                    // debuggable builds downgrades of packages are permitted only if requested via
15679                    // installFlags. This is because we aim to keep the behavior of debuggable
15680                    // platform builds as close as possible to the behavior of non-debuggable
15681                    // platform builds.
15682                    final boolean downgradeRequested =
15683                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15684                    final boolean packageDebuggable =
15685                                (dataOwnerPkg.applicationInfo.flags
15686                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15687                    final boolean downgradePermitted =
15688                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15689                    if (!downgradePermitted) {
15690                        try {
15691                            checkDowngrade(dataOwnerPkg, pkgLite);
15692                        } catch (PackageManagerException e) {
15693                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15694                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15695                        }
15696                    }
15697                }
15698
15699                if (installedPkg != null) {
15700                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15701                        // Check for updated system application.
15702                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15703                            if (onSd) {
15704                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15705                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15706                            }
15707                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15708                        } else {
15709                            if (onSd) {
15710                                // Install flag overrides everything.
15711                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15712                            }
15713                            // If current upgrade specifies particular preference
15714                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15715                                // Application explicitly specified internal.
15716                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15717                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15718                                // App explictly prefers external. Let policy decide
15719                            } else {
15720                                // Prefer previous location
15721                                if (isExternal(installedPkg)) {
15722                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15723                                }
15724                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15725                            }
15726                        }
15727                    } else {
15728                        // Invalid install. Return error code
15729                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15730                    }
15731                }
15732            }
15733            // All the special cases have been taken care of.
15734            // Return result based on recommended install location.
15735            if (onSd) {
15736                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15737            }
15738            return pkgLite.recommendedInstallLocation;
15739        }
15740
15741        /*
15742         * Invoke remote method to get package information and install
15743         * location values. Override install location based on default
15744         * policy if needed and then create install arguments based
15745         * on the install location.
15746         */
15747        public void handleStartCopy() throws RemoteException {
15748            int ret = PackageManager.INSTALL_SUCCEEDED;
15749
15750            // If we're already staged, we've firmly committed to an install location
15751            if (origin.staged) {
15752                if (origin.file != null) {
15753                    installFlags |= PackageManager.INSTALL_INTERNAL;
15754                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15755                } else if (origin.cid != null) {
15756                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15757                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15758                } else {
15759                    throw new IllegalStateException("Invalid stage location");
15760                }
15761            }
15762
15763            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15764            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15765            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15766            PackageInfoLite pkgLite = null;
15767
15768            if (onInt && onSd) {
15769                // Check if both bits are set.
15770                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15771                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15772            } else if (onSd && ephemeral) {
15773                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15774                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15775            } else {
15776                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15777                        packageAbiOverride);
15778
15779                if (DEBUG_EPHEMERAL && ephemeral) {
15780                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15781                }
15782
15783                /*
15784                 * If we have too little free space, try to free cache
15785                 * before giving up.
15786                 */
15787                if (!origin.staged && pkgLite.recommendedInstallLocation
15788                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15789                    // TODO: focus freeing disk space on the target device
15790                    final StorageManager storage = StorageManager.from(mContext);
15791                    final long lowThreshold = storage.getStorageLowBytes(
15792                            Environment.getDataDirectory());
15793
15794                    final long sizeBytes = mContainerService.calculateInstalledSize(
15795                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15796
15797                    try {
15798                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15799                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15800                                installFlags, packageAbiOverride);
15801                    } catch (InstallerException e) {
15802                        Slog.w(TAG, "Failed to free cache", e);
15803                    }
15804
15805                    /*
15806                     * The cache free must have deleted the file we
15807                     * downloaded to install.
15808                     *
15809                     * TODO: fix the "freeCache" call to not delete
15810                     *       the file we care about.
15811                     */
15812                    if (pkgLite.recommendedInstallLocation
15813                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15814                        pkgLite.recommendedInstallLocation
15815                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15816                    }
15817                }
15818            }
15819
15820            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15821                int loc = pkgLite.recommendedInstallLocation;
15822                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15823                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15824                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15825                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15826                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15827                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15828                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15829                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15830                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15831                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15832                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15833                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15834                } else {
15835                    // Override with defaults if needed.
15836                    loc = installLocationPolicy(pkgLite);
15837                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15838                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15839                    } else if (!onSd && !onInt) {
15840                        // Override install location with flags
15841                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15842                            // Set the flag to install on external media.
15843                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15844                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15845                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15846                            if (DEBUG_EPHEMERAL) {
15847                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15848                            }
15849                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15850                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15851                                    |PackageManager.INSTALL_INTERNAL);
15852                        } else {
15853                            // Make sure the flag for installing on external
15854                            // media is unset
15855                            installFlags |= PackageManager.INSTALL_INTERNAL;
15856                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15857                        }
15858                    }
15859                }
15860            }
15861
15862            final InstallArgs args = createInstallArgs(this);
15863            mArgs = args;
15864
15865            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15866                // TODO: http://b/22976637
15867                // Apps installed for "all" users use the device owner to verify the app
15868                UserHandle verifierUser = getUser();
15869                if (verifierUser == UserHandle.ALL) {
15870                    verifierUser = UserHandle.SYSTEM;
15871                }
15872
15873                /*
15874                 * Determine if we have any installed package verifiers. If we
15875                 * do, then we'll defer to them to verify the packages.
15876                 */
15877                final int requiredUid = mRequiredVerifierPackage == null ? -1
15878                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15879                                verifierUser.getIdentifier());
15880                final int installerUid =
15881                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15882                if (!origin.existing && requiredUid != -1
15883                        && isVerificationEnabled(
15884                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15885                    final Intent verification = new Intent(
15886                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15887                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15888                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15889                            PACKAGE_MIME_TYPE);
15890                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15891
15892                    // Query all live verifiers based on current user state
15893                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15894                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15895
15896                    if (DEBUG_VERIFY) {
15897                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15898                                + verification.toString() + " with " + pkgLite.verifiers.length
15899                                + " optional verifiers");
15900                    }
15901
15902                    final int verificationId = mPendingVerificationToken++;
15903
15904                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15905
15906                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15907                            installerPackageName);
15908
15909                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15910                            installFlags);
15911
15912                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15913                            pkgLite.packageName);
15914
15915                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15916                            pkgLite.versionCode);
15917
15918                    if (verificationInfo != null) {
15919                        if (verificationInfo.originatingUri != null) {
15920                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15921                                    verificationInfo.originatingUri);
15922                        }
15923                        if (verificationInfo.referrer != null) {
15924                            verification.putExtra(Intent.EXTRA_REFERRER,
15925                                    verificationInfo.referrer);
15926                        }
15927                        if (verificationInfo.originatingUid >= 0) {
15928                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15929                                    verificationInfo.originatingUid);
15930                        }
15931                        if (verificationInfo.installerUid >= 0) {
15932                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15933                                    verificationInfo.installerUid);
15934                        }
15935                    }
15936
15937                    final PackageVerificationState verificationState = new PackageVerificationState(
15938                            requiredUid, args);
15939
15940                    mPendingVerification.append(verificationId, verificationState);
15941
15942                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15943                            receivers, verificationState);
15944
15945                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15946                    final long idleDuration = getVerificationTimeout();
15947
15948                    /*
15949                     * If any sufficient verifiers were listed in the package
15950                     * manifest, attempt to ask them.
15951                     */
15952                    if (sufficientVerifiers != null) {
15953                        final int N = sufficientVerifiers.size();
15954                        if (N == 0) {
15955                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15956                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15957                        } else {
15958                            for (int i = 0; i < N; i++) {
15959                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15960                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15961                                        verifierComponent.getPackageName(), idleDuration,
15962                                        verifierUser.getIdentifier(), false, "package verifier");
15963
15964                                final Intent sufficientIntent = new Intent(verification);
15965                                sufficientIntent.setComponent(verifierComponent);
15966                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15967                            }
15968                        }
15969                    }
15970
15971                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15972                            mRequiredVerifierPackage, receivers);
15973                    if (ret == PackageManager.INSTALL_SUCCEEDED
15974                            && mRequiredVerifierPackage != null) {
15975                        Trace.asyncTraceBegin(
15976                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15977                        /*
15978                         * Send the intent to the required verification agent,
15979                         * but only start the verification timeout after the
15980                         * target BroadcastReceivers have run.
15981                         */
15982                        verification.setComponent(requiredVerifierComponent);
15983                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15984                                mRequiredVerifierPackage, idleDuration,
15985                                verifierUser.getIdentifier(), false, "package verifier");
15986                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15987                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15988                                new BroadcastReceiver() {
15989                                    @Override
15990                                    public void onReceive(Context context, Intent intent) {
15991                                        final Message msg = mHandler
15992                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15993                                        msg.arg1 = verificationId;
15994                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15995                                    }
15996                                }, null, 0, null, null);
15997
15998                        /*
15999                         * We don't want the copy to proceed until verification
16000                         * succeeds, so null out this field.
16001                         */
16002                        mArgs = null;
16003                    }
16004                } else {
16005                    /*
16006                     * No package verification is enabled, so immediately start
16007                     * the remote call to initiate copy using temporary file.
16008                     */
16009                    ret = args.copyApk(mContainerService, true);
16010                }
16011            }
16012
16013            mRet = ret;
16014        }
16015
16016        @Override
16017        void handleReturnCode() {
16018            // If mArgs is null, then MCS couldn't be reached. When it
16019            // reconnects, it will try again to install. At that point, this
16020            // will succeed.
16021            if (mArgs != null) {
16022                processPendingInstall(mArgs, mRet);
16023            }
16024        }
16025
16026        @Override
16027        void handleServiceError() {
16028            mArgs = createInstallArgs(this);
16029            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16030        }
16031
16032        public boolean isForwardLocked() {
16033            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16034        }
16035    }
16036
16037    /**
16038     * Used during creation of InstallArgs
16039     *
16040     * @param installFlags package installation flags
16041     * @return true if should be installed on external storage
16042     */
16043    private static boolean installOnExternalAsec(int installFlags) {
16044        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16045            return false;
16046        }
16047        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16048            return true;
16049        }
16050        return false;
16051    }
16052
16053    /**
16054     * Used during creation of InstallArgs
16055     *
16056     * @param installFlags package installation flags
16057     * @return true if should be installed as forward locked
16058     */
16059    private static boolean installForwardLocked(int installFlags) {
16060        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16061    }
16062
16063    private InstallArgs createInstallArgs(InstallParams params) {
16064        if (params.move != null) {
16065            return new MoveInstallArgs(params);
16066        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16067            return new AsecInstallArgs(params);
16068        } else {
16069            return new FileInstallArgs(params);
16070        }
16071    }
16072
16073    /**
16074     * Create args that describe an existing installed package. Typically used
16075     * when cleaning up old installs, or used as a move source.
16076     */
16077    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16078            String resourcePath, String[] instructionSets) {
16079        final boolean isInAsec;
16080        if (installOnExternalAsec(installFlags)) {
16081            /* Apps on SD card are always in ASEC containers. */
16082            isInAsec = true;
16083        } else if (installForwardLocked(installFlags)
16084                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16085            /*
16086             * Forward-locked apps are only in ASEC containers if they're the
16087             * new style
16088             */
16089            isInAsec = true;
16090        } else {
16091            isInAsec = false;
16092        }
16093
16094        if (isInAsec) {
16095            return new AsecInstallArgs(codePath, instructionSets,
16096                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16097        } else {
16098            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16099        }
16100    }
16101
16102    static abstract class InstallArgs {
16103        /** @see InstallParams#origin */
16104        final OriginInfo origin;
16105        /** @see InstallParams#move */
16106        final MoveInfo move;
16107
16108        final IPackageInstallObserver2 observer;
16109        // Always refers to PackageManager flags only
16110        final int installFlags;
16111        final String installerPackageName;
16112        final String volumeUuid;
16113        final UserHandle user;
16114        final String abiOverride;
16115        final String[] installGrantPermissions;
16116        /** If non-null, drop an async trace when the install completes */
16117        final String traceMethod;
16118        final int traceCookie;
16119        final Certificate[][] certificates;
16120        final int installReason;
16121
16122        // The list of instruction sets supported by this app. This is currently
16123        // only used during the rmdex() phase to clean up resources. We can get rid of this
16124        // if we move dex files under the common app path.
16125        /* nullable */ String[] instructionSets;
16126
16127        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16128                int installFlags, String installerPackageName, String volumeUuid,
16129                UserHandle user, String[] instructionSets,
16130                String abiOverride, String[] installGrantPermissions,
16131                String traceMethod, int traceCookie, Certificate[][] certificates,
16132                int installReason) {
16133            this.origin = origin;
16134            this.move = move;
16135            this.installFlags = installFlags;
16136            this.observer = observer;
16137            this.installerPackageName = installerPackageName;
16138            this.volumeUuid = volumeUuid;
16139            this.user = user;
16140            this.instructionSets = instructionSets;
16141            this.abiOverride = abiOverride;
16142            this.installGrantPermissions = installGrantPermissions;
16143            this.traceMethod = traceMethod;
16144            this.traceCookie = traceCookie;
16145            this.certificates = certificates;
16146            this.installReason = installReason;
16147        }
16148
16149        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16150        abstract int doPreInstall(int status);
16151
16152        /**
16153         * Rename package into final resting place. All paths on the given
16154         * scanned package should be updated to reflect the rename.
16155         */
16156        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16157        abstract int doPostInstall(int status, int uid);
16158
16159        /** @see PackageSettingBase#codePathString */
16160        abstract String getCodePath();
16161        /** @see PackageSettingBase#resourcePathString */
16162        abstract String getResourcePath();
16163
16164        // Need installer lock especially for dex file removal.
16165        abstract void cleanUpResourcesLI();
16166        abstract boolean doPostDeleteLI(boolean delete);
16167
16168        /**
16169         * Called before the source arguments are copied. This is used mostly
16170         * for MoveParams when it needs to read the source file to put it in the
16171         * destination.
16172         */
16173        int doPreCopy() {
16174            return PackageManager.INSTALL_SUCCEEDED;
16175        }
16176
16177        /**
16178         * Called after the source arguments are copied. This is used mostly for
16179         * MoveParams when it needs to read the source file to put it in the
16180         * destination.
16181         */
16182        int doPostCopy(int uid) {
16183            return PackageManager.INSTALL_SUCCEEDED;
16184        }
16185
16186        protected boolean isFwdLocked() {
16187            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16188        }
16189
16190        protected boolean isExternalAsec() {
16191            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16192        }
16193
16194        protected boolean isEphemeral() {
16195            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16196        }
16197
16198        UserHandle getUser() {
16199            return user;
16200        }
16201    }
16202
16203    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16204        if (!allCodePaths.isEmpty()) {
16205            if (instructionSets == null) {
16206                throw new IllegalStateException("instructionSet == null");
16207            }
16208            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16209            for (String codePath : allCodePaths) {
16210                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16211                    try {
16212                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16213                    } catch (InstallerException ignored) {
16214                    }
16215                }
16216            }
16217        }
16218    }
16219
16220    /**
16221     * Logic to handle installation of non-ASEC applications, including copying
16222     * and renaming logic.
16223     */
16224    class FileInstallArgs extends InstallArgs {
16225        private File codeFile;
16226        private File resourceFile;
16227
16228        // Example topology:
16229        // /data/app/com.example/base.apk
16230        // /data/app/com.example/split_foo.apk
16231        // /data/app/com.example/lib/arm/libfoo.so
16232        // /data/app/com.example/lib/arm64/libfoo.so
16233        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16234
16235        /** New install */
16236        FileInstallArgs(InstallParams params) {
16237            super(params.origin, params.move, params.observer, params.installFlags,
16238                    params.installerPackageName, params.volumeUuid,
16239                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16240                    params.grantedRuntimePermissions,
16241                    params.traceMethod, params.traceCookie, params.certificates,
16242                    params.installReason);
16243            if (isFwdLocked()) {
16244                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16245            }
16246        }
16247
16248        /** Existing install */
16249        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16250            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16251                    null, null, null, 0, null /*certificates*/,
16252                    PackageManager.INSTALL_REASON_UNKNOWN);
16253            this.codeFile = (codePath != null) ? new File(codePath) : null;
16254            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16255        }
16256
16257        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16258            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16259            try {
16260                return doCopyApk(imcs, temp);
16261            } finally {
16262                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16263            }
16264        }
16265
16266        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16267            if (origin.staged) {
16268                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16269                codeFile = origin.file;
16270                resourceFile = origin.file;
16271                return PackageManager.INSTALL_SUCCEEDED;
16272            }
16273
16274            try {
16275                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16276                final File tempDir =
16277                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16278                codeFile = tempDir;
16279                resourceFile = tempDir;
16280            } catch (IOException e) {
16281                Slog.w(TAG, "Failed to create copy file: " + e);
16282                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16283            }
16284
16285            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16286                @Override
16287                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16288                    if (!FileUtils.isValidExtFilename(name)) {
16289                        throw new IllegalArgumentException("Invalid filename: " + name);
16290                    }
16291                    try {
16292                        final File file = new File(codeFile, name);
16293                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16294                                O_RDWR | O_CREAT, 0644);
16295                        Os.chmod(file.getAbsolutePath(), 0644);
16296                        return new ParcelFileDescriptor(fd);
16297                    } catch (ErrnoException e) {
16298                        throw new RemoteException("Failed to open: " + e.getMessage());
16299                    }
16300                }
16301            };
16302
16303            int ret = PackageManager.INSTALL_SUCCEEDED;
16304            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16305            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16306                Slog.e(TAG, "Failed to copy package");
16307                return ret;
16308            }
16309
16310            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16311            NativeLibraryHelper.Handle handle = null;
16312            try {
16313                handle = NativeLibraryHelper.Handle.create(codeFile);
16314                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16315                        abiOverride);
16316            } catch (IOException e) {
16317                Slog.e(TAG, "Copying native libraries failed", e);
16318                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16319            } finally {
16320                IoUtils.closeQuietly(handle);
16321            }
16322
16323            return ret;
16324        }
16325
16326        int doPreInstall(int status) {
16327            if (status != PackageManager.INSTALL_SUCCEEDED) {
16328                cleanUp();
16329            }
16330            return status;
16331        }
16332
16333        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16334            if (status != PackageManager.INSTALL_SUCCEEDED) {
16335                cleanUp();
16336                return false;
16337            }
16338
16339            final File targetDir = codeFile.getParentFile();
16340            final File beforeCodeFile = codeFile;
16341            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16342
16343            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16344            try {
16345                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16346            } catch (ErrnoException e) {
16347                Slog.w(TAG, "Failed to rename", e);
16348                return false;
16349            }
16350
16351            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16352                Slog.w(TAG, "Failed to restorecon");
16353                return false;
16354            }
16355
16356            // Reflect the rename internally
16357            codeFile = afterCodeFile;
16358            resourceFile = afterCodeFile;
16359
16360            // Reflect the rename in scanned details
16361            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16362            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16363                    afterCodeFile, pkg.baseCodePath));
16364            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16365                    afterCodeFile, pkg.splitCodePaths));
16366
16367            // Reflect the rename in app info
16368            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16369            pkg.setApplicationInfoCodePath(pkg.codePath);
16370            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16371            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16372            pkg.setApplicationInfoResourcePath(pkg.codePath);
16373            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16374            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16375
16376            return true;
16377        }
16378
16379        int doPostInstall(int status, int uid) {
16380            if (status != PackageManager.INSTALL_SUCCEEDED) {
16381                cleanUp();
16382            }
16383            return status;
16384        }
16385
16386        @Override
16387        String getCodePath() {
16388            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16389        }
16390
16391        @Override
16392        String getResourcePath() {
16393            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16394        }
16395
16396        private boolean cleanUp() {
16397            if (codeFile == null || !codeFile.exists()) {
16398                return false;
16399            }
16400
16401            removeCodePathLI(codeFile);
16402
16403            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16404                resourceFile.delete();
16405            }
16406
16407            return true;
16408        }
16409
16410        void cleanUpResourcesLI() {
16411            // Try enumerating all code paths before deleting
16412            List<String> allCodePaths = Collections.EMPTY_LIST;
16413            if (codeFile != null && codeFile.exists()) {
16414                try {
16415                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16416                    allCodePaths = pkg.getAllCodePaths();
16417                } catch (PackageParserException e) {
16418                    // Ignored; we tried our best
16419                }
16420            }
16421
16422            cleanUp();
16423            removeDexFiles(allCodePaths, instructionSets);
16424        }
16425
16426        boolean doPostDeleteLI(boolean delete) {
16427            // XXX err, shouldn't we respect the delete flag?
16428            cleanUpResourcesLI();
16429            return true;
16430        }
16431    }
16432
16433    private boolean isAsecExternal(String cid) {
16434        final String asecPath = PackageHelper.getSdFilesystem(cid);
16435        return !asecPath.startsWith(mAsecInternalPath);
16436    }
16437
16438    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16439            PackageManagerException {
16440        if (copyRet < 0) {
16441            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16442                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16443                throw new PackageManagerException(copyRet, message);
16444            }
16445        }
16446    }
16447
16448    /**
16449     * Extract the StorageManagerService "container ID" from the full code path of an
16450     * .apk.
16451     */
16452    static String cidFromCodePath(String fullCodePath) {
16453        int eidx = fullCodePath.lastIndexOf("/");
16454        String subStr1 = fullCodePath.substring(0, eidx);
16455        int sidx = subStr1.lastIndexOf("/");
16456        return subStr1.substring(sidx+1, eidx);
16457    }
16458
16459    /**
16460     * Logic to handle installation of ASEC applications, including copying and
16461     * renaming logic.
16462     */
16463    class AsecInstallArgs extends InstallArgs {
16464        static final String RES_FILE_NAME = "pkg.apk";
16465        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16466
16467        String cid;
16468        String packagePath;
16469        String resourcePath;
16470
16471        /** New install */
16472        AsecInstallArgs(InstallParams params) {
16473            super(params.origin, params.move, params.observer, params.installFlags,
16474                    params.installerPackageName, params.volumeUuid,
16475                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16476                    params.grantedRuntimePermissions,
16477                    params.traceMethod, params.traceCookie, params.certificates,
16478                    params.installReason);
16479        }
16480
16481        /** Existing install */
16482        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16483                        boolean isExternal, boolean isForwardLocked) {
16484            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16485                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16486                    instructionSets, null, null, null, 0, null /*certificates*/,
16487                    PackageManager.INSTALL_REASON_UNKNOWN);
16488            // Hackily pretend we're still looking at a full code path
16489            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16490                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16491            }
16492
16493            // Extract cid from fullCodePath
16494            int eidx = fullCodePath.lastIndexOf("/");
16495            String subStr1 = fullCodePath.substring(0, eidx);
16496            int sidx = subStr1.lastIndexOf("/");
16497            cid = subStr1.substring(sidx+1, eidx);
16498            setMountPath(subStr1);
16499        }
16500
16501        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16502            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16503                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16504                    instructionSets, null, null, null, 0, null /*certificates*/,
16505                    PackageManager.INSTALL_REASON_UNKNOWN);
16506            this.cid = cid;
16507            setMountPath(PackageHelper.getSdDir(cid));
16508        }
16509
16510        void createCopyFile() {
16511            cid = mInstallerService.allocateExternalStageCidLegacy();
16512        }
16513
16514        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16515            if (origin.staged && origin.cid != null) {
16516                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16517                cid = origin.cid;
16518                setMountPath(PackageHelper.getSdDir(cid));
16519                return PackageManager.INSTALL_SUCCEEDED;
16520            }
16521
16522            if (temp) {
16523                createCopyFile();
16524            } else {
16525                /*
16526                 * Pre-emptively destroy the container since it's destroyed if
16527                 * copying fails due to it existing anyway.
16528                 */
16529                PackageHelper.destroySdDir(cid);
16530            }
16531
16532            final String newMountPath = imcs.copyPackageToContainer(
16533                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16534                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16535
16536            if (newMountPath != null) {
16537                setMountPath(newMountPath);
16538                return PackageManager.INSTALL_SUCCEEDED;
16539            } else {
16540                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16541            }
16542        }
16543
16544        @Override
16545        String getCodePath() {
16546            return packagePath;
16547        }
16548
16549        @Override
16550        String getResourcePath() {
16551            return resourcePath;
16552        }
16553
16554        int doPreInstall(int status) {
16555            if (status != PackageManager.INSTALL_SUCCEEDED) {
16556                // Destroy container
16557                PackageHelper.destroySdDir(cid);
16558            } else {
16559                boolean mounted = PackageHelper.isContainerMounted(cid);
16560                if (!mounted) {
16561                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16562                            Process.SYSTEM_UID);
16563                    if (newMountPath != null) {
16564                        setMountPath(newMountPath);
16565                    } else {
16566                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16567                    }
16568                }
16569            }
16570            return status;
16571        }
16572
16573        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16574            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16575            String newMountPath = null;
16576            if (PackageHelper.isContainerMounted(cid)) {
16577                // Unmount the container
16578                if (!PackageHelper.unMountSdDir(cid)) {
16579                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16580                    return false;
16581                }
16582            }
16583            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16584                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16585                        " which might be stale. Will try to clean up.");
16586                // Clean up the stale container and proceed to recreate.
16587                if (!PackageHelper.destroySdDir(newCacheId)) {
16588                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16589                    return false;
16590                }
16591                // Successfully cleaned up stale container. Try to rename again.
16592                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16593                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16594                            + " inspite of cleaning it up.");
16595                    return false;
16596                }
16597            }
16598            if (!PackageHelper.isContainerMounted(newCacheId)) {
16599                Slog.w(TAG, "Mounting container " + newCacheId);
16600                newMountPath = PackageHelper.mountSdDir(newCacheId,
16601                        getEncryptKey(), Process.SYSTEM_UID);
16602            } else {
16603                newMountPath = PackageHelper.getSdDir(newCacheId);
16604            }
16605            if (newMountPath == null) {
16606                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16607                return false;
16608            }
16609            Log.i(TAG, "Succesfully renamed " + cid +
16610                    " to " + newCacheId +
16611                    " at new path: " + newMountPath);
16612            cid = newCacheId;
16613
16614            final File beforeCodeFile = new File(packagePath);
16615            setMountPath(newMountPath);
16616            final File afterCodeFile = new File(packagePath);
16617
16618            // Reflect the rename in scanned details
16619            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16620            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16621                    afterCodeFile, pkg.baseCodePath));
16622            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16623                    afterCodeFile, pkg.splitCodePaths));
16624
16625            // Reflect the rename in app info
16626            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16627            pkg.setApplicationInfoCodePath(pkg.codePath);
16628            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16629            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16630            pkg.setApplicationInfoResourcePath(pkg.codePath);
16631            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16632            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16633
16634            return true;
16635        }
16636
16637        private void setMountPath(String mountPath) {
16638            final File mountFile = new File(mountPath);
16639
16640            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16641            if (monolithicFile.exists()) {
16642                packagePath = monolithicFile.getAbsolutePath();
16643                if (isFwdLocked()) {
16644                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16645                } else {
16646                    resourcePath = packagePath;
16647                }
16648            } else {
16649                packagePath = mountFile.getAbsolutePath();
16650                resourcePath = packagePath;
16651            }
16652        }
16653
16654        int doPostInstall(int status, int uid) {
16655            if (status != PackageManager.INSTALL_SUCCEEDED) {
16656                cleanUp();
16657            } else {
16658                final int groupOwner;
16659                final String protectedFile;
16660                if (isFwdLocked()) {
16661                    groupOwner = UserHandle.getSharedAppGid(uid);
16662                    protectedFile = RES_FILE_NAME;
16663                } else {
16664                    groupOwner = -1;
16665                    protectedFile = null;
16666                }
16667
16668                if (uid < Process.FIRST_APPLICATION_UID
16669                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16670                    Slog.e(TAG, "Failed to finalize " + cid);
16671                    PackageHelper.destroySdDir(cid);
16672                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16673                }
16674
16675                boolean mounted = PackageHelper.isContainerMounted(cid);
16676                if (!mounted) {
16677                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16678                }
16679            }
16680            return status;
16681        }
16682
16683        private void cleanUp() {
16684            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16685
16686            // Destroy secure container
16687            PackageHelper.destroySdDir(cid);
16688        }
16689
16690        private List<String> getAllCodePaths() {
16691            final File codeFile = new File(getCodePath());
16692            if (codeFile != null && codeFile.exists()) {
16693                try {
16694                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16695                    return pkg.getAllCodePaths();
16696                } catch (PackageParserException e) {
16697                    // Ignored; we tried our best
16698                }
16699            }
16700            return Collections.EMPTY_LIST;
16701        }
16702
16703        void cleanUpResourcesLI() {
16704            // Enumerate all code paths before deleting
16705            cleanUpResourcesLI(getAllCodePaths());
16706        }
16707
16708        private void cleanUpResourcesLI(List<String> allCodePaths) {
16709            cleanUp();
16710            removeDexFiles(allCodePaths, instructionSets);
16711        }
16712
16713        String getPackageName() {
16714            return getAsecPackageName(cid);
16715        }
16716
16717        boolean doPostDeleteLI(boolean delete) {
16718            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16719            final List<String> allCodePaths = getAllCodePaths();
16720            boolean mounted = PackageHelper.isContainerMounted(cid);
16721            if (mounted) {
16722                // Unmount first
16723                if (PackageHelper.unMountSdDir(cid)) {
16724                    mounted = false;
16725                }
16726            }
16727            if (!mounted && delete) {
16728                cleanUpResourcesLI(allCodePaths);
16729            }
16730            return !mounted;
16731        }
16732
16733        @Override
16734        int doPreCopy() {
16735            if (isFwdLocked()) {
16736                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16737                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16738                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16739                }
16740            }
16741
16742            return PackageManager.INSTALL_SUCCEEDED;
16743        }
16744
16745        @Override
16746        int doPostCopy(int uid) {
16747            if (isFwdLocked()) {
16748                if (uid < Process.FIRST_APPLICATION_UID
16749                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16750                                RES_FILE_NAME)) {
16751                    Slog.e(TAG, "Failed to finalize " + cid);
16752                    PackageHelper.destroySdDir(cid);
16753                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16754                }
16755            }
16756
16757            return PackageManager.INSTALL_SUCCEEDED;
16758        }
16759    }
16760
16761    /**
16762     * Logic to handle movement of existing installed applications.
16763     */
16764    class MoveInstallArgs extends InstallArgs {
16765        private File codeFile;
16766        private File resourceFile;
16767
16768        /** New install */
16769        MoveInstallArgs(InstallParams params) {
16770            super(params.origin, params.move, params.observer, params.installFlags,
16771                    params.installerPackageName, params.volumeUuid,
16772                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16773                    params.grantedRuntimePermissions,
16774                    params.traceMethod, params.traceCookie, params.certificates,
16775                    params.installReason);
16776        }
16777
16778        int copyApk(IMediaContainerService imcs, boolean temp) {
16779            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16780                    + move.fromUuid + " to " + move.toUuid);
16781            synchronized (mInstaller) {
16782                try {
16783                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16784                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16785                } catch (InstallerException e) {
16786                    Slog.w(TAG, "Failed to move app", e);
16787                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16788                }
16789            }
16790
16791            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16792            resourceFile = codeFile;
16793            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16794
16795            return PackageManager.INSTALL_SUCCEEDED;
16796        }
16797
16798        int doPreInstall(int status) {
16799            if (status != PackageManager.INSTALL_SUCCEEDED) {
16800                cleanUp(move.toUuid);
16801            }
16802            return status;
16803        }
16804
16805        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16806            if (status != PackageManager.INSTALL_SUCCEEDED) {
16807                cleanUp(move.toUuid);
16808                return false;
16809            }
16810
16811            // Reflect the move in app info
16812            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16813            pkg.setApplicationInfoCodePath(pkg.codePath);
16814            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16815            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16816            pkg.setApplicationInfoResourcePath(pkg.codePath);
16817            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16818            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16819
16820            return true;
16821        }
16822
16823        int doPostInstall(int status, int uid) {
16824            if (status == PackageManager.INSTALL_SUCCEEDED) {
16825                cleanUp(move.fromUuid);
16826            } else {
16827                cleanUp(move.toUuid);
16828            }
16829            return status;
16830        }
16831
16832        @Override
16833        String getCodePath() {
16834            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16835        }
16836
16837        @Override
16838        String getResourcePath() {
16839            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16840        }
16841
16842        private boolean cleanUp(String volumeUuid) {
16843            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16844                    move.dataAppName);
16845            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16846            final int[] userIds = sUserManager.getUserIds();
16847            synchronized (mInstallLock) {
16848                // Clean up both app data and code
16849                // All package moves are frozen until finished
16850                for (int userId : userIds) {
16851                    try {
16852                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16853                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16854                    } catch (InstallerException e) {
16855                        Slog.w(TAG, String.valueOf(e));
16856                    }
16857                }
16858                removeCodePathLI(codeFile);
16859            }
16860            return true;
16861        }
16862
16863        void cleanUpResourcesLI() {
16864            throw new UnsupportedOperationException();
16865        }
16866
16867        boolean doPostDeleteLI(boolean delete) {
16868            throw new UnsupportedOperationException();
16869        }
16870    }
16871
16872    static String getAsecPackageName(String packageCid) {
16873        int idx = packageCid.lastIndexOf("-");
16874        if (idx == -1) {
16875            return packageCid;
16876        }
16877        return packageCid.substring(0, idx);
16878    }
16879
16880    // Utility method used to create code paths based on package name and available index.
16881    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16882        String idxStr = "";
16883        int idx = 1;
16884        // Fall back to default value of idx=1 if prefix is not
16885        // part of oldCodePath
16886        if (oldCodePath != null) {
16887            String subStr = oldCodePath;
16888            // Drop the suffix right away
16889            if (suffix != null && subStr.endsWith(suffix)) {
16890                subStr = subStr.substring(0, subStr.length() - suffix.length());
16891            }
16892            // If oldCodePath already contains prefix find out the
16893            // ending index to either increment or decrement.
16894            int sidx = subStr.lastIndexOf(prefix);
16895            if (sidx != -1) {
16896                subStr = subStr.substring(sidx + prefix.length());
16897                if (subStr != null) {
16898                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16899                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16900                    }
16901                    try {
16902                        idx = Integer.parseInt(subStr);
16903                        if (idx <= 1) {
16904                            idx++;
16905                        } else {
16906                            idx--;
16907                        }
16908                    } catch(NumberFormatException e) {
16909                    }
16910                }
16911            }
16912        }
16913        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16914        return prefix + idxStr;
16915    }
16916
16917    private File getNextCodePath(File targetDir, String packageName) {
16918        File result;
16919        SecureRandom random = new SecureRandom();
16920        byte[] bytes = new byte[16];
16921        do {
16922            random.nextBytes(bytes);
16923            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16924            result = new File(targetDir, packageName + "-" + suffix);
16925        } while (result.exists());
16926        return result;
16927    }
16928
16929    // Utility method that returns the relative package path with respect
16930    // to the installation directory. Like say for /data/data/com.test-1.apk
16931    // string com.test-1 is returned.
16932    static String deriveCodePathName(String codePath) {
16933        if (codePath == null) {
16934            return null;
16935        }
16936        final File codeFile = new File(codePath);
16937        final String name = codeFile.getName();
16938        if (codeFile.isDirectory()) {
16939            return name;
16940        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16941            final int lastDot = name.lastIndexOf('.');
16942            return name.substring(0, lastDot);
16943        } else {
16944            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16945            return null;
16946        }
16947    }
16948
16949    static class PackageInstalledInfo {
16950        String name;
16951        int uid;
16952        // The set of users that originally had this package installed.
16953        int[] origUsers;
16954        // The set of users that now have this package installed.
16955        int[] newUsers;
16956        PackageParser.Package pkg;
16957        int returnCode;
16958        String returnMsg;
16959        PackageRemovedInfo removedInfo;
16960        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16961
16962        public void setError(int code, String msg) {
16963            setReturnCode(code);
16964            setReturnMessage(msg);
16965            Slog.w(TAG, msg);
16966        }
16967
16968        public void setError(String msg, PackageParserException e) {
16969            setReturnCode(e.error);
16970            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16971            Slog.w(TAG, msg, e);
16972        }
16973
16974        public void setError(String msg, PackageManagerException e) {
16975            returnCode = e.error;
16976            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16977            Slog.w(TAG, msg, e);
16978        }
16979
16980        public void setReturnCode(int returnCode) {
16981            this.returnCode = returnCode;
16982            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16983            for (int i = 0; i < childCount; i++) {
16984                addedChildPackages.valueAt(i).returnCode = returnCode;
16985            }
16986        }
16987
16988        private void setReturnMessage(String returnMsg) {
16989            this.returnMsg = returnMsg;
16990            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16991            for (int i = 0; i < childCount; i++) {
16992                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16993            }
16994        }
16995
16996        // In some error cases we want to convey more info back to the observer
16997        String origPackage;
16998        String origPermission;
16999    }
17000
17001    /*
17002     * Install a non-existing package.
17003     */
17004    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17005            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17006            PackageInstalledInfo res, int installReason) {
17007        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17008
17009        // Remember this for later, in case we need to rollback this install
17010        String pkgName = pkg.packageName;
17011
17012        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17013
17014        synchronized(mPackages) {
17015            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17016            if (renamedPackage != null) {
17017                // A package with the same name is already installed, though
17018                // it has been renamed to an older name.  The package we
17019                // are trying to install should be installed as an update to
17020                // the existing one, but that has not been requested, so bail.
17021                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17022                        + " without first uninstalling package running as "
17023                        + renamedPackage);
17024                return;
17025            }
17026            if (mPackages.containsKey(pkgName)) {
17027                // Don't allow installation over an existing package with the same name.
17028                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17029                        + " without first uninstalling.");
17030                return;
17031            }
17032        }
17033
17034        try {
17035            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17036                    System.currentTimeMillis(), user);
17037
17038            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17039
17040            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17041                prepareAppDataAfterInstallLIF(newPackage);
17042
17043            } else {
17044                // Remove package from internal structures, but keep around any
17045                // data that might have already existed
17046                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17047                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17048            }
17049        } catch (PackageManagerException e) {
17050            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17051        }
17052
17053        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17054    }
17055
17056    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17057        // Can't rotate keys during boot or if sharedUser.
17058        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17059                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17060            return false;
17061        }
17062        // app is using upgradeKeySets; make sure all are valid
17063        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17064        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17065        for (int i = 0; i < upgradeKeySets.length; i++) {
17066            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17067                Slog.wtf(TAG, "Package "
17068                         + (oldPs.name != null ? oldPs.name : "<null>")
17069                         + " contains upgrade-key-set reference to unknown key-set: "
17070                         + upgradeKeySets[i]
17071                         + " reverting to signatures check.");
17072                return false;
17073            }
17074        }
17075        return true;
17076    }
17077
17078    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17079        // Upgrade keysets are being used.  Determine if new package has a superset of the
17080        // required keys.
17081        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17082        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17083        for (int i = 0; i < upgradeKeySets.length; i++) {
17084            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17085            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17086                return true;
17087            }
17088        }
17089        return false;
17090    }
17091
17092    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17093        try (DigestInputStream digestStream =
17094                new DigestInputStream(new FileInputStream(file), digest)) {
17095            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17096        }
17097    }
17098
17099    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17100            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17101            int installReason) {
17102        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17103
17104        final PackageParser.Package oldPackage;
17105        final PackageSetting ps;
17106        final String pkgName = pkg.packageName;
17107        final int[] allUsers;
17108        final int[] installedUsers;
17109
17110        synchronized(mPackages) {
17111            oldPackage = mPackages.get(pkgName);
17112            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17113
17114            // don't allow upgrade to target a release SDK from a pre-release SDK
17115            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17116                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17117            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17118                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17119            if (oldTargetsPreRelease
17120                    && !newTargetsPreRelease
17121                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17122                Slog.w(TAG, "Can't install package targeting released sdk");
17123                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17124                return;
17125            }
17126
17127            ps = mSettings.mPackages.get(pkgName);
17128
17129            // verify signatures are valid
17130            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17131                if (!checkUpgradeKeySetLP(ps, pkg)) {
17132                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17133                            "New package not signed by keys specified by upgrade-keysets: "
17134                                    + pkgName);
17135                    return;
17136                }
17137            } else {
17138                // default to original signature matching
17139                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17140                        != PackageManager.SIGNATURE_MATCH) {
17141                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17142                            "New package has a different signature: " + pkgName);
17143                    return;
17144                }
17145            }
17146
17147            // don't allow a system upgrade unless the upgrade hash matches
17148            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17149                byte[] digestBytes = null;
17150                try {
17151                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17152                    updateDigest(digest, new File(pkg.baseCodePath));
17153                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17154                        for (String path : pkg.splitCodePaths) {
17155                            updateDigest(digest, new File(path));
17156                        }
17157                    }
17158                    digestBytes = digest.digest();
17159                } catch (NoSuchAlgorithmException | IOException e) {
17160                    res.setError(INSTALL_FAILED_INVALID_APK,
17161                            "Could not compute hash: " + pkgName);
17162                    return;
17163                }
17164                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17165                    res.setError(INSTALL_FAILED_INVALID_APK,
17166                            "New package fails restrict-update check: " + pkgName);
17167                    return;
17168                }
17169                // retain upgrade restriction
17170                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17171            }
17172
17173            // Check for shared user id changes
17174            String invalidPackageName =
17175                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17176            if (invalidPackageName != null) {
17177                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17178                        "Package " + invalidPackageName + " tried to change user "
17179                                + oldPackage.mSharedUserId);
17180                return;
17181            }
17182
17183            // In case of rollback, remember per-user/profile install state
17184            allUsers = sUserManager.getUserIds();
17185            installedUsers = ps.queryInstalledUsers(allUsers, true);
17186
17187            // don't allow an upgrade from full to ephemeral
17188            if (isInstantApp) {
17189                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17190                    for (int currentUser : allUsers) {
17191                        if (!ps.getInstantApp(currentUser)) {
17192                            // can't downgrade from full to instant
17193                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17194                                    + " for user: " + currentUser);
17195                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17196                            return;
17197                        }
17198                    }
17199                } else if (!ps.getInstantApp(user.getIdentifier())) {
17200                    // can't downgrade from full to instant
17201                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17202                            + " for user: " + user.getIdentifier());
17203                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17204                    return;
17205                }
17206            }
17207        }
17208
17209        // Update what is removed
17210        res.removedInfo = new PackageRemovedInfo(this);
17211        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17212        res.removedInfo.removedPackage = oldPackage.packageName;
17213        res.removedInfo.installerPackageName = ps.installerPackageName;
17214        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17215        res.removedInfo.isUpdate = true;
17216        res.removedInfo.origUsers = installedUsers;
17217        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17218        for (int i = 0; i < installedUsers.length; i++) {
17219            final int userId = installedUsers[i];
17220            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17221        }
17222
17223        final int childCount = (oldPackage.childPackages != null)
17224                ? oldPackage.childPackages.size() : 0;
17225        for (int i = 0; i < childCount; i++) {
17226            boolean childPackageUpdated = false;
17227            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17228            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17229            if (res.addedChildPackages != null) {
17230                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17231                if (childRes != null) {
17232                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17233                    childRes.removedInfo.removedPackage = childPkg.packageName;
17234                    if (childPs != null) {
17235                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17236                    }
17237                    childRes.removedInfo.isUpdate = true;
17238                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17239                    childPackageUpdated = true;
17240                }
17241            }
17242            if (!childPackageUpdated) {
17243                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17244                childRemovedRes.removedPackage = childPkg.packageName;
17245                if (childPs != null) {
17246                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17247                }
17248                childRemovedRes.isUpdate = false;
17249                childRemovedRes.dataRemoved = true;
17250                synchronized (mPackages) {
17251                    if (childPs != null) {
17252                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17253                    }
17254                }
17255                if (res.removedInfo.removedChildPackages == null) {
17256                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17257                }
17258                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17259            }
17260        }
17261
17262        boolean sysPkg = (isSystemApp(oldPackage));
17263        if (sysPkg) {
17264            // Set the system/privileged flags as needed
17265            final boolean privileged =
17266                    (oldPackage.applicationInfo.privateFlags
17267                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17268            final int systemPolicyFlags = policyFlags
17269                    | PackageParser.PARSE_IS_SYSTEM
17270                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17271
17272            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17273                    user, allUsers, installerPackageName, res, installReason);
17274        } else {
17275            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17276                    user, allUsers, installerPackageName, res, installReason);
17277        }
17278    }
17279
17280    @Override
17281    public List<String> getPreviousCodePaths(String packageName) {
17282        final int callingUid = Binder.getCallingUid();
17283        final List<String> result = new ArrayList<>();
17284        if (getInstantAppPackageName(callingUid) != null) {
17285            return result;
17286        }
17287        final PackageSetting ps = mSettings.mPackages.get(packageName);
17288        if (ps != null
17289                && ps.oldCodePaths != null
17290                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17291            result.addAll(ps.oldCodePaths);
17292        }
17293        return result;
17294    }
17295
17296    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17297            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17298            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17299            int installReason) {
17300        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17301                + deletedPackage);
17302
17303        String pkgName = deletedPackage.packageName;
17304        boolean deletedPkg = true;
17305        boolean addedPkg = false;
17306        boolean updatedSettings = false;
17307        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17308        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17309                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17310
17311        final long origUpdateTime = (pkg.mExtras != null)
17312                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17313
17314        // First delete the existing package while retaining the data directory
17315        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17316                res.removedInfo, true, pkg)) {
17317            // If the existing package wasn't successfully deleted
17318            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17319            deletedPkg = false;
17320        } else {
17321            // Successfully deleted the old package; proceed with replace.
17322
17323            // If deleted package lived in a container, give users a chance to
17324            // relinquish resources before killing.
17325            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17326                if (DEBUG_INSTALL) {
17327                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17328                }
17329                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17330                final ArrayList<String> pkgList = new ArrayList<String>(1);
17331                pkgList.add(deletedPackage.applicationInfo.packageName);
17332                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17333            }
17334
17335            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17336                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17337            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17338
17339            try {
17340                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17341                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17342                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17343                        installReason);
17344
17345                // Update the in-memory copy of the previous code paths.
17346                PackageSetting ps = mSettings.mPackages.get(pkgName);
17347                if (!killApp) {
17348                    if (ps.oldCodePaths == null) {
17349                        ps.oldCodePaths = new ArraySet<>();
17350                    }
17351                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17352                    if (deletedPackage.splitCodePaths != null) {
17353                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17354                    }
17355                } else {
17356                    ps.oldCodePaths = null;
17357                }
17358                if (ps.childPackageNames != null) {
17359                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17360                        final String childPkgName = ps.childPackageNames.get(i);
17361                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17362                        childPs.oldCodePaths = ps.oldCodePaths;
17363                    }
17364                }
17365                // set instant app status, but, only if it's explicitly specified
17366                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17367                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17368                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17369                prepareAppDataAfterInstallLIF(newPackage);
17370                addedPkg = true;
17371                mDexManager.notifyPackageUpdated(newPackage.packageName,
17372                        newPackage.baseCodePath, newPackage.splitCodePaths);
17373            } catch (PackageManagerException e) {
17374                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17375            }
17376        }
17377
17378        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17379            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17380
17381            // Revert all internal state mutations and added folders for the failed install
17382            if (addedPkg) {
17383                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17384                        res.removedInfo, true, null);
17385            }
17386
17387            // Restore the old package
17388            if (deletedPkg) {
17389                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17390                File restoreFile = new File(deletedPackage.codePath);
17391                // Parse old package
17392                boolean oldExternal = isExternal(deletedPackage);
17393                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17394                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17395                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17396                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17397                try {
17398                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17399                            null);
17400                } catch (PackageManagerException e) {
17401                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17402                            + e.getMessage());
17403                    return;
17404                }
17405
17406                synchronized (mPackages) {
17407                    // Ensure the installer package name up to date
17408                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17409
17410                    // Update permissions for restored package
17411                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17412
17413                    mSettings.writeLPr();
17414                }
17415
17416                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17417            }
17418        } else {
17419            synchronized (mPackages) {
17420                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17421                if (ps != null) {
17422                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17423                    if (res.removedInfo.removedChildPackages != null) {
17424                        final int childCount = res.removedInfo.removedChildPackages.size();
17425                        // Iterate in reverse as we may modify the collection
17426                        for (int i = childCount - 1; i >= 0; i--) {
17427                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17428                            if (res.addedChildPackages.containsKey(childPackageName)) {
17429                                res.removedInfo.removedChildPackages.removeAt(i);
17430                            } else {
17431                                PackageRemovedInfo childInfo = res.removedInfo
17432                                        .removedChildPackages.valueAt(i);
17433                                childInfo.removedForAllUsers = mPackages.get(
17434                                        childInfo.removedPackage) == null;
17435                            }
17436                        }
17437                    }
17438                }
17439            }
17440        }
17441    }
17442
17443    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17444            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17445            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17446            int installReason) {
17447        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17448                + ", old=" + deletedPackage);
17449
17450        final boolean disabledSystem;
17451
17452        // Remove existing system package
17453        removePackageLI(deletedPackage, true);
17454
17455        synchronized (mPackages) {
17456            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17457        }
17458        if (!disabledSystem) {
17459            // We didn't need to disable the .apk as a current system package,
17460            // which means we are replacing another update that is already
17461            // installed.  We need to make sure to delete the older one's .apk.
17462            res.removedInfo.args = createInstallArgsForExisting(0,
17463                    deletedPackage.applicationInfo.getCodePath(),
17464                    deletedPackage.applicationInfo.getResourcePath(),
17465                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17466        } else {
17467            res.removedInfo.args = null;
17468        }
17469
17470        // Successfully disabled the old package. Now proceed with re-installation
17471        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17472                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17473        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17474
17475        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17476        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17477                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17478
17479        PackageParser.Package newPackage = null;
17480        try {
17481            // Add the package to the internal data structures
17482            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17483
17484            // Set the update and install times
17485            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17486            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17487                    System.currentTimeMillis());
17488
17489            // Update the package dynamic state if succeeded
17490            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17491                // Now that the install succeeded make sure we remove data
17492                // directories for any child package the update removed.
17493                final int deletedChildCount = (deletedPackage.childPackages != null)
17494                        ? deletedPackage.childPackages.size() : 0;
17495                final int newChildCount = (newPackage.childPackages != null)
17496                        ? newPackage.childPackages.size() : 0;
17497                for (int i = 0; i < deletedChildCount; i++) {
17498                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17499                    boolean childPackageDeleted = true;
17500                    for (int j = 0; j < newChildCount; j++) {
17501                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17502                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17503                            childPackageDeleted = false;
17504                            break;
17505                        }
17506                    }
17507                    if (childPackageDeleted) {
17508                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17509                                deletedChildPkg.packageName);
17510                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17511                            PackageRemovedInfo removedChildRes = res.removedInfo
17512                                    .removedChildPackages.get(deletedChildPkg.packageName);
17513                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17514                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17515                        }
17516                    }
17517                }
17518
17519                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17520                        installReason);
17521                prepareAppDataAfterInstallLIF(newPackage);
17522
17523                mDexManager.notifyPackageUpdated(newPackage.packageName,
17524                            newPackage.baseCodePath, newPackage.splitCodePaths);
17525            }
17526        } catch (PackageManagerException e) {
17527            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17528            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17529        }
17530
17531        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17532            // Re installation failed. Restore old information
17533            // Remove new pkg information
17534            if (newPackage != null) {
17535                removeInstalledPackageLI(newPackage, true);
17536            }
17537            // Add back the old system package
17538            try {
17539                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17540            } catch (PackageManagerException e) {
17541                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17542            }
17543
17544            synchronized (mPackages) {
17545                if (disabledSystem) {
17546                    enableSystemPackageLPw(deletedPackage);
17547                }
17548
17549                // Ensure the installer package name up to date
17550                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17551
17552                // Update permissions for restored package
17553                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17554
17555                mSettings.writeLPr();
17556            }
17557
17558            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17559                    + " after failed upgrade");
17560        }
17561    }
17562
17563    /**
17564     * Checks whether the parent or any of the child packages have a change shared
17565     * user. For a package to be a valid update the shred users of the parent and
17566     * the children should match. We may later support changing child shared users.
17567     * @param oldPkg The updated package.
17568     * @param newPkg The update package.
17569     * @return The shared user that change between the versions.
17570     */
17571    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17572            PackageParser.Package newPkg) {
17573        // Check parent shared user
17574        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17575            return newPkg.packageName;
17576        }
17577        // Check child shared users
17578        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17579        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17580        for (int i = 0; i < newChildCount; i++) {
17581            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17582            // If this child was present, did it have the same shared user?
17583            for (int j = 0; j < oldChildCount; j++) {
17584                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17585                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17586                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17587                    return newChildPkg.packageName;
17588                }
17589            }
17590        }
17591        return null;
17592    }
17593
17594    private void removeNativeBinariesLI(PackageSetting ps) {
17595        // Remove the lib path for the parent package
17596        if (ps != null) {
17597            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17598            // Remove the lib path for the child packages
17599            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17600            for (int i = 0; i < childCount; i++) {
17601                PackageSetting childPs = null;
17602                synchronized (mPackages) {
17603                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17604                }
17605                if (childPs != null) {
17606                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17607                            .legacyNativeLibraryPathString);
17608                }
17609            }
17610        }
17611    }
17612
17613    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17614        // Enable the parent package
17615        mSettings.enableSystemPackageLPw(pkg.packageName);
17616        // Enable the child packages
17617        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17618        for (int i = 0; i < childCount; i++) {
17619            PackageParser.Package childPkg = pkg.childPackages.get(i);
17620            mSettings.enableSystemPackageLPw(childPkg.packageName);
17621        }
17622    }
17623
17624    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17625            PackageParser.Package newPkg) {
17626        // Disable the parent package (parent always replaced)
17627        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17628        // Disable the child packages
17629        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17630        for (int i = 0; i < childCount; i++) {
17631            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17632            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17633            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17634        }
17635        return disabled;
17636    }
17637
17638    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17639            String installerPackageName) {
17640        // Enable the parent package
17641        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17642        // Enable the child packages
17643        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17644        for (int i = 0; i < childCount; i++) {
17645            PackageParser.Package childPkg = pkg.childPackages.get(i);
17646            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17647        }
17648    }
17649
17650    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17651        // Collect all used permissions in the UID
17652        ArraySet<String> usedPermissions = new ArraySet<>();
17653        final int packageCount = su.packages.size();
17654        for (int i = 0; i < packageCount; i++) {
17655            PackageSetting ps = su.packages.valueAt(i);
17656            if (ps.pkg == null) {
17657                continue;
17658            }
17659            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17660            for (int j = 0; j < requestedPermCount; j++) {
17661                String permission = ps.pkg.requestedPermissions.get(j);
17662                BasePermission bp = mSettings.mPermissions.get(permission);
17663                if (bp != null) {
17664                    usedPermissions.add(permission);
17665                }
17666            }
17667        }
17668
17669        PermissionsState permissionsState = su.getPermissionsState();
17670        // Prune install permissions
17671        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17672        final int installPermCount = installPermStates.size();
17673        for (int i = installPermCount - 1; i >= 0;  i--) {
17674            PermissionState permissionState = installPermStates.get(i);
17675            if (!usedPermissions.contains(permissionState.getName())) {
17676                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17677                if (bp != null) {
17678                    permissionsState.revokeInstallPermission(bp);
17679                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17680                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17681                }
17682            }
17683        }
17684
17685        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17686
17687        // Prune runtime permissions
17688        for (int userId : allUserIds) {
17689            List<PermissionState> runtimePermStates = permissionsState
17690                    .getRuntimePermissionStates(userId);
17691            final int runtimePermCount = runtimePermStates.size();
17692            for (int i = runtimePermCount - 1; i >= 0; i--) {
17693                PermissionState permissionState = runtimePermStates.get(i);
17694                if (!usedPermissions.contains(permissionState.getName())) {
17695                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17696                    if (bp != null) {
17697                        permissionsState.revokeRuntimePermission(bp, userId);
17698                        permissionsState.updatePermissionFlags(bp, userId,
17699                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17700                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17701                                runtimePermissionChangedUserIds, userId);
17702                    }
17703                }
17704            }
17705        }
17706
17707        return runtimePermissionChangedUserIds;
17708    }
17709
17710    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17711            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17712        // Update the parent package setting
17713        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17714                res, user, installReason);
17715        // Update the child packages setting
17716        final int childCount = (newPackage.childPackages != null)
17717                ? newPackage.childPackages.size() : 0;
17718        for (int i = 0; i < childCount; i++) {
17719            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17720            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17721            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17722                    childRes.origUsers, childRes, user, installReason);
17723        }
17724    }
17725
17726    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17727            String installerPackageName, int[] allUsers, int[] installedForUsers,
17728            PackageInstalledInfo res, UserHandle user, int installReason) {
17729        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17730
17731        String pkgName = newPackage.packageName;
17732        synchronized (mPackages) {
17733            //write settings. the installStatus will be incomplete at this stage.
17734            //note that the new package setting would have already been
17735            //added to mPackages. It hasn't been persisted yet.
17736            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17737            // TODO: Remove this write? It's also written at the end of this method
17738            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17739            mSettings.writeLPr();
17740            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17741        }
17742
17743        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17744        synchronized (mPackages) {
17745            updatePermissionsLPw(newPackage.packageName, newPackage,
17746                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17747                            ? UPDATE_PERMISSIONS_ALL : 0));
17748            // For system-bundled packages, we assume that installing an upgraded version
17749            // of the package implies that the user actually wants to run that new code,
17750            // so we enable the package.
17751            PackageSetting ps = mSettings.mPackages.get(pkgName);
17752            final int userId = user.getIdentifier();
17753            if (ps != null) {
17754                if (isSystemApp(newPackage)) {
17755                    if (DEBUG_INSTALL) {
17756                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17757                    }
17758                    // Enable system package for requested users
17759                    if (res.origUsers != null) {
17760                        for (int origUserId : res.origUsers) {
17761                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17762                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17763                                        origUserId, installerPackageName);
17764                            }
17765                        }
17766                    }
17767                    // Also convey the prior install/uninstall state
17768                    if (allUsers != null && installedForUsers != null) {
17769                        for (int currentUserId : allUsers) {
17770                            final boolean installed = ArrayUtils.contains(
17771                                    installedForUsers, currentUserId);
17772                            if (DEBUG_INSTALL) {
17773                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17774                            }
17775                            ps.setInstalled(installed, currentUserId);
17776                        }
17777                        // these install state changes will be persisted in the
17778                        // upcoming call to mSettings.writeLPr().
17779                    }
17780                }
17781                // It's implied that when a user requests installation, they want the app to be
17782                // installed and enabled.
17783                if (userId != UserHandle.USER_ALL) {
17784                    ps.setInstalled(true, userId);
17785                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17786                }
17787
17788                // When replacing an existing package, preserve the original install reason for all
17789                // users that had the package installed before.
17790                final Set<Integer> previousUserIds = new ArraySet<>();
17791                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17792                    final int installReasonCount = res.removedInfo.installReasons.size();
17793                    for (int i = 0; i < installReasonCount; i++) {
17794                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17795                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17796                        ps.setInstallReason(previousInstallReason, previousUserId);
17797                        previousUserIds.add(previousUserId);
17798                    }
17799                }
17800
17801                // Set install reason for users that are having the package newly installed.
17802                if (userId == UserHandle.USER_ALL) {
17803                    for (int currentUserId : sUserManager.getUserIds()) {
17804                        if (!previousUserIds.contains(currentUserId)) {
17805                            ps.setInstallReason(installReason, currentUserId);
17806                        }
17807                    }
17808                } else if (!previousUserIds.contains(userId)) {
17809                    ps.setInstallReason(installReason, userId);
17810                }
17811                mSettings.writeKernelMappingLPr(ps);
17812            }
17813            res.name = pkgName;
17814            res.uid = newPackage.applicationInfo.uid;
17815            res.pkg = newPackage;
17816            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17817            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17818            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17819            //to update install status
17820            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17821            mSettings.writeLPr();
17822            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17823        }
17824
17825        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17826    }
17827
17828    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17829        try {
17830            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17831            installPackageLI(args, res);
17832        } finally {
17833            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17834        }
17835    }
17836
17837    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17838        final int installFlags = args.installFlags;
17839        final String installerPackageName = args.installerPackageName;
17840        final String volumeUuid = args.volumeUuid;
17841        final File tmpPackageFile = new File(args.getCodePath());
17842        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17843        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17844                || (args.volumeUuid != null));
17845        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17846        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17847        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17848        boolean replace = false;
17849        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17850        if (args.move != null) {
17851            // moving a complete application; perform an initial scan on the new install location
17852            scanFlags |= SCAN_INITIAL;
17853        }
17854        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17855            scanFlags |= SCAN_DONT_KILL_APP;
17856        }
17857        if (instantApp) {
17858            scanFlags |= SCAN_AS_INSTANT_APP;
17859        }
17860        if (fullApp) {
17861            scanFlags |= SCAN_AS_FULL_APP;
17862        }
17863
17864        // Result object to be returned
17865        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17866
17867        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17868
17869        // Sanity check
17870        if (instantApp && (forwardLocked || onExternal)) {
17871            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17872                    + " external=" + onExternal);
17873            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17874            return;
17875        }
17876
17877        // Retrieve PackageSettings and parse package
17878        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17879                | PackageParser.PARSE_ENFORCE_CODE
17880                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17881                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17882                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17883                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17884        PackageParser pp = new PackageParser();
17885        pp.setSeparateProcesses(mSeparateProcesses);
17886        pp.setDisplayMetrics(mMetrics);
17887        pp.setCallback(mPackageParserCallback);
17888
17889        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17890        final PackageParser.Package pkg;
17891        try {
17892            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17893        } catch (PackageParserException e) {
17894            res.setError("Failed parse during installPackageLI", e);
17895            return;
17896        } finally {
17897            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17898        }
17899
17900        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17901        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17902            Slog.w(TAG, "Instant app package " + pkg.packageName
17903                    + " does not target O, this will be a fatal error.");
17904            // STOPSHIP: Make this a fatal error
17905            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
17906        }
17907        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17908            Slog.w(TAG, "Instant app package " + pkg.packageName
17909                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
17910            // STOPSHIP: Make this a fatal error
17911            pkg.applicationInfo.targetSandboxVersion = 2;
17912        }
17913
17914        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17915            // Static shared libraries have synthetic package names
17916            renameStaticSharedLibraryPackage(pkg);
17917
17918            // No static shared libs on external storage
17919            if (onExternal) {
17920                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17921                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17922                        "Packages declaring static-shared libs cannot be updated");
17923                return;
17924            }
17925        }
17926
17927        // If we are installing a clustered package add results for the children
17928        if (pkg.childPackages != null) {
17929            synchronized (mPackages) {
17930                final int childCount = pkg.childPackages.size();
17931                for (int i = 0; i < childCount; i++) {
17932                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17933                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17934                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17935                    childRes.pkg = childPkg;
17936                    childRes.name = childPkg.packageName;
17937                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17938                    if (childPs != null) {
17939                        childRes.origUsers = childPs.queryInstalledUsers(
17940                                sUserManager.getUserIds(), true);
17941                    }
17942                    if ((mPackages.containsKey(childPkg.packageName))) {
17943                        childRes.removedInfo = new PackageRemovedInfo(this);
17944                        childRes.removedInfo.removedPackage = childPkg.packageName;
17945                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17946                    }
17947                    if (res.addedChildPackages == null) {
17948                        res.addedChildPackages = new ArrayMap<>();
17949                    }
17950                    res.addedChildPackages.put(childPkg.packageName, childRes);
17951                }
17952            }
17953        }
17954
17955        // If package doesn't declare API override, mark that we have an install
17956        // time CPU ABI override.
17957        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17958            pkg.cpuAbiOverride = args.abiOverride;
17959        }
17960
17961        String pkgName = res.name = pkg.packageName;
17962        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17963            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17964                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17965                return;
17966            }
17967        }
17968
17969        try {
17970            // either use what we've been given or parse directly from the APK
17971            if (args.certificates != null) {
17972                try {
17973                    PackageParser.populateCertificates(pkg, args.certificates);
17974                } catch (PackageParserException e) {
17975                    // there was something wrong with the certificates we were given;
17976                    // try to pull them from the APK
17977                    PackageParser.collectCertificates(pkg, parseFlags);
17978                }
17979            } else {
17980                PackageParser.collectCertificates(pkg, parseFlags);
17981            }
17982        } catch (PackageParserException e) {
17983            res.setError("Failed collect during installPackageLI", e);
17984            return;
17985        }
17986
17987        // Get rid of all references to package scan path via parser.
17988        pp = null;
17989        String oldCodePath = null;
17990        boolean systemApp = false;
17991        synchronized (mPackages) {
17992            // Check if installing already existing package
17993            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17994                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17995                if (pkg.mOriginalPackages != null
17996                        && pkg.mOriginalPackages.contains(oldName)
17997                        && mPackages.containsKey(oldName)) {
17998                    // This package is derived from an original package,
17999                    // and this device has been updating from that original
18000                    // name.  We must continue using the original name, so
18001                    // rename the new package here.
18002                    pkg.setPackageName(oldName);
18003                    pkgName = pkg.packageName;
18004                    replace = true;
18005                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18006                            + oldName + " pkgName=" + pkgName);
18007                } else if (mPackages.containsKey(pkgName)) {
18008                    // This package, under its official name, already exists
18009                    // on the device; we should replace it.
18010                    replace = true;
18011                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18012                }
18013
18014                // Child packages are installed through the parent package
18015                if (pkg.parentPackage != null) {
18016                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18017                            "Package " + pkg.packageName + " is child of package "
18018                                    + pkg.parentPackage.parentPackage + ". Child packages "
18019                                    + "can be updated only through the parent package.");
18020                    return;
18021                }
18022
18023                if (replace) {
18024                    // Prevent apps opting out from runtime permissions
18025                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18026                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18027                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18028                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18029                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18030                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18031                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18032                                        + " doesn't support runtime permissions but the old"
18033                                        + " target SDK " + oldTargetSdk + " does.");
18034                        return;
18035                    }
18036                    // Prevent apps from downgrading their targetSandbox.
18037                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18038                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18039                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18040                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18041                                "Package " + pkg.packageName + " new target sandbox "
18042                                + newTargetSandbox + " is incompatible with the previous value of"
18043                                + oldTargetSandbox + ".");
18044                        return;
18045                    }
18046
18047                    // Prevent installing of child packages
18048                    if (oldPackage.parentPackage != null) {
18049                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18050                                "Package " + pkg.packageName + " is child of package "
18051                                        + oldPackage.parentPackage + ". Child packages "
18052                                        + "can be updated only through the parent package.");
18053                        return;
18054                    }
18055                }
18056            }
18057
18058            PackageSetting ps = mSettings.mPackages.get(pkgName);
18059            if (ps != null) {
18060                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18061
18062                // Static shared libs have same package with different versions where
18063                // we internally use a synthetic package name to allow multiple versions
18064                // of the same package, therefore we need to compare signatures against
18065                // the package setting for the latest library version.
18066                PackageSetting signatureCheckPs = ps;
18067                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18068                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18069                    if (libraryEntry != null) {
18070                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18071                    }
18072                }
18073
18074                // Quick sanity check that we're signed correctly if updating;
18075                // we'll check this again later when scanning, but we want to
18076                // bail early here before tripping over redefined permissions.
18077                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18078                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18079                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18080                                + pkg.packageName + " upgrade keys do not match the "
18081                                + "previously installed version");
18082                        return;
18083                    }
18084                } else {
18085                    try {
18086                        verifySignaturesLP(signatureCheckPs, pkg);
18087                    } catch (PackageManagerException e) {
18088                        res.setError(e.error, e.getMessage());
18089                        return;
18090                    }
18091                }
18092
18093                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18094                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18095                    systemApp = (ps.pkg.applicationInfo.flags &
18096                            ApplicationInfo.FLAG_SYSTEM) != 0;
18097                }
18098                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18099            }
18100
18101            int N = pkg.permissions.size();
18102            for (int i = N-1; i >= 0; i--) {
18103                PackageParser.Permission perm = pkg.permissions.get(i);
18104                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18105
18106                // Don't allow anyone but the system to define ephemeral permissions.
18107                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18108                        && !systemApp) {
18109                    Slog.w(TAG, "Non-System package " + pkg.packageName
18110                            + " attempting to delcare ephemeral permission "
18111                            + perm.info.name + "; Removing ephemeral.");
18112                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18113                }
18114                // Check whether the newly-scanned package wants to define an already-defined perm
18115                if (bp != null) {
18116                    // If the defining package is signed with our cert, it's okay.  This
18117                    // also includes the "updating the same package" case, of course.
18118                    // "updating same package" could also involve key-rotation.
18119                    final boolean sigsOk;
18120                    if (bp.sourcePackage.equals(pkg.packageName)
18121                            && (bp.packageSetting instanceof PackageSetting)
18122                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18123                                    scanFlags))) {
18124                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18125                    } else {
18126                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18127                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18128                    }
18129                    if (!sigsOk) {
18130                        // If the owning package is the system itself, we log but allow
18131                        // install to proceed; we fail the install on all other permission
18132                        // redefinitions.
18133                        if (!bp.sourcePackage.equals("android")) {
18134                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18135                                    + pkg.packageName + " attempting to redeclare permission "
18136                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18137                            res.origPermission = perm.info.name;
18138                            res.origPackage = bp.sourcePackage;
18139                            return;
18140                        } else {
18141                            Slog.w(TAG, "Package " + pkg.packageName
18142                                    + " attempting to redeclare system permission "
18143                                    + perm.info.name + "; ignoring new declaration");
18144                            pkg.permissions.remove(i);
18145                        }
18146                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18147                        // Prevent apps to change protection level to dangerous from any other
18148                        // type as this would allow a privilege escalation where an app adds a
18149                        // normal/signature permission in other app's group and later redefines
18150                        // it as dangerous leading to the group auto-grant.
18151                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18152                                == PermissionInfo.PROTECTION_DANGEROUS) {
18153                            if (bp != null && !bp.isRuntime()) {
18154                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18155                                        + "non-runtime permission " + perm.info.name
18156                                        + " to runtime; keeping old protection level");
18157                                perm.info.protectionLevel = bp.protectionLevel;
18158                            }
18159                        }
18160                    }
18161                }
18162            }
18163        }
18164
18165        if (systemApp) {
18166            if (onExternal) {
18167                // Abort update; system app can't be replaced with app on sdcard
18168                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18169                        "Cannot install updates to system apps on sdcard");
18170                return;
18171            } else if (instantApp) {
18172                // Abort update; system app can't be replaced with an instant app
18173                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18174                        "Cannot update a system app with an instant app");
18175                return;
18176            }
18177        }
18178
18179        if (args.move != null) {
18180            // We did an in-place move, so dex is ready to roll
18181            scanFlags |= SCAN_NO_DEX;
18182            scanFlags |= SCAN_MOVE;
18183
18184            synchronized (mPackages) {
18185                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18186                if (ps == null) {
18187                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18188                            "Missing settings for moved package " + pkgName);
18189                }
18190
18191                // We moved the entire application as-is, so bring over the
18192                // previously derived ABI information.
18193                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18194                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18195            }
18196
18197        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18198            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18199            scanFlags |= SCAN_NO_DEX;
18200
18201            try {
18202                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18203                    args.abiOverride : pkg.cpuAbiOverride);
18204                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18205                        true /*extractLibs*/, mAppLib32InstallDir);
18206            } catch (PackageManagerException pme) {
18207                Slog.e(TAG, "Error deriving application ABI", pme);
18208                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18209                return;
18210            }
18211
18212            // Shared libraries for the package need to be updated.
18213            synchronized (mPackages) {
18214                try {
18215                    updateSharedLibrariesLPr(pkg, null);
18216                } catch (PackageManagerException e) {
18217                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18218                }
18219            }
18220
18221            // dexopt can take some time to complete, so, for instant apps, we skip this
18222            // step during installation. Instead, we'll take extra time the first time the
18223            // instant app starts. It's preferred to do it this way to provide continuous
18224            // progress to the user instead of mysteriously blocking somewhere in the
18225            // middle of running an instant app.
18226            if (!instantApp) {
18227                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18228                // Do not run PackageDexOptimizer through the local performDexOpt
18229                // method because `pkg` may not be in `mPackages` yet.
18230                //
18231                // Also, don't fail application installs if the dexopt step fails.
18232                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18233                        null /* instructionSets */, false /* checkProfiles */,
18234                        getCompilerFilterForReason(REASON_INSTALL),
18235                        getOrCreateCompilerPackageStats(pkg),
18236                        mDexManager.isUsedByOtherApps(pkg.packageName),
18237                        true /* bootComplete */);
18238                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18239            }
18240
18241            // Notify BackgroundDexOptService that the package has been changed.
18242            // If this is an update of a package which used to fail to compile,
18243            // BDOS will remove it from its blacklist.
18244            // TODO: Layering violation
18245            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18246        }
18247
18248        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18249            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18250            return;
18251        }
18252
18253        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18254
18255        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18256                "installPackageLI")) {
18257            if (replace) {
18258                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18259                    // Static libs have a synthetic package name containing the version
18260                    // and cannot be updated as an update would get a new package name,
18261                    // unless this is the exact same version code which is useful for
18262                    // development.
18263                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18264                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18265                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18266                                + "static-shared libs cannot be updated");
18267                        return;
18268                    }
18269                }
18270                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18271                        installerPackageName, res, args.installReason);
18272            } else {
18273                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18274                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18275            }
18276        }
18277
18278        synchronized (mPackages) {
18279            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18280            if (ps != null) {
18281                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18282                ps.setUpdateAvailable(false /*updateAvailable*/);
18283            }
18284
18285            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18286            for (int i = 0; i < childCount; i++) {
18287                PackageParser.Package childPkg = pkg.childPackages.get(i);
18288                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18289                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18290                if (childPs != null) {
18291                    childRes.newUsers = childPs.queryInstalledUsers(
18292                            sUserManager.getUserIds(), true);
18293                }
18294            }
18295
18296            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18297                updateSequenceNumberLP(ps, res.newUsers);
18298                updateInstantAppInstallerLocked(pkgName);
18299            }
18300        }
18301    }
18302
18303    private void startIntentFilterVerifications(int userId, boolean replacing,
18304            PackageParser.Package pkg) {
18305        if (mIntentFilterVerifierComponent == null) {
18306            Slog.w(TAG, "No IntentFilter verification will not be done as "
18307                    + "there is no IntentFilterVerifier available!");
18308            return;
18309        }
18310
18311        final int verifierUid = getPackageUid(
18312                mIntentFilterVerifierComponent.getPackageName(),
18313                MATCH_DEBUG_TRIAGED_MISSING,
18314                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18315
18316        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18317        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18318        mHandler.sendMessage(msg);
18319
18320        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18321        for (int i = 0; i < childCount; i++) {
18322            PackageParser.Package childPkg = pkg.childPackages.get(i);
18323            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18324            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18325            mHandler.sendMessage(msg);
18326        }
18327    }
18328
18329    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18330            PackageParser.Package pkg) {
18331        int size = pkg.activities.size();
18332        if (size == 0) {
18333            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18334                    "No activity, so no need to verify any IntentFilter!");
18335            return;
18336        }
18337
18338        final boolean hasDomainURLs = hasDomainURLs(pkg);
18339        if (!hasDomainURLs) {
18340            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18341                    "No domain URLs, so no need to verify any IntentFilter!");
18342            return;
18343        }
18344
18345        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18346                + " if any IntentFilter from the " + size
18347                + " Activities needs verification ...");
18348
18349        int count = 0;
18350        final String packageName = pkg.packageName;
18351
18352        synchronized (mPackages) {
18353            // If this is a new install and we see that we've already run verification for this
18354            // package, we have nothing to do: it means the state was restored from backup.
18355            if (!replacing) {
18356                IntentFilterVerificationInfo ivi =
18357                        mSettings.getIntentFilterVerificationLPr(packageName);
18358                if (ivi != null) {
18359                    if (DEBUG_DOMAIN_VERIFICATION) {
18360                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18361                                + ivi.getStatusString());
18362                    }
18363                    return;
18364                }
18365            }
18366
18367            // If any filters need to be verified, then all need to be.
18368            boolean needToVerify = false;
18369            for (PackageParser.Activity a : pkg.activities) {
18370                for (ActivityIntentInfo filter : a.intents) {
18371                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18372                        if (DEBUG_DOMAIN_VERIFICATION) {
18373                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18374                        }
18375                        needToVerify = true;
18376                        break;
18377                    }
18378                }
18379            }
18380
18381            if (needToVerify) {
18382                final int verificationId = mIntentFilterVerificationToken++;
18383                for (PackageParser.Activity a : pkg.activities) {
18384                    for (ActivityIntentInfo filter : a.intents) {
18385                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18386                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18387                                    "Verification needed for IntentFilter:" + filter.toString());
18388                            mIntentFilterVerifier.addOneIntentFilterVerification(
18389                                    verifierUid, userId, verificationId, filter, packageName);
18390                            count++;
18391                        }
18392                    }
18393                }
18394            }
18395        }
18396
18397        if (count > 0) {
18398            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18399                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18400                    +  " for userId:" + userId);
18401            mIntentFilterVerifier.startVerifications(userId);
18402        } else {
18403            if (DEBUG_DOMAIN_VERIFICATION) {
18404                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18405            }
18406        }
18407    }
18408
18409    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18410        final ComponentName cn  = filter.activity.getComponentName();
18411        final String packageName = cn.getPackageName();
18412
18413        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18414                packageName);
18415        if (ivi == null) {
18416            return true;
18417        }
18418        int status = ivi.getStatus();
18419        switch (status) {
18420            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18421            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18422                return true;
18423
18424            default:
18425                // Nothing to do
18426                return false;
18427        }
18428    }
18429
18430    private static boolean isMultiArch(ApplicationInfo info) {
18431        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18432    }
18433
18434    private static boolean isExternal(PackageParser.Package pkg) {
18435        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18436    }
18437
18438    private static boolean isExternal(PackageSetting ps) {
18439        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18440    }
18441
18442    private static boolean isSystemApp(PackageParser.Package pkg) {
18443        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18444    }
18445
18446    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18447        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18448    }
18449
18450    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18451        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18452    }
18453
18454    private static boolean isSystemApp(PackageSetting ps) {
18455        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18456    }
18457
18458    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18459        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18460    }
18461
18462    private int packageFlagsToInstallFlags(PackageSetting ps) {
18463        int installFlags = 0;
18464        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18465            // This existing package was an external ASEC install when we have
18466            // the external flag without a UUID
18467            installFlags |= PackageManager.INSTALL_EXTERNAL;
18468        }
18469        if (ps.isForwardLocked()) {
18470            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18471        }
18472        return installFlags;
18473    }
18474
18475    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18476        if (isExternal(pkg)) {
18477            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18478                return StorageManager.UUID_PRIMARY_PHYSICAL;
18479            } else {
18480                return pkg.volumeUuid;
18481            }
18482        } else {
18483            return StorageManager.UUID_PRIVATE_INTERNAL;
18484        }
18485    }
18486
18487    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18488        if (isExternal(pkg)) {
18489            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18490                return mSettings.getExternalVersion();
18491            } else {
18492                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18493            }
18494        } else {
18495            return mSettings.getInternalVersion();
18496        }
18497    }
18498
18499    private void deleteTempPackageFiles() {
18500        final FilenameFilter filter = new FilenameFilter() {
18501            public boolean accept(File dir, String name) {
18502                return name.startsWith("vmdl") && name.endsWith(".tmp");
18503            }
18504        };
18505        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18506            file.delete();
18507        }
18508    }
18509
18510    @Override
18511    public void deletePackageAsUser(String packageName, int versionCode,
18512            IPackageDeleteObserver observer, int userId, int flags) {
18513        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18514                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18515    }
18516
18517    @Override
18518    public void deletePackageVersioned(VersionedPackage versionedPackage,
18519            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18520        final int callingUid = Binder.getCallingUid();
18521        mContext.enforceCallingOrSelfPermission(
18522                android.Manifest.permission.DELETE_PACKAGES, null);
18523        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18524        Preconditions.checkNotNull(versionedPackage);
18525        Preconditions.checkNotNull(observer);
18526        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18527                PackageManager.VERSION_CODE_HIGHEST,
18528                Integer.MAX_VALUE, "versionCode must be >= -1");
18529
18530        final String packageName = versionedPackage.getPackageName();
18531        final int versionCode = versionedPackage.getVersionCode();
18532        final String internalPackageName;
18533        synchronized (mPackages) {
18534            // Normalize package name to handle renamed packages and static libs
18535            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18536                    versionedPackage.getVersionCode());
18537        }
18538
18539        final int uid = Binder.getCallingUid();
18540        if (!isOrphaned(internalPackageName)
18541                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18542            try {
18543                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18544                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18545                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18546                observer.onUserActionRequired(intent);
18547            } catch (RemoteException re) {
18548            }
18549            return;
18550        }
18551        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18552        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18553        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18554            mContext.enforceCallingOrSelfPermission(
18555                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18556                    "deletePackage for user " + userId);
18557        }
18558
18559        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18560            try {
18561                observer.onPackageDeleted(packageName,
18562                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18563            } catch (RemoteException re) {
18564            }
18565            return;
18566        }
18567
18568        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18569            try {
18570                observer.onPackageDeleted(packageName,
18571                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18572            } catch (RemoteException re) {
18573            }
18574            return;
18575        }
18576
18577        if (DEBUG_REMOVE) {
18578            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18579                    + " deleteAllUsers: " + deleteAllUsers + " version="
18580                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18581                    ? "VERSION_CODE_HIGHEST" : versionCode));
18582        }
18583        // Queue up an async operation since the package deletion may take a little while.
18584        mHandler.post(new Runnable() {
18585            public void run() {
18586                mHandler.removeCallbacks(this);
18587                int returnCode;
18588                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18589                boolean doDeletePackage = true;
18590                if (ps != null) {
18591                    final boolean targetIsInstantApp =
18592                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18593                    doDeletePackage = !targetIsInstantApp
18594                            || canViewInstantApps;
18595                }
18596                if (doDeletePackage) {
18597                    if (!deleteAllUsers) {
18598                        returnCode = deletePackageX(internalPackageName, versionCode,
18599                                userId, deleteFlags);
18600                    } else {
18601                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18602                                internalPackageName, users);
18603                        // If nobody is blocking uninstall, proceed with delete for all users
18604                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18605                            returnCode = deletePackageX(internalPackageName, versionCode,
18606                                    userId, deleteFlags);
18607                        } else {
18608                            // Otherwise uninstall individually for users with blockUninstalls=false
18609                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18610                            for (int userId : users) {
18611                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18612                                    returnCode = deletePackageX(internalPackageName, versionCode,
18613                                            userId, userFlags);
18614                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18615                                        Slog.w(TAG, "Package delete failed for user " + userId
18616                                                + ", returnCode " + returnCode);
18617                                    }
18618                                }
18619                            }
18620                            // The app has only been marked uninstalled for certain users.
18621                            // We still need to report that delete was blocked
18622                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18623                        }
18624                    }
18625                } else {
18626                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18627                }
18628                try {
18629                    observer.onPackageDeleted(packageName, returnCode, null);
18630                } catch (RemoteException e) {
18631                    Log.i(TAG, "Observer no longer exists.");
18632                } //end catch
18633            } //end run
18634        });
18635    }
18636
18637    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18638        if (pkg.staticSharedLibName != null) {
18639            return pkg.manifestPackageName;
18640        }
18641        return pkg.packageName;
18642    }
18643
18644    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18645        // Handle renamed packages
18646        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18647        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18648
18649        // Is this a static library?
18650        SparseArray<SharedLibraryEntry> versionedLib =
18651                mStaticLibsByDeclaringPackage.get(packageName);
18652        if (versionedLib == null || versionedLib.size() <= 0) {
18653            return packageName;
18654        }
18655
18656        // Figure out which lib versions the caller can see
18657        SparseIntArray versionsCallerCanSee = null;
18658        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18659        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18660                && callingAppId != Process.ROOT_UID) {
18661            versionsCallerCanSee = new SparseIntArray();
18662            String libName = versionedLib.valueAt(0).info.getName();
18663            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18664            if (uidPackages != null) {
18665                for (String uidPackage : uidPackages) {
18666                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18667                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18668                    if (libIdx >= 0) {
18669                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18670                        versionsCallerCanSee.append(libVersion, libVersion);
18671                    }
18672                }
18673            }
18674        }
18675
18676        // Caller can see nothing - done
18677        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18678            return packageName;
18679        }
18680
18681        // Find the version the caller can see and the app version code
18682        SharedLibraryEntry highestVersion = null;
18683        final int versionCount = versionedLib.size();
18684        for (int i = 0; i < versionCount; i++) {
18685            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18686            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18687                    libEntry.info.getVersion()) < 0) {
18688                continue;
18689            }
18690            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18691            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18692                if (libVersionCode == versionCode) {
18693                    return libEntry.apk;
18694                }
18695            } else if (highestVersion == null) {
18696                highestVersion = libEntry;
18697            } else if (libVersionCode  > highestVersion.info
18698                    .getDeclaringPackage().getVersionCode()) {
18699                highestVersion = libEntry;
18700            }
18701        }
18702
18703        if (highestVersion != null) {
18704            return highestVersion.apk;
18705        }
18706
18707        return packageName;
18708    }
18709
18710    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18711        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18712              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18713            return true;
18714        }
18715        final int callingUserId = UserHandle.getUserId(callingUid);
18716        // If the caller installed the pkgName, then allow it to silently uninstall.
18717        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18718            return true;
18719        }
18720
18721        // Allow package verifier to silently uninstall.
18722        if (mRequiredVerifierPackage != null &&
18723                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18724            return true;
18725        }
18726
18727        // Allow package uninstaller to silently uninstall.
18728        if (mRequiredUninstallerPackage != null &&
18729                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18730            return true;
18731        }
18732
18733        // Allow storage manager to silently uninstall.
18734        if (mStorageManagerPackage != null &&
18735                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18736            return true;
18737        }
18738
18739        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18740        // uninstall for device owner provisioning.
18741        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18742                == PERMISSION_GRANTED) {
18743            return true;
18744        }
18745
18746        return false;
18747    }
18748
18749    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18750        int[] result = EMPTY_INT_ARRAY;
18751        for (int userId : userIds) {
18752            if (getBlockUninstallForUser(packageName, userId)) {
18753                result = ArrayUtils.appendInt(result, userId);
18754            }
18755        }
18756        return result;
18757    }
18758
18759    @Override
18760    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18761        final int callingUid = Binder.getCallingUid();
18762        if (getInstantAppPackageName(callingUid) != null
18763                && !isCallerSameApp(packageName, callingUid)) {
18764            return false;
18765        }
18766        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18767    }
18768
18769    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18770        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18771                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18772        try {
18773            if (dpm != null) {
18774                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18775                        /* callingUserOnly =*/ false);
18776                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18777                        : deviceOwnerComponentName.getPackageName();
18778                // Does the package contains the device owner?
18779                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18780                // this check is probably not needed, since DO should be registered as a device
18781                // admin on some user too. (Original bug for this: b/17657954)
18782                if (packageName.equals(deviceOwnerPackageName)) {
18783                    return true;
18784                }
18785                // Does it contain a device admin for any user?
18786                int[] users;
18787                if (userId == UserHandle.USER_ALL) {
18788                    users = sUserManager.getUserIds();
18789                } else {
18790                    users = new int[]{userId};
18791                }
18792                for (int i = 0; i < users.length; ++i) {
18793                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18794                        return true;
18795                    }
18796                }
18797            }
18798        } catch (RemoteException e) {
18799        }
18800        return false;
18801    }
18802
18803    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18804        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18805    }
18806
18807    /**
18808     *  This method is an internal method that could be get invoked either
18809     *  to delete an installed package or to clean up a failed installation.
18810     *  After deleting an installed package, a broadcast is sent to notify any
18811     *  listeners that the package has been removed. For cleaning up a failed
18812     *  installation, the broadcast is not necessary since the package's
18813     *  installation wouldn't have sent the initial broadcast either
18814     *  The key steps in deleting a package are
18815     *  deleting the package information in internal structures like mPackages,
18816     *  deleting the packages base directories through installd
18817     *  updating mSettings to reflect current status
18818     *  persisting settings for later use
18819     *  sending a broadcast if necessary
18820     */
18821    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18822        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18823        final boolean res;
18824
18825        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18826                ? UserHandle.USER_ALL : userId;
18827
18828        if (isPackageDeviceAdmin(packageName, removeUser)) {
18829            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18830            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18831        }
18832
18833        PackageSetting uninstalledPs = null;
18834        PackageParser.Package pkg = null;
18835
18836        // for the uninstall-updates case and restricted profiles, remember the per-
18837        // user handle installed state
18838        int[] allUsers;
18839        synchronized (mPackages) {
18840            uninstalledPs = mSettings.mPackages.get(packageName);
18841            if (uninstalledPs == null) {
18842                Slog.w(TAG, "Not removing non-existent package " + packageName);
18843                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18844            }
18845
18846            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18847                    && uninstalledPs.versionCode != versionCode) {
18848                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18849                        + uninstalledPs.versionCode + " != " + versionCode);
18850                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18851            }
18852
18853            // Static shared libs can be declared by any package, so let us not
18854            // allow removing a package if it provides a lib others depend on.
18855            pkg = mPackages.get(packageName);
18856
18857            allUsers = sUserManager.getUserIds();
18858
18859            if (pkg != null && pkg.staticSharedLibName != null) {
18860                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18861                        pkg.staticSharedLibVersion);
18862                if (libEntry != null) {
18863                    for (int currUserId : allUsers) {
18864                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18865                            continue;
18866                        }
18867                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18868                                libEntry.info, 0, currUserId);
18869                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18870                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18871                                    + " hosting lib " + libEntry.info.getName() + " version "
18872                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18873                                    + " for user " + currUserId);
18874                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18875                        }
18876                    }
18877                }
18878            }
18879
18880            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18881        }
18882
18883        final int freezeUser;
18884        if (isUpdatedSystemApp(uninstalledPs)
18885                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18886            // We're downgrading a system app, which will apply to all users, so
18887            // freeze them all during the downgrade
18888            freezeUser = UserHandle.USER_ALL;
18889        } else {
18890            freezeUser = removeUser;
18891        }
18892
18893        synchronized (mInstallLock) {
18894            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18895            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18896                    deleteFlags, "deletePackageX")) {
18897                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18898                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18899            }
18900            synchronized (mPackages) {
18901                if (res) {
18902                    if (pkg != null) {
18903                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18904                    }
18905                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18906                    updateInstantAppInstallerLocked(packageName);
18907                }
18908            }
18909        }
18910
18911        if (res) {
18912            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18913            info.sendPackageRemovedBroadcasts(killApp);
18914            info.sendSystemPackageUpdatedBroadcasts();
18915            info.sendSystemPackageAppearedBroadcasts();
18916        }
18917        // Force a gc here.
18918        Runtime.getRuntime().gc();
18919        // Delete the resources here after sending the broadcast to let
18920        // other processes clean up before deleting resources.
18921        if (info.args != null) {
18922            synchronized (mInstallLock) {
18923                info.args.doPostDeleteLI(true);
18924            }
18925        }
18926
18927        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18928    }
18929
18930    static class PackageRemovedInfo {
18931        final PackageSender packageSender;
18932        String removedPackage;
18933        String installerPackageName;
18934        int uid = -1;
18935        int removedAppId = -1;
18936        int[] origUsers;
18937        int[] removedUsers = null;
18938        int[] broadcastUsers = null;
18939        SparseArray<Integer> installReasons;
18940        boolean isRemovedPackageSystemUpdate = false;
18941        boolean isUpdate;
18942        boolean dataRemoved;
18943        boolean removedForAllUsers;
18944        boolean isStaticSharedLib;
18945        // Clean up resources deleted packages.
18946        InstallArgs args = null;
18947        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18948        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18949
18950        PackageRemovedInfo(PackageSender packageSender) {
18951            this.packageSender = packageSender;
18952        }
18953
18954        void sendPackageRemovedBroadcasts(boolean killApp) {
18955            sendPackageRemovedBroadcastInternal(killApp);
18956            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18957            for (int i = 0; i < childCount; i++) {
18958                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18959                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18960            }
18961        }
18962
18963        void sendSystemPackageUpdatedBroadcasts() {
18964            if (isRemovedPackageSystemUpdate) {
18965                sendSystemPackageUpdatedBroadcastsInternal();
18966                final int childCount = (removedChildPackages != null)
18967                        ? removedChildPackages.size() : 0;
18968                for (int i = 0; i < childCount; i++) {
18969                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18970                    if (childInfo.isRemovedPackageSystemUpdate) {
18971                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18972                    }
18973                }
18974            }
18975        }
18976
18977        void sendSystemPackageAppearedBroadcasts() {
18978            final int packageCount = (appearedChildPackages != null)
18979                    ? appearedChildPackages.size() : 0;
18980            for (int i = 0; i < packageCount; i++) {
18981                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18982                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18983                    true, UserHandle.getAppId(installedInfo.uid),
18984                    installedInfo.newUsers);
18985            }
18986        }
18987
18988        private void sendSystemPackageUpdatedBroadcastsInternal() {
18989            Bundle extras = new Bundle(2);
18990            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18991            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18992            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18993                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18994            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18995                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18996            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18997                null, null, 0, removedPackage, null, null);
18998            if (installerPackageName != null) {
18999                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19000                        removedPackage, extras, 0 /*flags*/,
19001                        installerPackageName, null, null);
19002                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19003                        removedPackage, extras, 0 /*flags*/,
19004                        installerPackageName, null, null);
19005            }
19006        }
19007
19008        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19009            // Don't send static shared library removal broadcasts as these
19010            // libs are visible only the the apps that depend on them an one
19011            // cannot remove the library if it has a dependency.
19012            if (isStaticSharedLib) {
19013                return;
19014            }
19015            Bundle extras = new Bundle(2);
19016            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19017            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19018            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19019            if (isUpdate || isRemovedPackageSystemUpdate) {
19020                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19021            }
19022            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19023            if (removedPackage != null) {
19024                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19025                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19026                if (installerPackageName != null) {
19027                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19028                            removedPackage, extras, 0 /*flags*/,
19029                            installerPackageName, null, broadcastUsers);
19030                }
19031                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19032                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19033                        removedPackage, extras,
19034                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19035                        null, null, broadcastUsers);
19036                }
19037            }
19038            if (removedAppId >= 0) {
19039                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19040                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19041                    null, null, broadcastUsers);
19042            }
19043        }
19044
19045        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19046            removedUsers = userIds;
19047            if (removedUsers == null) {
19048                broadcastUsers = null;
19049                return;
19050            }
19051
19052            broadcastUsers = EMPTY_INT_ARRAY;
19053            for (int i = userIds.length - 1; i >= 0; --i) {
19054                final int userId = userIds[i];
19055                if (deletedPackageSetting.getInstantApp(userId)) {
19056                    continue;
19057                }
19058                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19059            }
19060        }
19061    }
19062
19063    /*
19064     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19065     * flag is not set, the data directory is removed as well.
19066     * make sure this flag is set for partially installed apps. If not its meaningless to
19067     * delete a partially installed application.
19068     */
19069    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19070            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19071        String packageName = ps.name;
19072        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19073        // Retrieve object to delete permissions for shared user later on
19074        final PackageParser.Package deletedPkg;
19075        final PackageSetting deletedPs;
19076        // reader
19077        synchronized (mPackages) {
19078            deletedPkg = mPackages.get(packageName);
19079            deletedPs = mSettings.mPackages.get(packageName);
19080            if (outInfo != null) {
19081                outInfo.removedPackage = packageName;
19082                outInfo.installerPackageName = ps.installerPackageName;
19083                outInfo.isStaticSharedLib = deletedPkg != null
19084                        && deletedPkg.staticSharedLibName != null;
19085                outInfo.populateUsers(deletedPs == null ? null
19086                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19087            }
19088        }
19089
19090        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19091
19092        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19093            final PackageParser.Package resolvedPkg;
19094            if (deletedPkg != null) {
19095                resolvedPkg = deletedPkg;
19096            } else {
19097                // We don't have a parsed package when it lives on an ejected
19098                // adopted storage device, so fake something together
19099                resolvedPkg = new PackageParser.Package(ps.name);
19100                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19101            }
19102            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19103                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19104            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19105            if (outInfo != null) {
19106                outInfo.dataRemoved = true;
19107            }
19108            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19109        }
19110
19111        int removedAppId = -1;
19112
19113        // writer
19114        synchronized (mPackages) {
19115            boolean installedStateChanged = false;
19116            if (deletedPs != null) {
19117                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19118                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19119                    clearDefaultBrowserIfNeeded(packageName);
19120                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19121                    removedAppId = mSettings.removePackageLPw(packageName);
19122                    if (outInfo != null) {
19123                        outInfo.removedAppId = removedAppId;
19124                    }
19125                    updatePermissionsLPw(deletedPs.name, null, 0);
19126                    if (deletedPs.sharedUser != null) {
19127                        // Remove permissions associated with package. Since runtime
19128                        // permissions are per user we have to kill the removed package
19129                        // or packages running under the shared user of the removed
19130                        // package if revoking the permissions requested only by the removed
19131                        // package is successful and this causes a change in gids.
19132                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19133                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19134                                    userId);
19135                            if (userIdToKill == UserHandle.USER_ALL
19136                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19137                                // If gids changed for this user, kill all affected packages.
19138                                mHandler.post(new Runnable() {
19139                                    @Override
19140                                    public void run() {
19141                                        // This has to happen with no lock held.
19142                                        killApplication(deletedPs.name, deletedPs.appId,
19143                                                KILL_APP_REASON_GIDS_CHANGED);
19144                                    }
19145                                });
19146                                break;
19147                            }
19148                        }
19149                    }
19150                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19151                }
19152                // make sure to preserve per-user disabled state if this removal was just
19153                // a downgrade of a system app to the factory package
19154                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19155                    if (DEBUG_REMOVE) {
19156                        Slog.d(TAG, "Propagating install state across downgrade");
19157                    }
19158                    for (int userId : allUserHandles) {
19159                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19160                        if (DEBUG_REMOVE) {
19161                            Slog.d(TAG, "    user " + userId + " => " + installed);
19162                        }
19163                        if (installed != ps.getInstalled(userId)) {
19164                            installedStateChanged = true;
19165                        }
19166                        ps.setInstalled(installed, userId);
19167                    }
19168                }
19169            }
19170            // can downgrade to reader
19171            if (writeSettings) {
19172                // Save settings now
19173                mSettings.writeLPr();
19174            }
19175            if (installedStateChanged) {
19176                mSettings.writeKernelMappingLPr(ps);
19177            }
19178        }
19179        if (removedAppId != -1) {
19180            // A user ID was deleted here. Go through all users and remove it
19181            // from KeyStore.
19182            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19183        }
19184    }
19185
19186    static boolean locationIsPrivileged(File path) {
19187        try {
19188            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19189                    .getCanonicalPath();
19190            return path.getCanonicalPath().startsWith(privilegedAppDir);
19191        } catch (IOException e) {
19192            Slog.e(TAG, "Unable to access code path " + path);
19193        }
19194        return false;
19195    }
19196
19197    /*
19198     * Tries to delete system package.
19199     */
19200    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19201            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19202            boolean writeSettings) {
19203        if (deletedPs.parentPackageName != null) {
19204            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19205            return false;
19206        }
19207
19208        final boolean applyUserRestrictions
19209                = (allUserHandles != null) && (outInfo.origUsers != null);
19210        final PackageSetting disabledPs;
19211        // Confirm if the system package has been updated
19212        // An updated system app can be deleted. This will also have to restore
19213        // the system pkg from system partition
19214        // reader
19215        synchronized (mPackages) {
19216            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19217        }
19218
19219        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19220                + " disabledPs=" + disabledPs);
19221
19222        if (disabledPs == null) {
19223            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19224            return false;
19225        } else if (DEBUG_REMOVE) {
19226            Slog.d(TAG, "Deleting system pkg from data partition");
19227        }
19228
19229        if (DEBUG_REMOVE) {
19230            if (applyUserRestrictions) {
19231                Slog.d(TAG, "Remembering install states:");
19232                for (int userId : allUserHandles) {
19233                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19234                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19235                }
19236            }
19237        }
19238
19239        // Delete the updated package
19240        outInfo.isRemovedPackageSystemUpdate = true;
19241        if (outInfo.removedChildPackages != null) {
19242            final int childCount = (deletedPs.childPackageNames != null)
19243                    ? deletedPs.childPackageNames.size() : 0;
19244            for (int i = 0; i < childCount; i++) {
19245                String childPackageName = deletedPs.childPackageNames.get(i);
19246                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19247                        .contains(childPackageName)) {
19248                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19249                            childPackageName);
19250                    if (childInfo != null) {
19251                        childInfo.isRemovedPackageSystemUpdate = true;
19252                    }
19253                }
19254            }
19255        }
19256
19257        if (disabledPs.versionCode < deletedPs.versionCode) {
19258            // Delete data for downgrades
19259            flags &= ~PackageManager.DELETE_KEEP_DATA;
19260        } else {
19261            // Preserve data by setting flag
19262            flags |= PackageManager.DELETE_KEEP_DATA;
19263        }
19264
19265        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19266                outInfo, writeSettings, disabledPs.pkg);
19267        if (!ret) {
19268            return false;
19269        }
19270
19271        // writer
19272        synchronized (mPackages) {
19273            // Reinstate the old system package
19274            enableSystemPackageLPw(disabledPs.pkg);
19275            // Remove any native libraries from the upgraded package.
19276            removeNativeBinariesLI(deletedPs);
19277        }
19278
19279        // Install the system package
19280        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19281        int parseFlags = mDefParseFlags
19282                | PackageParser.PARSE_MUST_BE_APK
19283                | PackageParser.PARSE_IS_SYSTEM
19284                | PackageParser.PARSE_IS_SYSTEM_DIR;
19285        if (locationIsPrivileged(disabledPs.codePath)) {
19286            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19287        }
19288
19289        final PackageParser.Package newPkg;
19290        try {
19291            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19292                0 /* currentTime */, null);
19293        } catch (PackageManagerException e) {
19294            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19295                    + e.getMessage());
19296            return false;
19297        }
19298
19299        try {
19300            // update shared libraries for the newly re-installed system package
19301            updateSharedLibrariesLPr(newPkg, null);
19302        } catch (PackageManagerException e) {
19303            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19304        }
19305
19306        prepareAppDataAfterInstallLIF(newPkg);
19307
19308        // writer
19309        synchronized (mPackages) {
19310            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19311
19312            // Propagate the permissions state as we do not want to drop on the floor
19313            // runtime permissions. The update permissions method below will take
19314            // care of removing obsolete permissions and grant install permissions.
19315            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19316            updatePermissionsLPw(newPkg.packageName, newPkg,
19317                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19318
19319            if (applyUserRestrictions) {
19320                boolean installedStateChanged = false;
19321                if (DEBUG_REMOVE) {
19322                    Slog.d(TAG, "Propagating install state across reinstall");
19323                }
19324                for (int userId : allUserHandles) {
19325                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19326                    if (DEBUG_REMOVE) {
19327                        Slog.d(TAG, "    user " + userId + " => " + installed);
19328                    }
19329                    if (installed != ps.getInstalled(userId)) {
19330                        installedStateChanged = true;
19331                    }
19332                    ps.setInstalled(installed, userId);
19333
19334                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19335                }
19336                // Regardless of writeSettings we need to ensure that this restriction
19337                // state propagation is persisted
19338                mSettings.writeAllUsersPackageRestrictionsLPr();
19339                if (installedStateChanged) {
19340                    mSettings.writeKernelMappingLPr(ps);
19341                }
19342            }
19343            // can downgrade to reader here
19344            if (writeSettings) {
19345                mSettings.writeLPr();
19346            }
19347        }
19348        return true;
19349    }
19350
19351    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19352            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19353            PackageRemovedInfo outInfo, boolean writeSettings,
19354            PackageParser.Package replacingPackage) {
19355        synchronized (mPackages) {
19356            if (outInfo != null) {
19357                outInfo.uid = ps.appId;
19358            }
19359
19360            if (outInfo != null && outInfo.removedChildPackages != null) {
19361                final int childCount = (ps.childPackageNames != null)
19362                        ? ps.childPackageNames.size() : 0;
19363                for (int i = 0; i < childCount; i++) {
19364                    String childPackageName = ps.childPackageNames.get(i);
19365                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19366                    if (childPs == null) {
19367                        return false;
19368                    }
19369                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19370                            childPackageName);
19371                    if (childInfo != null) {
19372                        childInfo.uid = childPs.appId;
19373                    }
19374                }
19375            }
19376        }
19377
19378        // Delete package data from internal structures and also remove data if flag is set
19379        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19380
19381        // Delete the child packages data
19382        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19383        for (int i = 0; i < childCount; i++) {
19384            PackageSetting childPs;
19385            synchronized (mPackages) {
19386                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19387            }
19388            if (childPs != null) {
19389                PackageRemovedInfo childOutInfo = (outInfo != null
19390                        && outInfo.removedChildPackages != null)
19391                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19392                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19393                        && (replacingPackage != null
19394                        && !replacingPackage.hasChildPackage(childPs.name))
19395                        ? flags & ~DELETE_KEEP_DATA : flags;
19396                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19397                        deleteFlags, writeSettings);
19398            }
19399        }
19400
19401        // Delete application code and resources only for parent packages
19402        if (ps.parentPackageName == null) {
19403            if (deleteCodeAndResources && (outInfo != null)) {
19404                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19405                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19406                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19407            }
19408        }
19409
19410        return true;
19411    }
19412
19413    @Override
19414    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19415            int userId) {
19416        mContext.enforceCallingOrSelfPermission(
19417                android.Manifest.permission.DELETE_PACKAGES, null);
19418        synchronized (mPackages) {
19419            // Cannot block uninstall of static shared libs as they are
19420            // considered a part of the using app (emulating static linking).
19421            // Also static libs are installed always on internal storage.
19422            PackageParser.Package pkg = mPackages.get(packageName);
19423            if (pkg != null && pkg.staticSharedLibName != null) {
19424                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19425                        + " providing static shared library: " + pkg.staticSharedLibName);
19426                return false;
19427            }
19428            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19429            mSettings.writePackageRestrictionsLPr(userId);
19430        }
19431        return true;
19432    }
19433
19434    @Override
19435    public boolean getBlockUninstallForUser(String packageName, int userId) {
19436        synchronized (mPackages) {
19437            final PackageSetting ps = mSettings.mPackages.get(packageName);
19438            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19439                return true;
19440            }
19441            return mSettings.getBlockUninstallLPr(userId, packageName);
19442        }
19443    }
19444
19445    @Override
19446    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19447        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19448        synchronized (mPackages) {
19449            PackageSetting ps = mSettings.mPackages.get(packageName);
19450            if (ps == null) {
19451                Log.w(TAG, "Package doesn't exist: " + packageName);
19452                return false;
19453            }
19454            if (systemUserApp) {
19455                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19456            } else {
19457                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19458            }
19459            mSettings.writeLPr();
19460        }
19461        return true;
19462    }
19463
19464    /*
19465     * This method handles package deletion in general
19466     */
19467    private boolean deletePackageLIF(String packageName, UserHandle user,
19468            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19469            PackageRemovedInfo outInfo, boolean writeSettings,
19470            PackageParser.Package replacingPackage) {
19471        if (packageName == null) {
19472            Slog.w(TAG, "Attempt to delete null packageName.");
19473            return false;
19474        }
19475
19476        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19477
19478        PackageSetting ps;
19479        synchronized (mPackages) {
19480            ps = mSettings.mPackages.get(packageName);
19481            if (ps == null) {
19482                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19483                return false;
19484            }
19485
19486            if (ps.parentPackageName != null && (!isSystemApp(ps)
19487                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19488                if (DEBUG_REMOVE) {
19489                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19490                            + ((user == null) ? UserHandle.USER_ALL : user));
19491                }
19492                final int removedUserId = (user != null) ? user.getIdentifier()
19493                        : UserHandle.USER_ALL;
19494                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19495                    return false;
19496                }
19497                markPackageUninstalledForUserLPw(ps, user);
19498                scheduleWritePackageRestrictionsLocked(user);
19499                return true;
19500            }
19501        }
19502
19503        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19504                && user.getIdentifier() != UserHandle.USER_ALL)) {
19505            // The caller is asking that the package only be deleted for a single
19506            // user.  To do this, we just mark its uninstalled state and delete
19507            // its data. If this is a system app, we only allow this to happen if
19508            // they have set the special DELETE_SYSTEM_APP which requests different
19509            // semantics than normal for uninstalling system apps.
19510            markPackageUninstalledForUserLPw(ps, user);
19511
19512            if (!isSystemApp(ps)) {
19513                // Do not uninstall the APK if an app should be cached
19514                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19515                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19516                    // Other user still have this package installed, so all
19517                    // we need to do is clear this user's data and save that
19518                    // it is uninstalled.
19519                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19520                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19521                        return false;
19522                    }
19523                    scheduleWritePackageRestrictionsLocked(user);
19524                    return true;
19525                } else {
19526                    // We need to set it back to 'installed' so the uninstall
19527                    // broadcasts will be sent correctly.
19528                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19529                    ps.setInstalled(true, user.getIdentifier());
19530                    mSettings.writeKernelMappingLPr(ps);
19531                }
19532            } else {
19533                // This is a system app, so we assume that the
19534                // other users still have this package installed, so all
19535                // we need to do is clear this user's data and save that
19536                // it is uninstalled.
19537                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19538                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19539                    return false;
19540                }
19541                scheduleWritePackageRestrictionsLocked(user);
19542                return true;
19543            }
19544        }
19545
19546        // If we are deleting a composite package for all users, keep track
19547        // of result for each child.
19548        if (ps.childPackageNames != null && outInfo != null) {
19549            synchronized (mPackages) {
19550                final int childCount = ps.childPackageNames.size();
19551                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19552                for (int i = 0; i < childCount; i++) {
19553                    String childPackageName = ps.childPackageNames.get(i);
19554                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19555                    childInfo.removedPackage = childPackageName;
19556                    childInfo.installerPackageName = ps.installerPackageName;
19557                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19558                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19559                    if (childPs != null) {
19560                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19561                    }
19562                }
19563            }
19564        }
19565
19566        boolean ret = false;
19567        if (isSystemApp(ps)) {
19568            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19569            // When an updated system application is deleted we delete the existing resources
19570            // as well and fall back to existing code in system partition
19571            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19572        } else {
19573            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19574            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19575                    outInfo, writeSettings, replacingPackage);
19576        }
19577
19578        // Take a note whether we deleted the package for all users
19579        if (outInfo != null) {
19580            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19581            if (outInfo.removedChildPackages != null) {
19582                synchronized (mPackages) {
19583                    final int childCount = outInfo.removedChildPackages.size();
19584                    for (int i = 0; i < childCount; i++) {
19585                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19586                        if (childInfo != null) {
19587                            childInfo.removedForAllUsers = mPackages.get(
19588                                    childInfo.removedPackage) == null;
19589                        }
19590                    }
19591                }
19592            }
19593            // If we uninstalled an update to a system app there may be some
19594            // child packages that appeared as they are declared in the system
19595            // app but were not declared in the update.
19596            if (isSystemApp(ps)) {
19597                synchronized (mPackages) {
19598                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19599                    final int childCount = (updatedPs.childPackageNames != null)
19600                            ? updatedPs.childPackageNames.size() : 0;
19601                    for (int i = 0; i < childCount; i++) {
19602                        String childPackageName = updatedPs.childPackageNames.get(i);
19603                        if (outInfo.removedChildPackages == null
19604                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19605                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19606                            if (childPs == null) {
19607                                continue;
19608                            }
19609                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19610                            installRes.name = childPackageName;
19611                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19612                            installRes.pkg = mPackages.get(childPackageName);
19613                            installRes.uid = childPs.pkg.applicationInfo.uid;
19614                            if (outInfo.appearedChildPackages == null) {
19615                                outInfo.appearedChildPackages = new ArrayMap<>();
19616                            }
19617                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19618                        }
19619                    }
19620                }
19621            }
19622        }
19623
19624        return ret;
19625    }
19626
19627    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19628        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19629                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19630        for (int nextUserId : userIds) {
19631            if (DEBUG_REMOVE) {
19632                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19633            }
19634            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19635                    false /*installed*/,
19636                    true /*stopped*/,
19637                    true /*notLaunched*/,
19638                    false /*hidden*/,
19639                    false /*suspended*/,
19640                    false /*instantApp*/,
19641                    null /*lastDisableAppCaller*/,
19642                    null /*enabledComponents*/,
19643                    null /*disabledComponents*/,
19644                    ps.readUserState(nextUserId).domainVerificationStatus,
19645                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19646        }
19647        mSettings.writeKernelMappingLPr(ps);
19648    }
19649
19650    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19651            PackageRemovedInfo outInfo) {
19652        final PackageParser.Package pkg;
19653        synchronized (mPackages) {
19654            pkg = mPackages.get(ps.name);
19655        }
19656
19657        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19658                : new int[] {userId};
19659        for (int nextUserId : userIds) {
19660            if (DEBUG_REMOVE) {
19661                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19662                        + nextUserId);
19663            }
19664
19665            destroyAppDataLIF(pkg, userId,
19666                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19667            destroyAppProfilesLIF(pkg, userId);
19668            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19669            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19670            schedulePackageCleaning(ps.name, nextUserId, false);
19671            synchronized (mPackages) {
19672                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19673                    scheduleWritePackageRestrictionsLocked(nextUserId);
19674                }
19675                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19676            }
19677        }
19678
19679        if (outInfo != null) {
19680            outInfo.removedPackage = ps.name;
19681            outInfo.installerPackageName = ps.installerPackageName;
19682            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19683            outInfo.removedAppId = ps.appId;
19684            outInfo.removedUsers = userIds;
19685            outInfo.broadcastUsers = userIds;
19686        }
19687
19688        return true;
19689    }
19690
19691    private final class ClearStorageConnection implements ServiceConnection {
19692        IMediaContainerService mContainerService;
19693
19694        @Override
19695        public void onServiceConnected(ComponentName name, IBinder service) {
19696            synchronized (this) {
19697                mContainerService = IMediaContainerService.Stub
19698                        .asInterface(Binder.allowBlocking(service));
19699                notifyAll();
19700            }
19701        }
19702
19703        @Override
19704        public void onServiceDisconnected(ComponentName name) {
19705        }
19706    }
19707
19708    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19709        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19710
19711        final boolean mounted;
19712        if (Environment.isExternalStorageEmulated()) {
19713            mounted = true;
19714        } else {
19715            final String status = Environment.getExternalStorageState();
19716
19717            mounted = status.equals(Environment.MEDIA_MOUNTED)
19718                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19719        }
19720
19721        if (!mounted) {
19722            return;
19723        }
19724
19725        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19726        int[] users;
19727        if (userId == UserHandle.USER_ALL) {
19728            users = sUserManager.getUserIds();
19729        } else {
19730            users = new int[] { userId };
19731        }
19732        final ClearStorageConnection conn = new ClearStorageConnection();
19733        if (mContext.bindServiceAsUser(
19734                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19735            try {
19736                for (int curUser : users) {
19737                    long timeout = SystemClock.uptimeMillis() + 5000;
19738                    synchronized (conn) {
19739                        long now;
19740                        while (conn.mContainerService == null &&
19741                                (now = SystemClock.uptimeMillis()) < timeout) {
19742                            try {
19743                                conn.wait(timeout - now);
19744                            } catch (InterruptedException e) {
19745                            }
19746                        }
19747                    }
19748                    if (conn.mContainerService == null) {
19749                        return;
19750                    }
19751
19752                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19753                    clearDirectory(conn.mContainerService,
19754                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19755                    if (allData) {
19756                        clearDirectory(conn.mContainerService,
19757                                userEnv.buildExternalStorageAppDataDirs(packageName));
19758                        clearDirectory(conn.mContainerService,
19759                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19760                    }
19761                }
19762            } finally {
19763                mContext.unbindService(conn);
19764            }
19765        }
19766    }
19767
19768    @Override
19769    public void clearApplicationProfileData(String packageName) {
19770        enforceSystemOrRoot("Only the system can clear all profile data");
19771
19772        final PackageParser.Package pkg;
19773        synchronized (mPackages) {
19774            pkg = mPackages.get(packageName);
19775        }
19776
19777        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19778            synchronized (mInstallLock) {
19779                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19780            }
19781        }
19782    }
19783
19784    @Override
19785    public void clearApplicationUserData(final String packageName,
19786            final IPackageDataObserver observer, final int userId) {
19787        mContext.enforceCallingOrSelfPermission(
19788                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19789
19790        final int callingUid = Binder.getCallingUid();
19791        enforceCrossUserPermission(callingUid, userId,
19792                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19793
19794        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19795        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19796            return;
19797        }
19798        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19799            throw new SecurityException("Cannot clear data for a protected package: "
19800                    + packageName);
19801        }
19802        // Queue up an async operation since the package deletion may take a little while.
19803        mHandler.post(new Runnable() {
19804            public void run() {
19805                mHandler.removeCallbacks(this);
19806                final boolean succeeded;
19807                try (PackageFreezer freezer = freezePackage(packageName,
19808                        "clearApplicationUserData")) {
19809                    synchronized (mInstallLock) {
19810                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19811                    }
19812                    clearExternalStorageDataSync(packageName, userId, true);
19813                    synchronized (mPackages) {
19814                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19815                                packageName, userId);
19816                    }
19817                }
19818                if (succeeded) {
19819                    // invoke DeviceStorageMonitor's update method to clear any notifications
19820                    DeviceStorageMonitorInternal dsm = LocalServices
19821                            .getService(DeviceStorageMonitorInternal.class);
19822                    if (dsm != null) {
19823                        dsm.checkMemory();
19824                    }
19825                }
19826                if(observer != null) {
19827                    try {
19828                        observer.onRemoveCompleted(packageName, succeeded);
19829                    } catch (RemoteException e) {
19830                        Log.i(TAG, "Observer no longer exists.");
19831                    }
19832                } //end if observer
19833            } //end run
19834        });
19835    }
19836
19837    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19838        if (packageName == null) {
19839            Slog.w(TAG, "Attempt to delete null packageName.");
19840            return false;
19841        }
19842
19843        // Try finding details about the requested package
19844        PackageParser.Package pkg;
19845        synchronized (mPackages) {
19846            pkg = mPackages.get(packageName);
19847            if (pkg == null) {
19848                final PackageSetting ps = mSettings.mPackages.get(packageName);
19849                if (ps != null) {
19850                    pkg = ps.pkg;
19851                }
19852            }
19853
19854            if (pkg == null) {
19855                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19856                return false;
19857            }
19858
19859            PackageSetting ps = (PackageSetting) pkg.mExtras;
19860            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19861        }
19862
19863        clearAppDataLIF(pkg, userId,
19864                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19865
19866        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19867        removeKeystoreDataIfNeeded(userId, appId);
19868
19869        UserManagerInternal umInternal = getUserManagerInternal();
19870        final int flags;
19871        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19872            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19873        } else if (umInternal.isUserRunning(userId)) {
19874            flags = StorageManager.FLAG_STORAGE_DE;
19875        } else {
19876            flags = 0;
19877        }
19878        prepareAppDataContentsLIF(pkg, userId, flags);
19879
19880        return true;
19881    }
19882
19883    /**
19884     * Reverts user permission state changes (permissions and flags) in
19885     * all packages for a given user.
19886     *
19887     * @param userId The device user for which to do a reset.
19888     */
19889    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19890        final int packageCount = mPackages.size();
19891        for (int i = 0; i < packageCount; i++) {
19892            PackageParser.Package pkg = mPackages.valueAt(i);
19893            PackageSetting ps = (PackageSetting) pkg.mExtras;
19894            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19895        }
19896    }
19897
19898    private void resetNetworkPolicies(int userId) {
19899        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19900    }
19901
19902    /**
19903     * Reverts user permission state changes (permissions and flags).
19904     *
19905     * @param ps The package for which to reset.
19906     * @param userId The device user for which to do a reset.
19907     */
19908    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19909            final PackageSetting ps, final int userId) {
19910        if (ps.pkg == null) {
19911            return;
19912        }
19913
19914        // These are flags that can change base on user actions.
19915        final int userSettableMask = FLAG_PERMISSION_USER_SET
19916                | FLAG_PERMISSION_USER_FIXED
19917                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19918                | FLAG_PERMISSION_REVIEW_REQUIRED;
19919
19920        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19921                | FLAG_PERMISSION_POLICY_FIXED;
19922
19923        boolean writeInstallPermissions = false;
19924        boolean writeRuntimePermissions = false;
19925
19926        final int permissionCount = ps.pkg.requestedPermissions.size();
19927        for (int i = 0; i < permissionCount; i++) {
19928            String permission = ps.pkg.requestedPermissions.get(i);
19929
19930            BasePermission bp = mSettings.mPermissions.get(permission);
19931            if (bp == null) {
19932                continue;
19933            }
19934
19935            // If shared user we just reset the state to which only this app contributed.
19936            if (ps.sharedUser != null) {
19937                boolean used = false;
19938                final int packageCount = ps.sharedUser.packages.size();
19939                for (int j = 0; j < packageCount; j++) {
19940                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19941                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19942                            && pkg.pkg.requestedPermissions.contains(permission)) {
19943                        used = true;
19944                        break;
19945                    }
19946                }
19947                if (used) {
19948                    continue;
19949                }
19950            }
19951
19952            PermissionsState permissionsState = ps.getPermissionsState();
19953
19954            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19955
19956            // Always clear the user settable flags.
19957            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19958                    bp.name) != null;
19959            // If permission review is enabled and this is a legacy app, mark the
19960            // permission as requiring a review as this is the initial state.
19961            int flags = 0;
19962            if (mPermissionReviewRequired
19963                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19964                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19965            }
19966            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19967                if (hasInstallState) {
19968                    writeInstallPermissions = true;
19969                } else {
19970                    writeRuntimePermissions = true;
19971                }
19972            }
19973
19974            // Below is only runtime permission handling.
19975            if (!bp.isRuntime()) {
19976                continue;
19977            }
19978
19979            // Never clobber system or policy.
19980            if ((oldFlags & policyOrSystemFlags) != 0) {
19981                continue;
19982            }
19983
19984            // If this permission was granted by default, make sure it is.
19985            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19986                if (permissionsState.grantRuntimePermission(bp, userId)
19987                        != PERMISSION_OPERATION_FAILURE) {
19988                    writeRuntimePermissions = true;
19989                }
19990            // If permission review is enabled the permissions for a legacy apps
19991            // are represented as constantly granted runtime ones, so don't revoke.
19992            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19993                // Otherwise, reset the permission.
19994                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19995                switch (revokeResult) {
19996                    case PERMISSION_OPERATION_SUCCESS:
19997                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19998                        writeRuntimePermissions = true;
19999                        final int appId = ps.appId;
20000                        mHandler.post(new Runnable() {
20001                            @Override
20002                            public void run() {
20003                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20004                            }
20005                        });
20006                    } break;
20007                }
20008            }
20009        }
20010
20011        // Synchronously write as we are taking permissions away.
20012        if (writeRuntimePermissions) {
20013            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20014        }
20015
20016        // Synchronously write as we are taking permissions away.
20017        if (writeInstallPermissions) {
20018            mSettings.writeLPr();
20019        }
20020    }
20021
20022    /**
20023     * Remove entries from the keystore daemon. Will only remove it if the
20024     * {@code appId} is valid.
20025     */
20026    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20027        if (appId < 0) {
20028            return;
20029        }
20030
20031        final KeyStore keyStore = KeyStore.getInstance();
20032        if (keyStore != null) {
20033            if (userId == UserHandle.USER_ALL) {
20034                for (final int individual : sUserManager.getUserIds()) {
20035                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20036                }
20037            } else {
20038                keyStore.clearUid(UserHandle.getUid(userId, appId));
20039            }
20040        } else {
20041            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20042        }
20043    }
20044
20045    @Override
20046    public void deleteApplicationCacheFiles(final String packageName,
20047            final IPackageDataObserver observer) {
20048        final int userId = UserHandle.getCallingUserId();
20049        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20050    }
20051
20052    @Override
20053    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20054            final IPackageDataObserver observer) {
20055        final int callingUid = Binder.getCallingUid();
20056        mContext.enforceCallingOrSelfPermission(
20057                android.Manifest.permission.DELETE_CACHE_FILES, null);
20058        enforceCrossUserPermission(callingUid, userId,
20059                /* requireFullPermission= */ true, /* checkShell= */ false,
20060                "delete application cache files");
20061        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20062                android.Manifest.permission.ACCESS_INSTANT_APPS);
20063
20064        final PackageParser.Package pkg;
20065        synchronized (mPackages) {
20066            pkg = mPackages.get(packageName);
20067        }
20068
20069        // Queue up an async operation since the package deletion may take a little while.
20070        mHandler.post(new Runnable() {
20071            public void run() {
20072                final PackageSetting ps = (PackageSetting) pkg.mExtras;
20073                boolean doClearData = true;
20074                if (ps != null) {
20075                    final boolean targetIsInstantApp =
20076                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20077                    doClearData = !targetIsInstantApp
20078                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20079                }
20080                if (doClearData) {
20081                    synchronized (mInstallLock) {
20082                        final int flags = StorageManager.FLAG_STORAGE_DE
20083                                | StorageManager.FLAG_STORAGE_CE;
20084                        // We're only clearing cache files, so we don't care if the
20085                        // app is unfrozen and still able to run
20086                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20087                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20088                    }
20089                    clearExternalStorageDataSync(packageName, userId, false);
20090                }
20091                if (observer != null) {
20092                    try {
20093                        observer.onRemoveCompleted(packageName, true);
20094                    } catch (RemoteException e) {
20095                        Log.i(TAG, "Observer no longer exists.");
20096                    }
20097                }
20098            }
20099        });
20100    }
20101
20102    @Override
20103    public void getPackageSizeInfo(final String packageName, int userHandle,
20104            final IPackageStatsObserver observer) {
20105        throw new UnsupportedOperationException(
20106                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20107    }
20108
20109    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20110        final PackageSetting ps;
20111        synchronized (mPackages) {
20112            ps = mSettings.mPackages.get(packageName);
20113            if (ps == null) {
20114                Slog.w(TAG, "Failed to find settings for " + packageName);
20115                return false;
20116            }
20117        }
20118
20119        final String[] packageNames = { packageName };
20120        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20121        final String[] codePaths = { ps.codePathString };
20122
20123        try {
20124            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20125                    ps.appId, ceDataInodes, codePaths, stats);
20126
20127            // For now, ignore code size of packages on system partition
20128            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20129                stats.codeSize = 0;
20130            }
20131
20132            // External clients expect these to be tracked separately
20133            stats.dataSize -= stats.cacheSize;
20134
20135        } catch (InstallerException e) {
20136            Slog.w(TAG, String.valueOf(e));
20137            return false;
20138        }
20139
20140        return true;
20141    }
20142
20143    private int getUidTargetSdkVersionLockedLPr(int uid) {
20144        Object obj = mSettings.getUserIdLPr(uid);
20145        if (obj instanceof SharedUserSetting) {
20146            final SharedUserSetting sus = (SharedUserSetting) obj;
20147            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20148            final Iterator<PackageSetting> it = sus.packages.iterator();
20149            while (it.hasNext()) {
20150                final PackageSetting ps = it.next();
20151                if (ps.pkg != null) {
20152                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20153                    if (v < vers) vers = v;
20154                }
20155            }
20156            return vers;
20157        } else if (obj instanceof PackageSetting) {
20158            final PackageSetting ps = (PackageSetting) obj;
20159            if (ps.pkg != null) {
20160                return ps.pkg.applicationInfo.targetSdkVersion;
20161            }
20162        }
20163        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20164    }
20165
20166    @Override
20167    public void addPreferredActivity(IntentFilter filter, int match,
20168            ComponentName[] set, ComponentName activity, int userId) {
20169        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20170                "Adding preferred");
20171    }
20172
20173    private void addPreferredActivityInternal(IntentFilter filter, int match,
20174            ComponentName[] set, ComponentName activity, boolean always, int userId,
20175            String opname) {
20176        // writer
20177        int callingUid = Binder.getCallingUid();
20178        enforceCrossUserPermission(callingUid, userId,
20179                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20180        if (filter.countActions() == 0) {
20181            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20182            return;
20183        }
20184        synchronized (mPackages) {
20185            if (mContext.checkCallingOrSelfPermission(
20186                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20187                    != PackageManager.PERMISSION_GRANTED) {
20188                if (getUidTargetSdkVersionLockedLPr(callingUid)
20189                        < Build.VERSION_CODES.FROYO) {
20190                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20191                            + callingUid);
20192                    return;
20193                }
20194                mContext.enforceCallingOrSelfPermission(
20195                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20196            }
20197
20198            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20199            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20200                    + userId + ":");
20201            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20202            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20203            scheduleWritePackageRestrictionsLocked(userId);
20204            postPreferredActivityChangedBroadcast(userId);
20205        }
20206    }
20207
20208    private void postPreferredActivityChangedBroadcast(int userId) {
20209        mHandler.post(() -> {
20210            final IActivityManager am = ActivityManager.getService();
20211            if (am == null) {
20212                return;
20213            }
20214
20215            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20216            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20217            try {
20218                am.broadcastIntent(null, intent, null, null,
20219                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20220                        null, false, false, userId);
20221            } catch (RemoteException e) {
20222            }
20223        });
20224    }
20225
20226    @Override
20227    public void replacePreferredActivity(IntentFilter filter, int match,
20228            ComponentName[] set, ComponentName activity, int userId) {
20229        if (filter.countActions() != 1) {
20230            throw new IllegalArgumentException(
20231                    "replacePreferredActivity expects filter to have only 1 action.");
20232        }
20233        if (filter.countDataAuthorities() != 0
20234                || filter.countDataPaths() != 0
20235                || filter.countDataSchemes() > 1
20236                || filter.countDataTypes() != 0) {
20237            throw new IllegalArgumentException(
20238                    "replacePreferredActivity expects filter to have no data authorities, " +
20239                    "paths, or types; and at most one scheme.");
20240        }
20241
20242        final int callingUid = Binder.getCallingUid();
20243        enforceCrossUserPermission(callingUid, userId,
20244                true /* requireFullPermission */, false /* checkShell */,
20245                "replace preferred activity");
20246        synchronized (mPackages) {
20247            if (mContext.checkCallingOrSelfPermission(
20248                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20249                    != PackageManager.PERMISSION_GRANTED) {
20250                if (getUidTargetSdkVersionLockedLPr(callingUid)
20251                        < Build.VERSION_CODES.FROYO) {
20252                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20253                            + Binder.getCallingUid());
20254                    return;
20255                }
20256                mContext.enforceCallingOrSelfPermission(
20257                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20258            }
20259
20260            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20261            if (pir != null) {
20262                // Get all of the existing entries that exactly match this filter.
20263                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20264                if (existing != null && existing.size() == 1) {
20265                    PreferredActivity cur = existing.get(0);
20266                    if (DEBUG_PREFERRED) {
20267                        Slog.i(TAG, "Checking replace of preferred:");
20268                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20269                        if (!cur.mPref.mAlways) {
20270                            Slog.i(TAG, "  -- CUR; not mAlways!");
20271                        } else {
20272                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20273                            Slog.i(TAG, "  -- CUR: mSet="
20274                                    + Arrays.toString(cur.mPref.mSetComponents));
20275                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20276                            Slog.i(TAG, "  -- NEW: mMatch="
20277                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20278                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20279                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20280                        }
20281                    }
20282                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20283                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20284                            && cur.mPref.sameSet(set)) {
20285                        // Setting the preferred activity to what it happens to be already
20286                        if (DEBUG_PREFERRED) {
20287                            Slog.i(TAG, "Replacing with same preferred activity "
20288                                    + cur.mPref.mShortComponent + " for user "
20289                                    + userId + ":");
20290                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20291                        }
20292                        return;
20293                    }
20294                }
20295
20296                if (existing != null) {
20297                    if (DEBUG_PREFERRED) {
20298                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20299                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20300                    }
20301                    for (int i = 0; i < existing.size(); i++) {
20302                        PreferredActivity pa = existing.get(i);
20303                        if (DEBUG_PREFERRED) {
20304                            Slog.i(TAG, "Removing existing preferred activity "
20305                                    + pa.mPref.mComponent + ":");
20306                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20307                        }
20308                        pir.removeFilter(pa);
20309                    }
20310                }
20311            }
20312            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20313                    "Replacing preferred");
20314        }
20315    }
20316
20317    @Override
20318    public void clearPackagePreferredActivities(String packageName) {
20319        final int callingUid = Binder.getCallingUid();
20320        if (getInstantAppPackageName(callingUid) != null) {
20321            return;
20322        }
20323        // writer
20324        synchronized (mPackages) {
20325            PackageParser.Package pkg = mPackages.get(packageName);
20326            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20327                if (mContext.checkCallingOrSelfPermission(
20328                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20329                        != PackageManager.PERMISSION_GRANTED) {
20330                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20331                            < Build.VERSION_CODES.FROYO) {
20332                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20333                                + callingUid);
20334                        return;
20335                    }
20336                    mContext.enforceCallingOrSelfPermission(
20337                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20338                }
20339            }
20340            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20341            if (ps != null
20342                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20343                return;
20344            }
20345            int user = UserHandle.getCallingUserId();
20346            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20347                scheduleWritePackageRestrictionsLocked(user);
20348            }
20349        }
20350    }
20351
20352    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20353    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20354        ArrayList<PreferredActivity> removed = null;
20355        boolean changed = false;
20356        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20357            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20358            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20359            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20360                continue;
20361            }
20362            Iterator<PreferredActivity> it = pir.filterIterator();
20363            while (it.hasNext()) {
20364                PreferredActivity pa = it.next();
20365                // Mark entry for removal only if it matches the package name
20366                // and the entry is of type "always".
20367                if (packageName == null ||
20368                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20369                                && pa.mPref.mAlways)) {
20370                    if (removed == null) {
20371                        removed = new ArrayList<PreferredActivity>();
20372                    }
20373                    removed.add(pa);
20374                }
20375            }
20376            if (removed != null) {
20377                for (int j=0; j<removed.size(); j++) {
20378                    PreferredActivity pa = removed.get(j);
20379                    pir.removeFilter(pa);
20380                }
20381                changed = true;
20382            }
20383        }
20384        if (changed) {
20385            postPreferredActivityChangedBroadcast(userId);
20386        }
20387        return changed;
20388    }
20389
20390    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20391    private void clearIntentFilterVerificationsLPw(int userId) {
20392        final int packageCount = mPackages.size();
20393        for (int i = 0; i < packageCount; i++) {
20394            PackageParser.Package pkg = mPackages.valueAt(i);
20395            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20396        }
20397    }
20398
20399    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20400    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20401        if (userId == UserHandle.USER_ALL) {
20402            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20403                    sUserManager.getUserIds())) {
20404                for (int oneUserId : sUserManager.getUserIds()) {
20405                    scheduleWritePackageRestrictionsLocked(oneUserId);
20406                }
20407            }
20408        } else {
20409            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20410                scheduleWritePackageRestrictionsLocked(userId);
20411            }
20412        }
20413    }
20414
20415    /** Clears state for all users, and touches intent filter verification policy */
20416    void clearDefaultBrowserIfNeeded(String packageName) {
20417        for (int oneUserId : sUserManager.getUserIds()) {
20418            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20419        }
20420    }
20421
20422    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20423        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20424        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20425            if (packageName.equals(defaultBrowserPackageName)) {
20426                setDefaultBrowserPackageName(null, userId);
20427            }
20428        }
20429    }
20430
20431    @Override
20432    public void resetApplicationPreferences(int userId) {
20433        mContext.enforceCallingOrSelfPermission(
20434                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20435        final long identity = Binder.clearCallingIdentity();
20436        // writer
20437        try {
20438            synchronized (mPackages) {
20439                clearPackagePreferredActivitiesLPw(null, userId);
20440                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20441                // TODO: We have to reset the default SMS and Phone. This requires
20442                // significant refactoring to keep all default apps in the package
20443                // manager (cleaner but more work) or have the services provide
20444                // callbacks to the package manager to request a default app reset.
20445                applyFactoryDefaultBrowserLPw(userId);
20446                clearIntentFilterVerificationsLPw(userId);
20447                primeDomainVerificationsLPw(userId);
20448                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20449                scheduleWritePackageRestrictionsLocked(userId);
20450            }
20451            resetNetworkPolicies(userId);
20452        } finally {
20453            Binder.restoreCallingIdentity(identity);
20454        }
20455    }
20456
20457    @Override
20458    public int getPreferredActivities(List<IntentFilter> outFilters,
20459            List<ComponentName> outActivities, String packageName) {
20460        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20461            return 0;
20462        }
20463        int num = 0;
20464        final int userId = UserHandle.getCallingUserId();
20465        // reader
20466        synchronized (mPackages) {
20467            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20468            if (pir != null) {
20469                final Iterator<PreferredActivity> it = pir.filterIterator();
20470                while (it.hasNext()) {
20471                    final PreferredActivity pa = it.next();
20472                    if (packageName == null
20473                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20474                                    && pa.mPref.mAlways)) {
20475                        if (outFilters != null) {
20476                            outFilters.add(new IntentFilter(pa));
20477                        }
20478                        if (outActivities != null) {
20479                            outActivities.add(pa.mPref.mComponent);
20480                        }
20481                    }
20482                }
20483            }
20484        }
20485
20486        return num;
20487    }
20488
20489    @Override
20490    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20491            int userId) {
20492        int callingUid = Binder.getCallingUid();
20493        if (callingUid != Process.SYSTEM_UID) {
20494            throw new SecurityException(
20495                    "addPersistentPreferredActivity can only be run by the system");
20496        }
20497        if (filter.countActions() == 0) {
20498            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20499            return;
20500        }
20501        synchronized (mPackages) {
20502            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20503                    ":");
20504            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20505            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20506                    new PersistentPreferredActivity(filter, activity));
20507            scheduleWritePackageRestrictionsLocked(userId);
20508            postPreferredActivityChangedBroadcast(userId);
20509        }
20510    }
20511
20512    @Override
20513    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20514        int callingUid = Binder.getCallingUid();
20515        if (callingUid != Process.SYSTEM_UID) {
20516            throw new SecurityException(
20517                    "clearPackagePersistentPreferredActivities can only be run by the system");
20518        }
20519        ArrayList<PersistentPreferredActivity> removed = null;
20520        boolean changed = false;
20521        synchronized (mPackages) {
20522            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20523                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20524                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20525                        .valueAt(i);
20526                if (userId != thisUserId) {
20527                    continue;
20528                }
20529                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20530                while (it.hasNext()) {
20531                    PersistentPreferredActivity ppa = it.next();
20532                    // Mark entry for removal only if it matches the package name.
20533                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20534                        if (removed == null) {
20535                            removed = new ArrayList<PersistentPreferredActivity>();
20536                        }
20537                        removed.add(ppa);
20538                    }
20539                }
20540                if (removed != null) {
20541                    for (int j=0; j<removed.size(); j++) {
20542                        PersistentPreferredActivity ppa = removed.get(j);
20543                        ppir.removeFilter(ppa);
20544                    }
20545                    changed = true;
20546                }
20547            }
20548
20549            if (changed) {
20550                scheduleWritePackageRestrictionsLocked(userId);
20551                postPreferredActivityChangedBroadcast(userId);
20552            }
20553        }
20554    }
20555
20556    /**
20557     * Common machinery for picking apart a restored XML blob and passing
20558     * it to a caller-supplied functor to be applied to the running system.
20559     */
20560    private void restoreFromXml(XmlPullParser parser, int userId,
20561            String expectedStartTag, BlobXmlRestorer functor)
20562            throws IOException, XmlPullParserException {
20563        int type;
20564        while ((type = parser.next()) != XmlPullParser.START_TAG
20565                && type != XmlPullParser.END_DOCUMENT) {
20566        }
20567        if (type != XmlPullParser.START_TAG) {
20568            // oops didn't find a start tag?!
20569            if (DEBUG_BACKUP) {
20570                Slog.e(TAG, "Didn't find start tag during restore");
20571            }
20572            return;
20573        }
20574Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20575        // this is supposed to be TAG_PREFERRED_BACKUP
20576        if (!expectedStartTag.equals(parser.getName())) {
20577            if (DEBUG_BACKUP) {
20578                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20579            }
20580            return;
20581        }
20582
20583        // skip interfering stuff, then we're aligned with the backing implementation
20584        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20585Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20586        functor.apply(parser, userId);
20587    }
20588
20589    private interface BlobXmlRestorer {
20590        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20591    }
20592
20593    /**
20594     * Non-Binder method, support for the backup/restore mechanism: write the
20595     * full set of preferred activities in its canonical XML format.  Returns the
20596     * XML output as a byte array, or null if there is none.
20597     */
20598    @Override
20599    public byte[] getPreferredActivityBackup(int userId) {
20600        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20601            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20602        }
20603
20604        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20605        try {
20606            final XmlSerializer serializer = new FastXmlSerializer();
20607            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20608            serializer.startDocument(null, true);
20609            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20610
20611            synchronized (mPackages) {
20612                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20613            }
20614
20615            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20616            serializer.endDocument();
20617            serializer.flush();
20618        } catch (Exception e) {
20619            if (DEBUG_BACKUP) {
20620                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20621            }
20622            return null;
20623        }
20624
20625        return dataStream.toByteArray();
20626    }
20627
20628    @Override
20629    public void restorePreferredActivities(byte[] backup, int userId) {
20630        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20631            throw new SecurityException("Only the system may call restorePreferredActivities()");
20632        }
20633
20634        try {
20635            final XmlPullParser parser = Xml.newPullParser();
20636            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20637            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20638                    new BlobXmlRestorer() {
20639                        @Override
20640                        public void apply(XmlPullParser parser, int userId)
20641                                throws XmlPullParserException, IOException {
20642                            synchronized (mPackages) {
20643                                mSettings.readPreferredActivitiesLPw(parser, userId);
20644                            }
20645                        }
20646                    } );
20647        } catch (Exception e) {
20648            if (DEBUG_BACKUP) {
20649                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20650            }
20651        }
20652    }
20653
20654    /**
20655     * Non-Binder method, support for the backup/restore mechanism: write the
20656     * default browser (etc) settings in its canonical XML format.  Returns the default
20657     * browser XML representation as a byte array, or null if there is none.
20658     */
20659    @Override
20660    public byte[] getDefaultAppsBackup(int userId) {
20661        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20662            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20663        }
20664
20665        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20666        try {
20667            final XmlSerializer serializer = new FastXmlSerializer();
20668            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20669            serializer.startDocument(null, true);
20670            serializer.startTag(null, TAG_DEFAULT_APPS);
20671
20672            synchronized (mPackages) {
20673                mSettings.writeDefaultAppsLPr(serializer, userId);
20674            }
20675
20676            serializer.endTag(null, TAG_DEFAULT_APPS);
20677            serializer.endDocument();
20678            serializer.flush();
20679        } catch (Exception e) {
20680            if (DEBUG_BACKUP) {
20681                Slog.e(TAG, "Unable to write default apps for backup", e);
20682            }
20683            return null;
20684        }
20685
20686        return dataStream.toByteArray();
20687    }
20688
20689    @Override
20690    public void restoreDefaultApps(byte[] backup, int userId) {
20691        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20692            throw new SecurityException("Only the system may call restoreDefaultApps()");
20693        }
20694
20695        try {
20696            final XmlPullParser parser = Xml.newPullParser();
20697            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20698            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20699                    new BlobXmlRestorer() {
20700                        @Override
20701                        public void apply(XmlPullParser parser, int userId)
20702                                throws XmlPullParserException, IOException {
20703                            synchronized (mPackages) {
20704                                mSettings.readDefaultAppsLPw(parser, userId);
20705                            }
20706                        }
20707                    } );
20708        } catch (Exception e) {
20709            if (DEBUG_BACKUP) {
20710                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20711            }
20712        }
20713    }
20714
20715    @Override
20716    public byte[] getIntentFilterVerificationBackup(int userId) {
20717        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20718            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20719        }
20720
20721        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20722        try {
20723            final XmlSerializer serializer = new FastXmlSerializer();
20724            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20725            serializer.startDocument(null, true);
20726            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20727
20728            synchronized (mPackages) {
20729                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20730            }
20731
20732            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20733            serializer.endDocument();
20734            serializer.flush();
20735        } catch (Exception e) {
20736            if (DEBUG_BACKUP) {
20737                Slog.e(TAG, "Unable to write default apps for backup", e);
20738            }
20739            return null;
20740        }
20741
20742        return dataStream.toByteArray();
20743    }
20744
20745    @Override
20746    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20747        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20748            throw new SecurityException("Only the system may call restorePreferredActivities()");
20749        }
20750
20751        try {
20752            final XmlPullParser parser = Xml.newPullParser();
20753            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20754            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20755                    new BlobXmlRestorer() {
20756                        @Override
20757                        public void apply(XmlPullParser parser, int userId)
20758                                throws XmlPullParserException, IOException {
20759                            synchronized (mPackages) {
20760                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20761                                mSettings.writeLPr();
20762                            }
20763                        }
20764                    } );
20765        } catch (Exception e) {
20766            if (DEBUG_BACKUP) {
20767                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20768            }
20769        }
20770    }
20771
20772    @Override
20773    public byte[] getPermissionGrantBackup(int userId) {
20774        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20775            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20776        }
20777
20778        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20779        try {
20780            final XmlSerializer serializer = new FastXmlSerializer();
20781            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20782            serializer.startDocument(null, true);
20783            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20784
20785            synchronized (mPackages) {
20786                serializeRuntimePermissionGrantsLPr(serializer, userId);
20787            }
20788
20789            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20790            serializer.endDocument();
20791            serializer.flush();
20792        } catch (Exception e) {
20793            if (DEBUG_BACKUP) {
20794                Slog.e(TAG, "Unable to write default apps for backup", e);
20795            }
20796            return null;
20797        }
20798
20799        return dataStream.toByteArray();
20800    }
20801
20802    @Override
20803    public void restorePermissionGrants(byte[] backup, int userId) {
20804        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20805            throw new SecurityException("Only the system may call restorePermissionGrants()");
20806        }
20807
20808        try {
20809            final XmlPullParser parser = Xml.newPullParser();
20810            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20811            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20812                    new BlobXmlRestorer() {
20813                        @Override
20814                        public void apply(XmlPullParser parser, int userId)
20815                                throws XmlPullParserException, IOException {
20816                            synchronized (mPackages) {
20817                                processRestoredPermissionGrantsLPr(parser, userId);
20818                            }
20819                        }
20820                    } );
20821        } catch (Exception e) {
20822            if (DEBUG_BACKUP) {
20823                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20824            }
20825        }
20826    }
20827
20828    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20829            throws IOException {
20830        serializer.startTag(null, TAG_ALL_GRANTS);
20831
20832        final int N = mSettings.mPackages.size();
20833        for (int i = 0; i < N; i++) {
20834            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20835            boolean pkgGrantsKnown = false;
20836
20837            PermissionsState packagePerms = ps.getPermissionsState();
20838
20839            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20840                final int grantFlags = state.getFlags();
20841                // only look at grants that are not system/policy fixed
20842                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20843                    final boolean isGranted = state.isGranted();
20844                    // And only back up the user-twiddled state bits
20845                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20846                        final String packageName = mSettings.mPackages.keyAt(i);
20847                        if (!pkgGrantsKnown) {
20848                            serializer.startTag(null, TAG_GRANT);
20849                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20850                            pkgGrantsKnown = true;
20851                        }
20852
20853                        final boolean userSet =
20854                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20855                        final boolean userFixed =
20856                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20857                        final boolean revoke =
20858                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20859
20860                        serializer.startTag(null, TAG_PERMISSION);
20861                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20862                        if (isGranted) {
20863                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20864                        }
20865                        if (userSet) {
20866                            serializer.attribute(null, ATTR_USER_SET, "true");
20867                        }
20868                        if (userFixed) {
20869                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20870                        }
20871                        if (revoke) {
20872                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20873                        }
20874                        serializer.endTag(null, TAG_PERMISSION);
20875                    }
20876                }
20877            }
20878
20879            if (pkgGrantsKnown) {
20880                serializer.endTag(null, TAG_GRANT);
20881            }
20882        }
20883
20884        serializer.endTag(null, TAG_ALL_GRANTS);
20885    }
20886
20887    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20888            throws XmlPullParserException, IOException {
20889        String pkgName = null;
20890        int outerDepth = parser.getDepth();
20891        int type;
20892        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20893                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20894            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20895                continue;
20896            }
20897
20898            final String tagName = parser.getName();
20899            if (tagName.equals(TAG_GRANT)) {
20900                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20901                if (DEBUG_BACKUP) {
20902                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20903                }
20904            } else if (tagName.equals(TAG_PERMISSION)) {
20905
20906                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20907                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20908
20909                int newFlagSet = 0;
20910                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20911                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20912                }
20913                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20914                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20915                }
20916                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20917                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20918                }
20919                if (DEBUG_BACKUP) {
20920                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20921                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20922                }
20923                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20924                if (ps != null) {
20925                    // Already installed so we apply the grant immediately
20926                    if (DEBUG_BACKUP) {
20927                        Slog.v(TAG, "        + already installed; applying");
20928                    }
20929                    PermissionsState perms = ps.getPermissionsState();
20930                    BasePermission bp = mSettings.mPermissions.get(permName);
20931                    if (bp != null) {
20932                        if (isGranted) {
20933                            perms.grantRuntimePermission(bp, userId);
20934                        }
20935                        if (newFlagSet != 0) {
20936                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20937                        }
20938                    }
20939                } else {
20940                    // Need to wait for post-restore install to apply the grant
20941                    if (DEBUG_BACKUP) {
20942                        Slog.v(TAG, "        - not yet installed; saving for later");
20943                    }
20944                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20945                            isGranted, newFlagSet, userId);
20946                }
20947            } else {
20948                PackageManagerService.reportSettingsProblem(Log.WARN,
20949                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20950                XmlUtils.skipCurrentTag(parser);
20951            }
20952        }
20953
20954        scheduleWriteSettingsLocked();
20955        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20956    }
20957
20958    @Override
20959    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20960            int sourceUserId, int targetUserId, int flags) {
20961        mContext.enforceCallingOrSelfPermission(
20962                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20963        int callingUid = Binder.getCallingUid();
20964        enforceOwnerRights(ownerPackage, callingUid);
20965        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20966        if (intentFilter.countActions() == 0) {
20967            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20968            return;
20969        }
20970        synchronized (mPackages) {
20971            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20972                    ownerPackage, targetUserId, flags);
20973            CrossProfileIntentResolver resolver =
20974                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20975            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20976            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20977            if (existing != null) {
20978                int size = existing.size();
20979                for (int i = 0; i < size; i++) {
20980                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20981                        return;
20982                    }
20983                }
20984            }
20985            resolver.addFilter(newFilter);
20986            scheduleWritePackageRestrictionsLocked(sourceUserId);
20987        }
20988    }
20989
20990    @Override
20991    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20992        mContext.enforceCallingOrSelfPermission(
20993                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20994        final int callingUid = Binder.getCallingUid();
20995        enforceOwnerRights(ownerPackage, callingUid);
20996        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20997        synchronized (mPackages) {
20998            CrossProfileIntentResolver resolver =
20999                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21000            ArraySet<CrossProfileIntentFilter> set =
21001                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21002            for (CrossProfileIntentFilter filter : set) {
21003                if (filter.getOwnerPackage().equals(ownerPackage)) {
21004                    resolver.removeFilter(filter);
21005                }
21006            }
21007            scheduleWritePackageRestrictionsLocked(sourceUserId);
21008        }
21009    }
21010
21011    // Enforcing that callingUid is owning pkg on userId
21012    private void enforceOwnerRights(String pkg, int callingUid) {
21013        // The system owns everything.
21014        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21015            return;
21016        }
21017        final int callingUserId = UserHandle.getUserId(callingUid);
21018        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21019        if (pi == null) {
21020            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21021                    + callingUserId);
21022        }
21023        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21024            throw new SecurityException("Calling uid " + callingUid
21025                    + " does not own package " + pkg);
21026        }
21027    }
21028
21029    @Override
21030    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21031        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21032            return null;
21033        }
21034        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21035    }
21036
21037    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21038        UserManagerService ums = UserManagerService.getInstance();
21039        if (ums != null) {
21040            final UserInfo parent = ums.getProfileParent(userId);
21041            final int launcherUid = (parent != null) ? parent.id : userId;
21042            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21043            if (launcherComponent != null) {
21044                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21045                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21046                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21047                        .setPackage(launcherComponent.getPackageName());
21048                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21049            }
21050        }
21051    }
21052
21053    /**
21054     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21055     * then reports the most likely home activity or null if there are more than one.
21056     */
21057    private ComponentName getDefaultHomeActivity(int userId) {
21058        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21059        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21060        if (cn != null) {
21061            return cn;
21062        }
21063
21064        // Find the launcher with the highest priority and return that component if there are no
21065        // other home activity with the same priority.
21066        int lastPriority = Integer.MIN_VALUE;
21067        ComponentName lastComponent = null;
21068        final int size = allHomeCandidates.size();
21069        for (int i = 0; i < size; i++) {
21070            final ResolveInfo ri = allHomeCandidates.get(i);
21071            if (ri.priority > lastPriority) {
21072                lastComponent = ri.activityInfo.getComponentName();
21073                lastPriority = ri.priority;
21074            } else if (ri.priority == lastPriority) {
21075                // Two components found with same priority.
21076                lastComponent = null;
21077            }
21078        }
21079        return lastComponent;
21080    }
21081
21082    private Intent getHomeIntent() {
21083        Intent intent = new Intent(Intent.ACTION_MAIN);
21084        intent.addCategory(Intent.CATEGORY_HOME);
21085        intent.addCategory(Intent.CATEGORY_DEFAULT);
21086        return intent;
21087    }
21088
21089    private IntentFilter getHomeFilter() {
21090        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21091        filter.addCategory(Intent.CATEGORY_HOME);
21092        filter.addCategory(Intent.CATEGORY_DEFAULT);
21093        return filter;
21094    }
21095
21096    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21097            int userId) {
21098        Intent intent  = getHomeIntent();
21099        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21100                PackageManager.GET_META_DATA, userId);
21101        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21102                true, false, false, userId);
21103
21104        allHomeCandidates.clear();
21105        if (list != null) {
21106            for (ResolveInfo ri : list) {
21107                allHomeCandidates.add(ri);
21108            }
21109        }
21110        return (preferred == null || preferred.activityInfo == null)
21111                ? null
21112                : new ComponentName(preferred.activityInfo.packageName,
21113                        preferred.activityInfo.name);
21114    }
21115
21116    @Override
21117    public void setHomeActivity(ComponentName comp, int userId) {
21118        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21119            return;
21120        }
21121        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21122        getHomeActivitiesAsUser(homeActivities, userId);
21123
21124        boolean found = false;
21125
21126        final int size = homeActivities.size();
21127        final ComponentName[] set = new ComponentName[size];
21128        for (int i = 0; i < size; i++) {
21129            final ResolveInfo candidate = homeActivities.get(i);
21130            final ActivityInfo info = candidate.activityInfo;
21131            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21132            set[i] = activityName;
21133            if (!found && activityName.equals(comp)) {
21134                found = true;
21135            }
21136        }
21137        if (!found) {
21138            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21139                    + userId);
21140        }
21141        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21142                set, comp, userId);
21143    }
21144
21145    private @Nullable String getSetupWizardPackageName() {
21146        final Intent intent = new Intent(Intent.ACTION_MAIN);
21147        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21148
21149        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21150                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21151                        | MATCH_DISABLED_COMPONENTS,
21152                UserHandle.myUserId());
21153        if (matches.size() == 1) {
21154            return matches.get(0).getComponentInfo().packageName;
21155        } else {
21156            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21157                    + ": matches=" + matches);
21158            return null;
21159        }
21160    }
21161
21162    private @Nullable String getStorageManagerPackageName() {
21163        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21164
21165        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21166                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21167                        | MATCH_DISABLED_COMPONENTS,
21168                UserHandle.myUserId());
21169        if (matches.size() == 1) {
21170            return matches.get(0).getComponentInfo().packageName;
21171        } else {
21172            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21173                    + matches.size() + ": matches=" + matches);
21174            return null;
21175        }
21176    }
21177
21178    @Override
21179    public void setApplicationEnabledSetting(String appPackageName,
21180            int newState, int flags, int userId, String callingPackage) {
21181        if (!sUserManager.exists(userId)) return;
21182        if (callingPackage == null) {
21183            callingPackage = Integer.toString(Binder.getCallingUid());
21184        }
21185        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21186    }
21187
21188    @Override
21189    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21190        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21191        synchronized (mPackages) {
21192            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21193            if (pkgSetting != null) {
21194                pkgSetting.setUpdateAvailable(updateAvailable);
21195            }
21196        }
21197    }
21198
21199    @Override
21200    public void setComponentEnabledSetting(ComponentName componentName,
21201            int newState, int flags, int userId) {
21202        if (!sUserManager.exists(userId)) return;
21203        setEnabledSetting(componentName.getPackageName(),
21204                componentName.getClassName(), newState, flags, userId, null);
21205    }
21206
21207    private void setEnabledSetting(final String packageName, String className, int newState,
21208            final int flags, int userId, String callingPackage) {
21209        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21210              || newState == COMPONENT_ENABLED_STATE_ENABLED
21211              || newState == COMPONENT_ENABLED_STATE_DISABLED
21212              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21213              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21214            throw new IllegalArgumentException("Invalid new component state: "
21215                    + newState);
21216        }
21217        PackageSetting pkgSetting;
21218        final int callingUid = Binder.getCallingUid();
21219        final int permission;
21220        if (callingUid == Process.SYSTEM_UID) {
21221            permission = PackageManager.PERMISSION_GRANTED;
21222        } else {
21223            permission = mContext.checkCallingOrSelfPermission(
21224                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21225        }
21226        enforceCrossUserPermission(callingUid, userId,
21227                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21228        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21229        boolean sendNow = false;
21230        boolean isApp = (className == null);
21231        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21232        String componentName = isApp ? packageName : className;
21233        int packageUid = -1;
21234        ArrayList<String> components;
21235
21236        // reader
21237        synchronized (mPackages) {
21238            pkgSetting = mSettings.mPackages.get(packageName);
21239            if (pkgSetting == null) {
21240                if (!isCallerInstantApp) {
21241                    if (className == null) {
21242                        throw new IllegalArgumentException("Unknown package: " + packageName);
21243                    }
21244                    throw new IllegalArgumentException(
21245                            "Unknown component: " + packageName + "/" + className);
21246                } else {
21247                    // throw SecurityException to prevent leaking package information
21248                    throw new SecurityException(
21249                            "Attempt to change component state; "
21250                            + "pid=" + Binder.getCallingPid()
21251                            + ", uid=" + callingUid
21252                            + (className == null
21253                                    ? ", package=" + packageName
21254                                    : ", component=" + packageName + "/" + className));
21255                }
21256            }
21257        }
21258
21259        // Limit who can change which apps
21260        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21261            // Don't allow apps that don't have permission to modify other apps
21262            if (!allowedByPermission
21263                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21264                throw new SecurityException(
21265                        "Attempt to change component state; "
21266                        + "pid=" + Binder.getCallingPid()
21267                        + ", uid=" + callingUid
21268                        + (className == null
21269                                ? ", package=" + packageName
21270                                : ", component=" + packageName + "/" + className));
21271            }
21272            // Don't allow changing protected packages.
21273            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21274                throw new SecurityException("Cannot disable a protected package: " + packageName);
21275            }
21276        }
21277
21278        synchronized (mPackages) {
21279            if (callingUid == Process.SHELL_UID
21280                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21281                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21282                // unless it is a test package.
21283                int oldState = pkgSetting.getEnabled(userId);
21284                if (className == null
21285                    &&
21286                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21287                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21288                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21289                    &&
21290                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21291                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21292                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21293                    // ok
21294                } else {
21295                    throw new SecurityException(
21296                            "Shell cannot change component state for " + packageName + "/"
21297                            + className + " to " + newState);
21298                }
21299            }
21300            if (className == null) {
21301                // We're dealing with an application/package level state change
21302                if (pkgSetting.getEnabled(userId) == newState) {
21303                    // Nothing to do
21304                    return;
21305                }
21306                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21307                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21308                    // Don't care about who enables an app.
21309                    callingPackage = null;
21310                }
21311                pkgSetting.setEnabled(newState, userId, callingPackage);
21312                // pkgSetting.pkg.mSetEnabled = newState;
21313            } else {
21314                // We're dealing with a component level state change
21315                // First, verify that this is a valid class name.
21316                PackageParser.Package pkg = pkgSetting.pkg;
21317                if (pkg == null || !pkg.hasComponentClassName(className)) {
21318                    if (pkg != null &&
21319                            pkg.applicationInfo.targetSdkVersion >=
21320                                    Build.VERSION_CODES.JELLY_BEAN) {
21321                        throw new IllegalArgumentException("Component class " + className
21322                                + " does not exist in " + packageName);
21323                    } else {
21324                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21325                                + className + " does not exist in " + packageName);
21326                    }
21327                }
21328                switch (newState) {
21329                case COMPONENT_ENABLED_STATE_ENABLED:
21330                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21331                        return;
21332                    }
21333                    break;
21334                case COMPONENT_ENABLED_STATE_DISABLED:
21335                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21336                        return;
21337                    }
21338                    break;
21339                case COMPONENT_ENABLED_STATE_DEFAULT:
21340                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21341                        return;
21342                    }
21343                    break;
21344                default:
21345                    Slog.e(TAG, "Invalid new component state: " + newState);
21346                    return;
21347                }
21348            }
21349            scheduleWritePackageRestrictionsLocked(userId);
21350            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21351            final long callingId = Binder.clearCallingIdentity();
21352            try {
21353                updateInstantAppInstallerLocked(packageName);
21354            } finally {
21355                Binder.restoreCallingIdentity(callingId);
21356            }
21357            components = mPendingBroadcasts.get(userId, packageName);
21358            final boolean newPackage = components == null;
21359            if (newPackage) {
21360                components = new ArrayList<String>();
21361            }
21362            if (!components.contains(componentName)) {
21363                components.add(componentName);
21364            }
21365            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21366                sendNow = true;
21367                // Purge entry from pending broadcast list if another one exists already
21368                // since we are sending one right away.
21369                mPendingBroadcasts.remove(userId, packageName);
21370            } else {
21371                if (newPackage) {
21372                    mPendingBroadcasts.put(userId, packageName, components);
21373                }
21374                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21375                    // Schedule a message
21376                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21377                }
21378            }
21379        }
21380
21381        long callingId = Binder.clearCallingIdentity();
21382        try {
21383            if (sendNow) {
21384                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21385                sendPackageChangedBroadcast(packageName,
21386                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21387            }
21388        } finally {
21389            Binder.restoreCallingIdentity(callingId);
21390        }
21391    }
21392
21393    @Override
21394    public void flushPackageRestrictionsAsUser(int userId) {
21395        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21396            return;
21397        }
21398        if (!sUserManager.exists(userId)) {
21399            return;
21400        }
21401        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21402                false /* checkShell */, "flushPackageRestrictions");
21403        synchronized (mPackages) {
21404            mSettings.writePackageRestrictionsLPr(userId);
21405            mDirtyUsers.remove(userId);
21406            if (mDirtyUsers.isEmpty()) {
21407                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21408            }
21409        }
21410    }
21411
21412    private void sendPackageChangedBroadcast(String packageName,
21413            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21414        if (DEBUG_INSTALL)
21415            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21416                    + componentNames);
21417        Bundle extras = new Bundle(4);
21418        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21419        String nameList[] = new String[componentNames.size()];
21420        componentNames.toArray(nameList);
21421        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21422        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21423        extras.putInt(Intent.EXTRA_UID, packageUid);
21424        // If this is not reporting a change of the overall package, then only send it
21425        // to registered receivers.  We don't want to launch a swath of apps for every
21426        // little component state change.
21427        final int flags = !componentNames.contains(packageName)
21428                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21429        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21430                new int[] {UserHandle.getUserId(packageUid)});
21431    }
21432
21433    @Override
21434    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21435        if (!sUserManager.exists(userId)) return;
21436        final int callingUid = Binder.getCallingUid();
21437        if (getInstantAppPackageName(callingUid) != null) {
21438            return;
21439        }
21440        final int permission = mContext.checkCallingOrSelfPermission(
21441                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21442        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21443        enforceCrossUserPermission(callingUid, userId,
21444                true /* requireFullPermission */, true /* checkShell */, "stop package");
21445        // writer
21446        synchronized (mPackages) {
21447            final PackageSetting ps = mSettings.mPackages.get(packageName);
21448            if (!filterAppAccessLPr(ps, callingUid, userId)
21449                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21450                            allowedByPermission, callingUid, userId)) {
21451                scheduleWritePackageRestrictionsLocked(userId);
21452            }
21453        }
21454    }
21455
21456    @Override
21457    public String getInstallerPackageName(String packageName) {
21458        final int callingUid = Binder.getCallingUid();
21459        if (getInstantAppPackageName(callingUid) != null) {
21460            return null;
21461        }
21462        // reader
21463        synchronized (mPackages) {
21464            final PackageSetting ps = mSettings.mPackages.get(packageName);
21465            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21466                return null;
21467            }
21468            return mSettings.getInstallerPackageNameLPr(packageName);
21469        }
21470    }
21471
21472    public boolean isOrphaned(String packageName) {
21473        // reader
21474        synchronized (mPackages) {
21475            return mSettings.isOrphaned(packageName);
21476        }
21477    }
21478
21479    @Override
21480    public int getApplicationEnabledSetting(String packageName, int userId) {
21481        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21482        int callingUid = Binder.getCallingUid();
21483        enforceCrossUserPermission(callingUid, userId,
21484                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21485        // reader
21486        synchronized (mPackages) {
21487            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21488                return COMPONENT_ENABLED_STATE_DISABLED;
21489            }
21490            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21491        }
21492    }
21493
21494    @Override
21495    public int getComponentEnabledSetting(ComponentName component, int userId) {
21496        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21497        int callingUid = Binder.getCallingUid();
21498        enforceCrossUserPermission(callingUid, userId,
21499                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21500        synchronized (mPackages) {
21501            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21502                    component, TYPE_UNKNOWN, userId)) {
21503                return COMPONENT_ENABLED_STATE_DISABLED;
21504            }
21505            return mSettings.getComponentEnabledSettingLPr(component, userId);
21506        }
21507    }
21508
21509    @Override
21510    public void enterSafeMode() {
21511        enforceSystemOrRoot("Only the system can request entering safe mode");
21512
21513        if (!mSystemReady) {
21514            mSafeMode = true;
21515        }
21516    }
21517
21518    @Override
21519    public void systemReady() {
21520        enforceSystemOrRoot("Only the system can claim the system is ready");
21521
21522        mSystemReady = true;
21523        final ContentResolver resolver = mContext.getContentResolver();
21524        ContentObserver co = new ContentObserver(mHandler) {
21525            @Override
21526            public void onChange(boolean selfChange) {
21527                mEphemeralAppsDisabled =
21528                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21529                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21530            }
21531        };
21532        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21533                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21534                false, co, UserHandle.USER_SYSTEM);
21535        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21536                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21537        co.onChange(true);
21538
21539        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21540        // disabled after already being started.
21541        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21542                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21543
21544        // Read the compatibilty setting when the system is ready.
21545        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21546                mContext.getContentResolver(),
21547                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21548        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21549        if (DEBUG_SETTINGS) {
21550            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21551        }
21552
21553        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21554
21555        synchronized (mPackages) {
21556            // Verify that all of the preferred activity components actually
21557            // exist.  It is possible for applications to be updated and at
21558            // that point remove a previously declared activity component that
21559            // had been set as a preferred activity.  We try to clean this up
21560            // the next time we encounter that preferred activity, but it is
21561            // possible for the user flow to never be able to return to that
21562            // situation so here we do a sanity check to make sure we haven't
21563            // left any junk around.
21564            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21565            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21566                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21567                removed.clear();
21568                for (PreferredActivity pa : pir.filterSet()) {
21569                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21570                        removed.add(pa);
21571                    }
21572                }
21573                if (removed.size() > 0) {
21574                    for (int r=0; r<removed.size(); r++) {
21575                        PreferredActivity pa = removed.get(r);
21576                        Slog.w(TAG, "Removing dangling preferred activity: "
21577                                + pa.mPref.mComponent);
21578                        pir.removeFilter(pa);
21579                    }
21580                    mSettings.writePackageRestrictionsLPr(
21581                            mSettings.mPreferredActivities.keyAt(i));
21582                }
21583            }
21584
21585            for (int userId : UserManagerService.getInstance().getUserIds()) {
21586                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21587                    grantPermissionsUserIds = ArrayUtils.appendInt(
21588                            grantPermissionsUserIds, userId);
21589                }
21590            }
21591        }
21592        sUserManager.systemReady();
21593
21594        // If we upgraded grant all default permissions before kicking off.
21595        for (int userId : grantPermissionsUserIds) {
21596            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21597        }
21598
21599        // If we did not grant default permissions, we preload from this the
21600        // default permission exceptions lazily to ensure we don't hit the
21601        // disk on a new user creation.
21602        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21603            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21604        }
21605
21606        // Kick off any messages waiting for system ready
21607        if (mPostSystemReadyMessages != null) {
21608            for (Message msg : mPostSystemReadyMessages) {
21609                msg.sendToTarget();
21610            }
21611            mPostSystemReadyMessages = null;
21612        }
21613
21614        // Watch for external volumes that come and go over time
21615        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21616        storage.registerListener(mStorageListener);
21617
21618        mInstallerService.systemReady();
21619        mPackageDexOptimizer.systemReady();
21620
21621        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21622                StorageManagerInternal.class);
21623        StorageManagerInternal.addExternalStoragePolicy(
21624                new StorageManagerInternal.ExternalStorageMountPolicy() {
21625            @Override
21626            public int getMountMode(int uid, String packageName) {
21627                if (Process.isIsolated(uid)) {
21628                    return Zygote.MOUNT_EXTERNAL_NONE;
21629                }
21630                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21631                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21632                }
21633                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21634                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21635                }
21636                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21637                    return Zygote.MOUNT_EXTERNAL_READ;
21638                }
21639                return Zygote.MOUNT_EXTERNAL_WRITE;
21640            }
21641
21642            @Override
21643            public boolean hasExternalStorage(int uid, String packageName) {
21644                return true;
21645            }
21646        });
21647
21648        // Now that we're mostly running, clean up stale users and apps
21649        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21650        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21651
21652        if (mPrivappPermissionsViolations != null) {
21653            Slog.wtf(TAG,"Signature|privileged permissions not in "
21654                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21655            mPrivappPermissionsViolations = null;
21656        }
21657    }
21658
21659    public void waitForAppDataPrepared() {
21660        if (mPrepareAppDataFuture == null) {
21661            return;
21662        }
21663        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21664        mPrepareAppDataFuture = null;
21665    }
21666
21667    @Override
21668    public boolean isSafeMode() {
21669        // allow instant applications
21670        return mSafeMode;
21671    }
21672
21673    @Override
21674    public boolean hasSystemUidErrors() {
21675        // allow instant applications
21676        return mHasSystemUidErrors;
21677    }
21678
21679    static String arrayToString(int[] array) {
21680        StringBuffer buf = new StringBuffer(128);
21681        buf.append('[');
21682        if (array != null) {
21683            for (int i=0; i<array.length; i++) {
21684                if (i > 0) buf.append(", ");
21685                buf.append(array[i]);
21686            }
21687        }
21688        buf.append(']');
21689        return buf.toString();
21690    }
21691
21692    static class DumpState {
21693        public static final int DUMP_LIBS = 1 << 0;
21694        public static final int DUMP_FEATURES = 1 << 1;
21695        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21696        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21697        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21698        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21699        public static final int DUMP_PERMISSIONS = 1 << 6;
21700        public static final int DUMP_PACKAGES = 1 << 7;
21701        public static final int DUMP_SHARED_USERS = 1 << 8;
21702        public static final int DUMP_MESSAGES = 1 << 9;
21703        public static final int DUMP_PROVIDERS = 1 << 10;
21704        public static final int DUMP_VERIFIERS = 1 << 11;
21705        public static final int DUMP_PREFERRED = 1 << 12;
21706        public static final int DUMP_PREFERRED_XML = 1 << 13;
21707        public static final int DUMP_KEYSETS = 1 << 14;
21708        public static final int DUMP_VERSION = 1 << 15;
21709        public static final int DUMP_INSTALLS = 1 << 16;
21710        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21711        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21712        public static final int DUMP_FROZEN = 1 << 19;
21713        public static final int DUMP_DEXOPT = 1 << 20;
21714        public static final int DUMP_COMPILER_STATS = 1 << 21;
21715        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
21716        public static final int DUMP_CHANGES = 1 << 23;
21717
21718        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21719
21720        private int mTypes;
21721
21722        private int mOptions;
21723
21724        private boolean mTitlePrinted;
21725
21726        private SharedUserSetting mSharedUser;
21727
21728        public boolean isDumping(int type) {
21729            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21730                return true;
21731            }
21732
21733            return (mTypes & type) != 0;
21734        }
21735
21736        public void setDump(int type) {
21737            mTypes |= type;
21738        }
21739
21740        public boolean isOptionEnabled(int option) {
21741            return (mOptions & option) != 0;
21742        }
21743
21744        public void setOptionEnabled(int option) {
21745            mOptions |= option;
21746        }
21747
21748        public boolean onTitlePrinted() {
21749            final boolean printed = mTitlePrinted;
21750            mTitlePrinted = true;
21751            return printed;
21752        }
21753
21754        public boolean getTitlePrinted() {
21755            return mTitlePrinted;
21756        }
21757
21758        public void setTitlePrinted(boolean enabled) {
21759            mTitlePrinted = enabled;
21760        }
21761
21762        public SharedUserSetting getSharedUser() {
21763            return mSharedUser;
21764        }
21765
21766        public void setSharedUser(SharedUserSetting user) {
21767            mSharedUser = user;
21768        }
21769    }
21770
21771    @Override
21772    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21773            FileDescriptor err, String[] args, ShellCallback callback,
21774            ResultReceiver resultReceiver) {
21775        (new PackageManagerShellCommand(this)).exec(
21776                this, in, out, err, args, callback, resultReceiver);
21777    }
21778
21779    @Override
21780    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21781        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21782
21783        DumpState dumpState = new DumpState();
21784        boolean fullPreferred = false;
21785        boolean checkin = false;
21786
21787        String packageName = null;
21788        ArraySet<String> permissionNames = null;
21789
21790        int opti = 0;
21791        while (opti < args.length) {
21792            String opt = args[opti];
21793            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21794                break;
21795            }
21796            opti++;
21797
21798            if ("-a".equals(opt)) {
21799                // Right now we only know how to print all.
21800            } else if ("-h".equals(opt)) {
21801                pw.println("Package manager dump options:");
21802                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21803                pw.println("    --checkin: dump for a checkin");
21804                pw.println("    -f: print details of intent filters");
21805                pw.println("    -h: print this help");
21806                pw.println("  cmd may be one of:");
21807                pw.println("    l[ibraries]: list known shared libraries");
21808                pw.println("    f[eatures]: list device features");
21809                pw.println("    k[eysets]: print known keysets");
21810                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21811                pw.println("    perm[issions]: dump permissions");
21812                pw.println("    permission [name ...]: dump declaration and use of given permission");
21813                pw.println("    pref[erred]: print preferred package settings");
21814                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21815                pw.println("    prov[iders]: dump content providers");
21816                pw.println("    p[ackages]: dump installed packages");
21817                pw.println("    s[hared-users]: dump shared user IDs");
21818                pw.println("    m[essages]: print collected runtime messages");
21819                pw.println("    v[erifiers]: print package verifier info");
21820                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21821                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21822                pw.println("    version: print database version info");
21823                pw.println("    write: write current settings now");
21824                pw.println("    installs: details about install sessions");
21825                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21826                pw.println("    dexopt: dump dexopt state");
21827                pw.println("    compiler-stats: dump compiler statistics");
21828                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21829                pw.println("    <package.name>: info about given package");
21830                return;
21831            } else if ("--checkin".equals(opt)) {
21832                checkin = true;
21833            } else if ("-f".equals(opt)) {
21834                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21835            } else if ("--proto".equals(opt)) {
21836                dumpProto(fd);
21837                return;
21838            } else {
21839                pw.println("Unknown argument: " + opt + "; use -h for help");
21840            }
21841        }
21842
21843        // Is the caller requesting to dump a particular piece of data?
21844        if (opti < args.length) {
21845            String cmd = args[opti];
21846            opti++;
21847            // Is this a package name?
21848            if ("android".equals(cmd) || cmd.contains(".")) {
21849                packageName = cmd;
21850                // When dumping a single package, we always dump all of its
21851                // filter information since the amount of data will be reasonable.
21852                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21853            } else if ("check-permission".equals(cmd)) {
21854                if (opti >= args.length) {
21855                    pw.println("Error: check-permission missing permission argument");
21856                    return;
21857                }
21858                String perm = args[opti];
21859                opti++;
21860                if (opti >= args.length) {
21861                    pw.println("Error: check-permission missing package argument");
21862                    return;
21863                }
21864
21865                String pkg = args[opti];
21866                opti++;
21867                int user = UserHandle.getUserId(Binder.getCallingUid());
21868                if (opti < args.length) {
21869                    try {
21870                        user = Integer.parseInt(args[opti]);
21871                    } catch (NumberFormatException e) {
21872                        pw.println("Error: check-permission user argument is not a number: "
21873                                + args[opti]);
21874                        return;
21875                    }
21876                }
21877
21878                // Normalize package name to handle renamed packages and static libs
21879                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21880
21881                pw.println(checkPermission(perm, pkg, user));
21882                return;
21883            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21884                dumpState.setDump(DumpState.DUMP_LIBS);
21885            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21886                dumpState.setDump(DumpState.DUMP_FEATURES);
21887            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21888                if (opti >= args.length) {
21889                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21890                            | DumpState.DUMP_SERVICE_RESOLVERS
21891                            | DumpState.DUMP_RECEIVER_RESOLVERS
21892                            | DumpState.DUMP_CONTENT_RESOLVERS);
21893                } else {
21894                    while (opti < args.length) {
21895                        String name = args[opti];
21896                        if ("a".equals(name) || "activity".equals(name)) {
21897                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21898                        } else if ("s".equals(name) || "service".equals(name)) {
21899                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21900                        } else if ("r".equals(name) || "receiver".equals(name)) {
21901                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21902                        } else if ("c".equals(name) || "content".equals(name)) {
21903                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21904                        } else {
21905                            pw.println("Error: unknown resolver table type: " + name);
21906                            return;
21907                        }
21908                        opti++;
21909                    }
21910                }
21911            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21912                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21913            } else if ("permission".equals(cmd)) {
21914                if (opti >= args.length) {
21915                    pw.println("Error: permission requires permission name");
21916                    return;
21917                }
21918                permissionNames = new ArraySet<>();
21919                while (opti < args.length) {
21920                    permissionNames.add(args[opti]);
21921                    opti++;
21922                }
21923                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21924                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21925            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21926                dumpState.setDump(DumpState.DUMP_PREFERRED);
21927            } else if ("preferred-xml".equals(cmd)) {
21928                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21929                if (opti < args.length && "--full".equals(args[opti])) {
21930                    fullPreferred = true;
21931                    opti++;
21932                }
21933            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21934                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21935            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21936                dumpState.setDump(DumpState.DUMP_PACKAGES);
21937            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21938                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21939            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21940                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21941            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21942                dumpState.setDump(DumpState.DUMP_MESSAGES);
21943            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21944                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21945            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21946                    || "intent-filter-verifiers".equals(cmd)) {
21947                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21948            } else if ("version".equals(cmd)) {
21949                dumpState.setDump(DumpState.DUMP_VERSION);
21950            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21951                dumpState.setDump(DumpState.DUMP_KEYSETS);
21952            } else if ("installs".equals(cmd)) {
21953                dumpState.setDump(DumpState.DUMP_INSTALLS);
21954            } else if ("frozen".equals(cmd)) {
21955                dumpState.setDump(DumpState.DUMP_FROZEN);
21956            } else if ("dexopt".equals(cmd)) {
21957                dumpState.setDump(DumpState.DUMP_DEXOPT);
21958            } else if ("compiler-stats".equals(cmd)) {
21959                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21960            } else if ("enabled-overlays".equals(cmd)) {
21961                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
21962            } else if ("changes".equals(cmd)) {
21963                dumpState.setDump(DumpState.DUMP_CHANGES);
21964            } else if ("write".equals(cmd)) {
21965                synchronized (mPackages) {
21966                    mSettings.writeLPr();
21967                    pw.println("Settings written.");
21968                    return;
21969                }
21970            }
21971        }
21972
21973        if (checkin) {
21974            pw.println("vers,1");
21975        }
21976
21977        // reader
21978        synchronized (mPackages) {
21979            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21980                if (!checkin) {
21981                    if (dumpState.onTitlePrinted())
21982                        pw.println();
21983                    pw.println("Database versions:");
21984                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21985                }
21986            }
21987
21988            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21989                if (!checkin) {
21990                    if (dumpState.onTitlePrinted())
21991                        pw.println();
21992                    pw.println("Verifiers:");
21993                    pw.print("  Required: ");
21994                    pw.print(mRequiredVerifierPackage);
21995                    pw.print(" (uid=");
21996                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21997                            UserHandle.USER_SYSTEM));
21998                    pw.println(")");
21999                } else if (mRequiredVerifierPackage != null) {
22000                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22001                    pw.print(",");
22002                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22003                            UserHandle.USER_SYSTEM));
22004                }
22005            }
22006
22007            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22008                    packageName == null) {
22009                if (mIntentFilterVerifierComponent != null) {
22010                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22011                    if (!checkin) {
22012                        if (dumpState.onTitlePrinted())
22013                            pw.println();
22014                        pw.println("Intent Filter Verifier:");
22015                        pw.print("  Using: ");
22016                        pw.print(verifierPackageName);
22017                        pw.print(" (uid=");
22018                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22019                                UserHandle.USER_SYSTEM));
22020                        pw.println(")");
22021                    } else if (verifierPackageName != null) {
22022                        pw.print("ifv,"); pw.print(verifierPackageName);
22023                        pw.print(",");
22024                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22025                                UserHandle.USER_SYSTEM));
22026                    }
22027                } else {
22028                    pw.println();
22029                    pw.println("No Intent Filter Verifier available!");
22030                }
22031            }
22032
22033            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22034                boolean printedHeader = false;
22035                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22036                while (it.hasNext()) {
22037                    String libName = it.next();
22038                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22039                    if (versionedLib == null) {
22040                        continue;
22041                    }
22042                    final int versionCount = versionedLib.size();
22043                    for (int i = 0; i < versionCount; i++) {
22044                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22045                        if (!checkin) {
22046                            if (!printedHeader) {
22047                                if (dumpState.onTitlePrinted())
22048                                    pw.println();
22049                                pw.println("Libraries:");
22050                                printedHeader = true;
22051                            }
22052                            pw.print("  ");
22053                        } else {
22054                            pw.print("lib,");
22055                        }
22056                        pw.print(libEntry.info.getName());
22057                        if (libEntry.info.isStatic()) {
22058                            pw.print(" version=" + libEntry.info.getVersion());
22059                        }
22060                        if (!checkin) {
22061                            pw.print(" -> ");
22062                        }
22063                        if (libEntry.path != null) {
22064                            pw.print(" (jar) ");
22065                            pw.print(libEntry.path);
22066                        } else {
22067                            pw.print(" (apk) ");
22068                            pw.print(libEntry.apk);
22069                        }
22070                        pw.println();
22071                    }
22072                }
22073            }
22074
22075            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22076                if (dumpState.onTitlePrinted())
22077                    pw.println();
22078                if (!checkin) {
22079                    pw.println("Features:");
22080                }
22081
22082                synchronized (mAvailableFeatures) {
22083                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22084                        if (checkin) {
22085                            pw.print("feat,");
22086                            pw.print(feat.name);
22087                            pw.print(",");
22088                            pw.println(feat.version);
22089                        } else {
22090                            pw.print("  ");
22091                            pw.print(feat.name);
22092                            if (feat.version > 0) {
22093                                pw.print(" version=");
22094                                pw.print(feat.version);
22095                            }
22096                            pw.println();
22097                        }
22098                    }
22099                }
22100            }
22101
22102            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22103                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22104                        : "Activity Resolver Table:", "  ", packageName,
22105                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22106                    dumpState.setTitlePrinted(true);
22107                }
22108            }
22109            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22110                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22111                        : "Receiver Resolver Table:", "  ", packageName,
22112                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22113                    dumpState.setTitlePrinted(true);
22114                }
22115            }
22116            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22117                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22118                        : "Service Resolver Table:", "  ", packageName,
22119                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22120                    dumpState.setTitlePrinted(true);
22121                }
22122            }
22123            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22124                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22125                        : "Provider Resolver Table:", "  ", packageName,
22126                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22127                    dumpState.setTitlePrinted(true);
22128                }
22129            }
22130
22131            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22132                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22133                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22134                    int user = mSettings.mPreferredActivities.keyAt(i);
22135                    if (pir.dump(pw,
22136                            dumpState.getTitlePrinted()
22137                                ? "\nPreferred Activities User " + user + ":"
22138                                : "Preferred Activities User " + user + ":", "  ",
22139                            packageName, true, false)) {
22140                        dumpState.setTitlePrinted(true);
22141                    }
22142                }
22143            }
22144
22145            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22146                pw.flush();
22147                FileOutputStream fout = new FileOutputStream(fd);
22148                BufferedOutputStream str = new BufferedOutputStream(fout);
22149                XmlSerializer serializer = new FastXmlSerializer();
22150                try {
22151                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22152                    serializer.startDocument(null, true);
22153                    serializer.setFeature(
22154                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22155                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22156                    serializer.endDocument();
22157                    serializer.flush();
22158                } catch (IllegalArgumentException e) {
22159                    pw.println("Failed writing: " + e);
22160                } catch (IllegalStateException e) {
22161                    pw.println("Failed writing: " + e);
22162                } catch (IOException e) {
22163                    pw.println("Failed writing: " + e);
22164                }
22165            }
22166
22167            if (!checkin
22168                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22169                    && packageName == null) {
22170                pw.println();
22171                int count = mSettings.mPackages.size();
22172                if (count == 0) {
22173                    pw.println("No applications!");
22174                    pw.println();
22175                } else {
22176                    final String prefix = "  ";
22177                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22178                    if (allPackageSettings.size() == 0) {
22179                        pw.println("No domain preferred apps!");
22180                        pw.println();
22181                    } else {
22182                        pw.println("App verification status:");
22183                        pw.println();
22184                        count = 0;
22185                        for (PackageSetting ps : allPackageSettings) {
22186                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22187                            if (ivi == null || ivi.getPackageName() == null) continue;
22188                            pw.println(prefix + "Package: " + ivi.getPackageName());
22189                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22190                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22191                            pw.println();
22192                            count++;
22193                        }
22194                        if (count == 0) {
22195                            pw.println(prefix + "No app verification established.");
22196                            pw.println();
22197                        }
22198                        for (int userId : sUserManager.getUserIds()) {
22199                            pw.println("App linkages for user " + userId + ":");
22200                            pw.println();
22201                            count = 0;
22202                            for (PackageSetting ps : allPackageSettings) {
22203                                final long status = ps.getDomainVerificationStatusForUser(userId);
22204                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22205                                        && !DEBUG_DOMAIN_VERIFICATION) {
22206                                    continue;
22207                                }
22208                                pw.println(prefix + "Package: " + ps.name);
22209                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22210                                String statusStr = IntentFilterVerificationInfo.
22211                                        getStatusStringFromValue(status);
22212                                pw.println(prefix + "Status:  " + statusStr);
22213                                pw.println();
22214                                count++;
22215                            }
22216                            if (count == 0) {
22217                                pw.println(prefix + "No configured app linkages.");
22218                                pw.println();
22219                            }
22220                        }
22221                    }
22222                }
22223            }
22224
22225            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22226                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22227                if (packageName == null && permissionNames == null) {
22228                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22229                        if (iperm == 0) {
22230                            if (dumpState.onTitlePrinted())
22231                                pw.println();
22232                            pw.println("AppOp Permissions:");
22233                        }
22234                        pw.print("  AppOp Permission ");
22235                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22236                        pw.println(":");
22237                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22238                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22239                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22240                        }
22241                    }
22242                }
22243            }
22244
22245            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22246                boolean printedSomething = false;
22247                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22248                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22249                        continue;
22250                    }
22251                    if (!printedSomething) {
22252                        if (dumpState.onTitlePrinted())
22253                            pw.println();
22254                        pw.println("Registered ContentProviders:");
22255                        printedSomething = true;
22256                    }
22257                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22258                    pw.print("    "); pw.println(p.toString());
22259                }
22260                printedSomething = false;
22261                for (Map.Entry<String, PackageParser.Provider> entry :
22262                        mProvidersByAuthority.entrySet()) {
22263                    PackageParser.Provider p = entry.getValue();
22264                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22265                        continue;
22266                    }
22267                    if (!printedSomething) {
22268                        if (dumpState.onTitlePrinted())
22269                            pw.println();
22270                        pw.println("ContentProvider Authorities:");
22271                        printedSomething = true;
22272                    }
22273                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22274                    pw.print("    "); pw.println(p.toString());
22275                    if (p.info != null && p.info.applicationInfo != null) {
22276                        final String appInfo = p.info.applicationInfo.toString();
22277                        pw.print("      applicationInfo="); pw.println(appInfo);
22278                    }
22279                }
22280            }
22281
22282            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22283                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22284            }
22285
22286            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22287                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22288            }
22289
22290            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22291                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22292            }
22293
22294            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22295                if (dumpState.onTitlePrinted()) pw.println();
22296                pw.println("Package Changes:");
22297                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22298                final int K = mChangedPackages.size();
22299                for (int i = 0; i < K; i++) {
22300                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22301                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22302                    final int N = changes.size();
22303                    if (N == 0) {
22304                        pw.print("    "); pw.println("No packages changed");
22305                    } else {
22306                        for (int j = 0; j < N; j++) {
22307                            final String pkgName = changes.valueAt(j);
22308                            final int sequenceNumber = changes.keyAt(j);
22309                            pw.print("    ");
22310                            pw.print("seq=");
22311                            pw.print(sequenceNumber);
22312                            pw.print(", package=");
22313                            pw.println(pkgName);
22314                        }
22315                    }
22316                }
22317            }
22318
22319            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22320                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22321            }
22322
22323            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22324                // XXX should handle packageName != null by dumping only install data that
22325                // the given package is involved with.
22326                if (dumpState.onTitlePrinted()) pw.println();
22327
22328                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22329                ipw.println();
22330                ipw.println("Frozen packages:");
22331                ipw.increaseIndent();
22332                if (mFrozenPackages.size() == 0) {
22333                    ipw.println("(none)");
22334                } else {
22335                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22336                        ipw.println(mFrozenPackages.valueAt(i));
22337                    }
22338                }
22339                ipw.decreaseIndent();
22340            }
22341
22342            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22343                if (dumpState.onTitlePrinted()) pw.println();
22344                dumpDexoptStateLPr(pw, packageName);
22345            }
22346
22347            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22348                if (dumpState.onTitlePrinted()) pw.println();
22349                dumpCompilerStatsLPr(pw, packageName);
22350            }
22351
22352            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
22353                if (dumpState.onTitlePrinted()) pw.println();
22354                dumpEnabledOverlaysLPr(pw);
22355            }
22356
22357            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22358                if (dumpState.onTitlePrinted()) pw.println();
22359                mSettings.dumpReadMessagesLPr(pw, dumpState);
22360
22361                pw.println();
22362                pw.println("Package warning messages:");
22363                BufferedReader in = null;
22364                String line = null;
22365                try {
22366                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22367                    while ((line = in.readLine()) != null) {
22368                        if (line.contains("ignored: updated version")) continue;
22369                        pw.println(line);
22370                    }
22371                } catch (IOException ignored) {
22372                } finally {
22373                    IoUtils.closeQuietly(in);
22374                }
22375            }
22376
22377            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22378                BufferedReader in = null;
22379                String line = null;
22380                try {
22381                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22382                    while ((line = in.readLine()) != null) {
22383                        if (line.contains("ignored: updated version")) continue;
22384                        pw.print("msg,");
22385                        pw.println(line);
22386                    }
22387                } catch (IOException ignored) {
22388                } finally {
22389                    IoUtils.closeQuietly(in);
22390                }
22391            }
22392        }
22393
22394        // PackageInstaller should be called outside of mPackages lock
22395        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22396            // XXX should handle packageName != null by dumping only install data that
22397            // the given package is involved with.
22398            if (dumpState.onTitlePrinted()) pw.println();
22399            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22400        }
22401    }
22402
22403    private void dumpProto(FileDescriptor fd) {
22404        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22405
22406        synchronized (mPackages) {
22407            final long requiredVerifierPackageToken =
22408                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22409            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22410            proto.write(
22411                    PackageServiceDumpProto.PackageShortProto.UID,
22412                    getPackageUid(
22413                            mRequiredVerifierPackage,
22414                            MATCH_DEBUG_TRIAGED_MISSING,
22415                            UserHandle.USER_SYSTEM));
22416            proto.end(requiredVerifierPackageToken);
22417
22418            if (mIntentFilterVerifierComponent != null) {
22419                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22420                final long verifierPackageToken =
22421                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22422                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22423                proto.write(
22424                        PackageServiceDumpProto.PackageShortProto.UID,
22425                        getPackageUid(
22426                                verifierPackageName,
22427                                MATCH_DEBUG_TRIAGED_MISSING,
22428                                UserHandle.USER_SYSTEM));
22429                proto.end(verifierPackageToken);
22430            }
22431
22432            dumpSharedLibrariesProto(proto);
22433            dumpFeaturesProto(proto);
22434            mSettings.dumpPackagesProto(proto);
22435            mSettings.dumpSharedUsersProto(proto);
22436            dumpMessagesProto(proto);
22437        }
22438        proto.flush();
22439    }
22440
22441    private void dumpMessagesProto(ProtoOutputStream proto) {
22442        BufferedReader in = null;
22443        String line = null;
22444        try {
22445            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22446            while ((line = in.readLine()) != null) {
22447                if (line.contains("ignored: updated version")) continue;
22448                proto.write(PackageServiceDumpProto.MESSAGES, line);
22449            }
22450        } catch (IOException ignored) {
22451        } finally {
22452            IoUtils.closeQuietly(in);
22453        }
22454    }
22455
22456    private void dumpFeaturesProto(ProtoOutputStream proto) {
22457        synchronized (mAvailableFeatures) {
22458            final int count = mAvailableFeatures.size();
22459            for (int i = 0; i < count; i++) {
22460                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22461                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22462                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22463                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22464                proto.end(featureToken);
22465            }
22466        }
22467    }
22468
22469    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22470        final int count = mSharedLibraries.size();
22471        for (int i = 0; i < count; i++) {
22472            final String libName = mSharedLibraries.keyAt(i);
22473            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22474            if (versionedLib == null) {
22475                continue;
22476            }
22477            final int versionCount = versionedLib.size();
22478            for (int j = 0; j < versionCount; j++) {
22479                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22480                final long sharedLibraryToken =
22481                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22482                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22483                final boolean isJar = (libEntry.path != null);
22484                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22485                if (isJar) {
22486                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22487                } else {
22488                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22489                }
22490                proto.end(sharedLibraryToken);
22491            }
22492        }
22493    }
22494
22495    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22496        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22497        ipw.println();
22498        ipw.println("Dexopt state:");
22499        ipw.increaseIndent();
22500        Collection<PackageParser.Package> packages = null;
22501        if (packageName != null) {
22502            PackageParser.Package targetPackage = mPackages.get(packageName);
22503            if (targetPackage != null) {
22504                packages = Collections.singletonList(targetPackage);
22505            } else {
22506                ipw.println("Unable to find package: " + packageName);
22507                return;
22508            }
22509        } else {
22510            packages = mPackages.values();
22511        }
22512
22513        for (PackageParser.Package pkg : packages) {
22514            ipw.println("[" + pkg.packageName + "]");
22515            ipw.increaseIndent();
22516            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22517            ipw.decreaseIndent();
22518        }
22519    }
22520
22521    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22522        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22523        ipw.println();
22524        ipw.println("Compiler stats:");
22525        ipw.increaseIndent();
22526        Collection<PackageParser.Package> packages = null;
22527        if (packageName != null) {
22528            PackageParser.Package targetPackage = mPackages.get(packageName);
22529            if (targetPackage != null) {
22530                packages = Collections.singletonList(targetPackage);
22531            } else {
22532                ipw.println("Unable to find package: " + packageName);
22533                return;
22534            }
22535        } else {
22536            packages = mPackages.values();
22537        }
22538
22539        for (PackageParser.Package pkg : packages) {
22540            ipw.println("[" + pkg.packageName + "]");
22541            ipw.increaseIndent();
22542
22543            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22544            if (stats == null) {
22545                ipw.println("(No recorded stats)");
22546            } else {
22547                stats.dump(ipw);
22548            }
22549            ipw.decreaseIndent();
22550        }
22551    }
22552
22553    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
22554        pw.println("Enabled overlay paths:");
22555        final int N = mEnabledOverlayPaths.size();
22556        for (int i = 0; i < N; i++) {
22557            final int userId = mEnabledOverlayPaths.keyAt(i);
22558            pw.println(String.format("    User %d:", userId));
22559            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
22560                mEnabledOverlayPaths.valueAt(i);
22561            final int M = userSpecificOverlays.size();
22562            for (int j = 0; j < M; j++) {
22563                final String targetPackageName = userSpecificOverlays.keyAt(j);
22564                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
22565                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
22566            }
22567        }
22568    }
22569
22570    private String dumpDomainString(String packageName) {
22571        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22572                .getList();
22573        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22574
22575        ArraySet<String> result = new ArraySet<>();
22576        if (iviList.size() > 0) {
22577            for (IntentFilterVerificationInfo ivi : iviList) {
22578                for (String host : ivi.getDomains()) {
22579                    result.add(host);
22580                }
22581            }
22582        }
22583        if (filters != null && filters.size() > 0) {
22584            for (IntentFilter filter : filters) {
22585                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22586                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22587                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22588                    result.addAll(filter.getHostsList());
22589                }
22590            }
22591        }
22592
22593        StringBuilder sb = new StringBuilder(result.size() * 16);
22594        for (String domain : result) {
22595            if (sb.length() > 0) sb.append(" ");
22596            sb.append(domain);
22597        }
22598        return sb.toString();
22599    }
22600
22601    // ------- apps on sdcard specific code -------
22602    static final boolean DEBUG_SD_INSTALL = false;
22603
22604    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22605
22606    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22607
22608    private boolean mMediaMounted = false;
22609
22610    static String getEncryptKey() {
22611        try {
22612            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22613                    SD_ENCRYPTION_KEYSTORE_NAME);
22614            if (sdEncKey == null) {
22615                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22616                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22617                if (sdEncKey == null) {
22618                    Slog.e(TAG, "Failed to create encryption keys");
22619                    return null;
22620                }
22621            }
22622            return sdEncKey;
22623        } catch (NoSuchAlgorithmException nsae) {
22624            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22625            return null;
22626        } catch (IOException ioe) {
22627            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22628            return null;
22629        }
22630    }
22631
22632    /*
22633     * Update media status on PackageManager.
22634     */
22635    @Override
22636    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22637        enforceSystemOrRoot("Media status can only be updated by the system");
22638        // reader; this apparently protects mMediaMounted, but should probably
22639        // be a different lock in that case.
22640        synchronized (mPackages) {
22641            Log.i(TAG, "Updating external media status from "
22642                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22643                    + (mediaStatus ? "mounted" : "unmounted"));
22644            if (DEBUG_SD_INSTALL)
22645                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22646                        + ", mMediaMounted=" + mMediaMounted);
22647            if (mediaStatus == mMediaMounted) {
22648                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22649                        : 0, -1);
22650                mHandler.sendMessage(msg);
22651                return;
22652            }
22653            mMediaMounted = mediaStatus;
22654        }
22655        // Queue up an async operation since the package installation may take a
22656        // little while.
22657        mHandler.post(new Runnable() {
22658            public void run() {
22659                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22660            }
22661        });
22662    }
22663
22664    /**
22665     * Called by StorageManagerService when the initial ASECs to scan are available.
22666     * Should block until all the ASEC containers are finished being scanned.
22667     */
22668    public void scanAvailableAsecs() {
22669        updateExternalMediaStatusInner(true, false, false);
22670    }
22671
22672    /*
22673     * Collect information of applications on external media, map them against
22674     * existing containers and update information based on current mount status.
22675     * Please note that we always have to report status if reportStatus has been
22676     * set to true especially when unloading packages.
22677     */
22678    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22679            boolean externalStorage) {
22680        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22681        int[] uidArr = EmptyArray.INT;
22682
22683        final String[] list = PackageHelper.getSecureContainerList();
22684        if (ArrayUtils.isEmpty(list)) {
22685            Log.i(TAG, "No secure containers found");
22686        } else {
22687            // Process list of secure containers and categorize them
22688            // as active or stale based on their package internal state.
22689
22690            // reader
22691            synchronized (mPackages) {
22692                for (String cid : list) {
22693                    // Leave stages untouched for now; installer service owns them
22694                    if (PackageInstallerService.isStageName(cid)) continue;
22695
22696                    if (DEBUG_SD_INSTALL)
22697                        Log.i(TAG, "Processing container " + cid);
22698                    String pkgName = getAsecPackageName(cid);
22699                    if (pkgName == null) {
22700                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22701                        continue;
22702                    }
22703                    if (DEBUG_SD_INSTALL)
22704                        Log.i(TAG, "Looking for pkg : " + pkgName);
22705
22706                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22707                    if (ps == null) {
22708                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22709                        continue;
22710                    }
22711
22712                    /*
22713                     * Skip packages that are not external if we're unmounting
22714                     * external storage.
22715                     */
22716                    if (externalStorage && !isMounted && !isExternal(ps)) {
22717                        continue;
22718                    }
22719
22720                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22721                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22722                    // The package status is changed only if the code path
22723                    // matches between settings and the container id.
22724                    if (ps.codePathString != null
22725                            && ps.codePathString.startsWith(args.getCodePath())) {
22726                        if (DEBUG_SD_INSTALL) {
22727                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22728                                    + " at code path: " + ps.codePathString);
22729                        }
22730
22731                        // We do have a valid package installed on sdcard
22732                        processCids.put(args, ps.codePathString);
22733                        final int uid = ps.appId;
22734                        if (uid != -1) {
22735                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22736                        }
22737                    } else {
22738                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22739                                + ps.codePathString);
22740                    }
22741                }
22742            }
22743
22744            Arrays.sort(uidArr);
22745        }
22746
22747        // Process packages with valid entries.
22748        if (isMounted) {
22749            if (DEBUG_SD_INSTALL)
22750                Log.i(TAG, "Loading packages");
22751            loadMediaPackages(processCids, uidArr, externalStorage);
22752            startCleaningPackages();
22753            mInstallerService.onSecureContainersAvailable();
22754        } else {
22755            if (DEBUG_SD_INSTALL)
22756                Log.i(TAG, "Unloading packages");
22757            unloadMediaPackages(processCids, uidArr, reportStatus);
22758        }
22759    }
22760
22761    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22762            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22763        final int size = infos.size();
22764        final String[] packageNames = new String[size];
22765        final int[] packageUids = new int[size];
22766        for (int i = 0; i < size; i++) {
22767            final ApplicationInfo info = infos.get(i);
22768            packageNames[i] = info.packageName;
22769            packageUids[i] = info.uid;
22770        }
22771        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22772                finishedReceiver);
22773    }
22774
22775    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22776            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22777        sendResourcesChangedBroadcast(mediaStatus, replacing,
22778                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22779    }
22780
22781    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22782            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22783        int size = pkgList.length;
22784        if (size > 0) {
22785            // Send broadcasts here
22786            Bundle extras = new Bundle();
22787            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22788            if (uidArr != null) {
22789                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22790            }
22791            if (replacing) {
22792                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22793            }
22794            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22795                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22796            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22797        }
22798    }
22799
22800   /*
22801     * Look at potentially valid container ids from processCids If package
22802     * information doesn't match the one on record or package scanning fails,
22803     * the cid is added to list of removeCids. We currently don't delete stale
22804     * containers.
22805     */
22806    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22807            boolean externalStorage) {
22808        ArrayList<String> pkgList = new ArrayList<String>();
22809        Set<AsecInstallArgs> keys = processCids.keySet();
22810
22811        for (AsecInstallArgs args : keys) {
22812            String codePath = processCids.get(args);
22813            if (DEBUG_SD_INSTALL)
22814                Log.i(TAG, "Loading container : " + args.cid);
22815            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22816            try {
22817                // Make sure there are no container errors first.
22818                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22819                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22820                            + " when installing from sdcard");
22821                    continue;
22822                }
22823                // Check code path here.
22824                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22825                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22826                            + " does not match one in settings " + codePath);
22827                    continue;
22828                }
22829                // Parse package
22830                int parseFlags = mDefParseFlags;
22831                if (args.isExternalAsec()) {
22832                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22833                }
22834                if (args.isFwdLocked()) {
22835                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22836                }
22837
22838                synchronized (mInstallLock) {
22839                    PackageParser.Package pkg = null;
22840                    try {
22841                        // Sadly we don't know the package name yet to freeze it
22842                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22843                                SCAN_IGNORE_FROZEN, 0, null);
22844                    } catch (PackageManagerException e) {
22845                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22846                    }
22847                    // Scan the package
22848                    if (pkg != null) {
22849                        /*
22850                         * TODO why is the lock being held? doPostInstall is
22851                         * called in other places without the lock. This needs
22852                         * to be straightened out.
22853                         */
22854                        // writer
22855                        synchronized (mPackages) {
22856                            retCode = PackageManager.INSTALL_SUCCEEDED;
22857                            pkgList.add(pkg.packageName);
22858                            // Post process args
22859                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22860                                    pkg.applicationInfo.uid);
22861                        }
22862                    } else {
22863                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22864                    }
22865                }
22866
22867            } finally {
22868                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22869                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22870                }
22871            }
22872        }
22873        // writer
22874        synchronized (mPackages) {
22875            // If the platform SDK has changed since the last time we booted,
22876            // we need to re-grant app permission to catch any new ones that
22877            // appear. This is really a hack, and means that apps can in some
22878            // cases get permissions that the user didn't initially explicitly
22879            // allow... it would be nice to have some better way to handle
22880            // this situation.
22881            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22882                    : mSettings.getInternalVersion();
22883            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22884                    : StorageManager.UUID_PRIVATE_INTERNAL;
22885
22886            int updateFlags = UPDATE_PERMISSIONS_ALL;
22887            if (ver.sdkVersion != mSdkVersion) {
22888                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22889                        + mSdkVersion + "; regranting permissions for external");
22890                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22891            }
22892            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22893
22894            // Yay, everything is now upgraded
22895            ver.forceCurrent();
22896
22897            // can downgrade to reader
22898            // Persist settings
22899            mSettings.writeLPr();
22900        }
22901        // Send a broadcast to let everyone know we are done processing
22902        if (pkgList.size() > 0) {
22903            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22904        }
22905    }
22906
22907   /*
22908     * Utility method to unload a list of specified containers
22909     */
22910    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22911        // Just unmount all valid containers.
22912        for (AsecInstallArgs arg : cidArgs) {
22913            synchronized (mInstallLock) {
22914                arg.doPostDeleteLI(false);
22915           }
22916       }
22917   }
22918
22919    /*
22920     * Unload packages mounted on external media. This involves deleting package
22921     * data from internal structures, sending broadcasts about disabled packages,
22922     * gc'ing to free up references, unmounting all secure containers
22923     * corresponding to packages on external media, and posting a
22924     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22925     * that we always have to post this message if status has been requested no
22926     * matter what.
22927     */
22928    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22929            final boolean reportStatus) {
22930        if (DEBUG_SD_INSTALL)
22931            Log.i(TAG, "unloading media packages");
22932        ArrayList<String> pkgList = new ArrayList<String>();
22933        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22934        final Set<AsecInstallArgs> keys = processCids.keySet();
22935        for (AsecInstallArgs args : keys) {
22936            String pkgName = args.getPackageName();
22937            if (DEBUG_SD_INSTALL)
22938                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22939            // Delete package internally
22940            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22941            synchronized (mInstallLock) {
22942                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22943                final boolean res;
22944                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22945                        "unloadMediaPackages")) {
22946                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22947                            null);
22948                }
22949                if (res) {
22950                    pkgList.add(pkgName);
22951                } else {
22952                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22953                    failedList.add(args);
22954                }
22955            }
22956        }
22957
22958        // reader
22959        synchronized (mPackages) {
22960            // We didn't update the settings after removing each package;
22961            // write them now for all packages.
22962            mSettings.writeLPr();
22963        }
22964
22965        // We have to absolutely send UPDATED_MEDIA_STATUS only
22966        // after confirming that all the receivers processed the ordered
22967        // broadcast when packages get disabled, force a gc to clean things up.
22968        // and unload all the containers.
22969        if (pkgList.size() > 0) {
22970            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22971                    new IIntentReceiver.Stub() {
22972                public void performReceive(Intent intent, int resultCode, String data,
22973                        Bundle extras, boolean ordered, boolean sticky,
22974                        int sendingUser) throws RemoteException {
22975                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22976                            reportStatus ? 1 : 0, 1, keys);
22977                    mHandler.sendMessage(msg);
22978                }
22979            });
22980        } else {
22981            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22982                    keys);
22983            mHandler.sendMessage(msg);
22984        }
22985    }
22986
22987    private void loadPrivatePackages(final VolumeInfo vol) {
22988        mHandler.post(new Runnable() {
22989            @Override
22990            public void run() {
22991                loadPrivatePackagesInner(vol);
22992            }
22993        });
22994    }
22995
22996    private void loadPrivatePackagesInner(VolumeInfo vol) {
22997        final String volumeUuid = vol.fsUuid;
22998        if (TextUtils.isEmpty(volumeUuid)) {
22999            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23000            return;
23001        }
23002
23003        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23004        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23005        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23006
23007        final VersionInfo ver;
23008        final List<PackageSetting> packages;
23009        synchronized (mPackages) {
23010            ver = mSettings.findOrCreateVersion(volumeUuid);
23011            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23012        }
23013
23014        for (PackageSetting ps : packages) {
23015            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23016            synchronized (mInstallLock) {
23017                final PackageParser.Package pkg;
23018                try {
23019                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23020                    loaded.add(pkg.applicationInfo);
23021
23022                } catch (PackageManagerException e) {
23023                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23024                }
23025
23026                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23027                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23028                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23029                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23030                }
23031            }
23032        }
23033
23034        // Reconcile app data for all started/unlocked users
23035        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23036        final UserManager um = mContext.getSystemService(UserManager.class);
23037        UserManagerInternal umInternal = getUserManagerInternal();
23038        for (UserInfo user : um.getUsers()) {
23039            final int flags;
23040            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23041                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23042            } else if (umInternal.isUserRunning(user.id)) {
23043                flags = StorageManager.FLAG_STORAGE_DE;
23044            } else {
23045                continue;
23046            }
23047
23048            try {
23049                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23050                synchronized (mInstallLock) {
23051                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23052                }
23053            } catch (IllegalStateException e) {
23054                // Device was probably ejected, and we'll process that event momentarily
23055                Slog.w(TAG, "Failed to prepare storage: " + e);
23056            }
23057        }
23058
23059        synchronized (mPackages) {
23060            int updateFlags = UPDATE_PERMISSIONS_ALL;
23061            if (ver.sdkVersion != mSdkVersion) {
23062                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23063                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23064                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23065            }
23066            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23067
23068            // Yay, everything is now upgraded
23069            ver.forceCurrent();
23070
23071            mSettings.writeLPr();
23072        }
23073
23074        for (PackageFreezer freezer : freezers) {
23075            freezer.close();
23076        }
23077
23078        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23079        sendResourcesChangedBroadcast(true, false, loaded, null);
23080    }
23081
23082    private void unloadPrivatePackages(final VolumeInfo vol) {
23083        mHandler.post(new Runnable() {
23084            @Override
23085            public void run() {
23086                unloadPrivatePackagesInner(vol);
23087            }
23088        });
23089    }
23090
23091    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23092        final String volumeUuid = vol.fsUuid;
23093        if (TextUtils.isEmpty(volumeUuid)) {
23094            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23095            return;
23096        }
23097
23098        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23099        synchronized (mInstallLock) {
23100        synchronized (mPackages) {
23101            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23102            for (PackageSetting ps : packages) {
23103                if (ps.pkg == null) continue;
23104
23105                final ApplicationInfo info = ps.pkg.applicationInfo;
23106                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23107                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23108
23109                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23110                        "unloadPrivatePackagesInner")) {
23111                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23112                            false, null)) {
23113                        unloaded.add(info);
23114                    } else {
23115                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23116                    }
23117                }
23118
23119                // Try very hard to release any references to this package
23120                // so we don't risk the system server being killed due to
23121                // open FDs
23122                AttributeCache.instance().removePackage(ps.name);
23123            }
23124
23125            mSettings.writeLPr();
23126        }
23127        }
23128
23129        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23130        sendResourcesChangedBroadcast(false, false, unloaded, null);
23131
23132        // Try very hard to release any references to this path so we don't risk
23133        // the system server being killed due to open FDs
23134        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23135
23136        for (int i = 0; i < 3; i++) {
23137            System.gc();
23138            System.runFinalization();
23139        }
23140    }
23141
23142    private void assertPackageKnown(String volumeUuid, String packageName)
23143            throws PackageManagerException {
23144        synchronized (mPackages) {
23145            // Normalize package name to handle renamed packages
23146            packageName = normalizePackageNameLPr(packageName);
23147
23148            final PackageSetting ps = mSettings.mPackages.get(packageName);
23149            if (ps == null) {
23150                throw new PackageManagerException("Package " + packageName + " is unknown");
23151            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23152                throw new PackageManagerException(
23153                        "Package " + packageName + " found on unknown volume " + volumeUuid
23154                                + "; expected volume " + ps.volumeUuid);
23155            }
23156        }
23157    }
23158
23159    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23160            throws PackageManagerException {
23161        synchronized (mPackages) {
23162            // Normalize package name to handle renamed packages
23163            packageName = normalizePackageNameLPr(packageName);
23164
23165            final PackageSetting ps = mSettings.mPackages.get(packageName);
23166            if (ps == null) {
23167                throw new PackageManagerException("Package " + packageName + " is unknown");
23168            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23169                throw new PackageManagerException(
23170                        "Package " + packageName + " found on unknown volume " + volumeUuid
23171                                + "; expected volume " + ps.volumeUuid);
23172            } else if (!ps.getInstalled(userId)) {
23173                throw new PackageManagerException(
23174                        "Package " + packageName + " not installed for user " + userId);
23175            }
23176        }
23177    }
23178
23179    private List<String> collectAbsoluteCodePaths() {
23180        synchronized (mPackages) {
23181            List<String> codePaths = new ArrayList<>();
23182            final int packageCount = mSettings.mPackages.size();
23183            for (int i = 0; i < packageCount; i++) {
23184                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23185                codePaths.add(ps.codePath.getAbsolutePath());
23186            }
23187            return codePaths;
23188        }
23189    }
23190
23191    /**
23192     * Examine all apps present on given mounted volume, and destroy apps that
23193     * aren't expected, either due to uninstallation or reinstallation on
23194     * another volume.
23195     */
23196    private void reconcileApps(String volumeUuid) {
23197        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23198        List<File> filesToDelete = null;
23199
23200        final File[] files = FileUtils.listFilesOrEmpty(
23201                Environment.getDataAppDirectory(volumeUuid));
23202        for (File file : files) {
23203            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23204                    && !PackageInstallerService.isStageName(file.getName());
23205            if (!isPackage) {
23206                // Ignore entries which are not packages
23207                continue;
23208            }
23209
23210            String absolutePath = file.getAbsolutePath();
23211
23212            boolean pathValid = false;
23213            final int absoluteCodePathCount = absoluteCodePaths.size();
23214            for (int i = 0; i < absoluteCodePathCount; i++) {
23215                String absoluteCodePath = absoluteCodePaths.get(i);
23216                if (absolutePath.startsWith(absoluteCodePath)) {
23217                    pathValid = true;
23218                    break;
23219                }
23220            }
23221
23222            if (!pathValid) {
23223                if (filesToDelete == null) {
23224                    filesToDelete = new ArrayList<>();
23225                }
23226                filesToDelete.add(file);
23227            }
23228        }
23229
23230        if (filesToDelete != null) {
23231            final int fileToDeleteCount = filesToDelete.size();
23232            for (int i = 0; i < fileToDeleteCount; i++) {
23233                File fileToDelete = filesToDelete.get(i);
23234                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23235                synchronized (mInstallLock) {
23236                    removeCodePathLI(fileToDelete);
23237                }
23238            }
23239        }
23240    }
23241
23242    /**
23243     * Reconcile all app data for the given user.
23244     * <p>
23245     * Verifies that directories exist and that ownership and labeling is
23246     * correct for all installed apps on all mounted volumes.
23247     */
23248    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23249        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23250        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23251            final String volumeUuid = vol.getFsUuid();
23252            synchronized (mInstallLock) {
23253                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23254            }
23255        }
23256    }
23257
23258    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23259            boolean migrateAppData) {
23260        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23261    }
23262
23263    /**
23264     * Reconcile all app data on given mounted volume.
23265     * <p>
23266     * Destroys app data that isn't expected, either due to uninstallation or
23267     * reinstallation on another volume.
23268     * <p>
23269     * Verifies that directories exist and that ownership and labeling is
23270     * correct for all installed apps.
23271     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23272     */
23273    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23274            boolean migrateAppData, boolean onlyCoreApps) {
23275        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23276                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23277        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23278
23279        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23280        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23281
23282        // First look for stale data that doesn't belong, and check if things
23283        // have changed since we did our last restorecon
23284        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23285            if (StorageManager.isFileEncryptedNativeOrEmulated()
23286                    && !StorageManager.isUserKeyUnlocked(userId)) {
23287                throw new RuntimeException(
23288                        "Yikes, someone asked us to reconcile CE storage while " + userId
23289                                + " was still locked; this would have caused massive data loss!");
23290            }
23291
23292            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23293            for (File file : files) {
23294                final String packageName = file.getName();
23295                try {
23296                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23297                } catch (PackageManagerException e) {
23298                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23299                    try {
23300                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23301                                StorageManager.FLAG_STORAGE_CE, 0);
23302                    } catch (InstallerException e2) {
23303                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23304                    }
23305                }
23306            }
23307        }
23308        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23309            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23310            for (File file : files) {
23311                final String packageName = file.getName();
23312                try {
23313                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23314                } catch (PackageManagerException e) {
23315                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23316                    try {
23317                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23318                                StorageManager.FLAG_STORAGE_DE, 0);
23319                    } catch (InstallerException e2) {
23320                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23321                    }
23322                }
23323            }
23324        }
23325
23326        // Ensure that data directories are ready to roll for all packages
23327        // installed for this volume and user
23328        final List<PackageSetting> packages;
23329        synchronized (mPackages) {
23330            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23331        }
23332        int preparedCount = 0;
23333        for (PackageSetting ps : packages) {
23334            final String packageName = ps.name;
23335            if (ps.pkg == null) {
23336                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23337                // TODO: might be due to legacy ASEC apps; we should circle back
23338                // and reconcile again once they're scanned
23339                continue;
23340            }
23341            // Skip non-core apps if requested
23342            if (onlyCoreApps && !ps.pkg.coreApp) {
23343                result.add(packageName);
23344                continue;
23345            }
23346
23347            if (ps.getInstalled(userId)) {
23348                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23349                preparedCount++;
23350            }
23351        }
23352
23353        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23354        return result;
23355    }
23356
23357    /**
23358     * Prepare app data for the given app just after it was installed or
23359     * upgraded. This method carefully only touches users that it's installed
23360     * for, and it forces a restorecon to handle any seinfo changes.
23361     * <p>
23362     * Verifies that directories exist and that ownership and labeling is
23363     * correct for all installed apps. If there is an ownership mismatch, it
23364     * will try recovering system apps by wiping data; third-party app data is
23365     * left intact.
23366     * <p>
23367     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23368     */
23369    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23370        final PackageSetting ps;
23371        synchronized (mPackages) {
23372            ps = mSettings.mPackages.get(pkg.packageName);
23373            mSettings.writeKernelMappingLPr(ps);
23374        }
23375
23376        final UserManager um = mContext.getSystemService(UserManager.class);
23377        UserManagerInternal umInternal = getUserManagerInternal();
23378        for (UserInfo user : um.getUsers()) {
23379            final int flags;
23380            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23381                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23382            } else if (umInternal.isUserRunning(user.id)) {
23383                flags = StorageManager.FLAG_STORAGE_DE;
23384            } else {
23385                continue;
23386            }
23387
23388            if (ps.getInstalled(user.id)) {
23389                // TODO: when user data is locked, mark that we're still dirty
23390                prepareAppDataLIF(pkg, user.id, flags);
23391            }
23392        }
23393    }
23394
23395    /**
23396     * Prepare app data for the given app.
23397     * <p>
23398     * Verifies that directories exist and that ownership and labeling is
23399     * correct for all installed apps. If there is an ownership mismatch, this
23400     * will try recovering system apps by wiping data; third-party app data is
23401     * left intact.
23402     */
23403    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23404        if (pkg == null) {
23405            Slog.wtf(TAG, "Package was null!", new Throwable());
23406            return;
23407        }
23408        prepareAppDataLeafLIF(pkg, userId, flags);
23409        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23410        for (int i = 0; i < childCount; i++) {
23411            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23412        }
23413    }
23414
23415    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23416            boolean maybeMigrateAppData) {
23417        prepareAppDataLIF(pkg, userId, flags);
23418
23419        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23420            // We may have just shuffled around app data directories, so
23421            // prepare them one more time
23422            prepareAppDataLIF(pkg, userId, flags);
23423        }
23424    }
23425
23426    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23427        if (DEBUG_APP_DATA) {
23428            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23429                    + Integer.toHexString(flags));
23430        }
23431
23432        final String volumeUuid = pkg.volumeUuid;
23433        final String packageName = pkg.packageName;
23434        final ApplicationInfo app = pkg.applicationInfo;
23435        final int appId = UserHandle.getAppId(app.uid);
23436
23437        Preconditions.checkNotNull(app.seInfo);
23438
23439        long ceDataInode = -1;
23440        try {
23441            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23442                    appId, app.seInfo, app.targetSdkVersion);
23443        } catch (InstallerException e) {
23444            if (app.isSystemApp()) {
23445                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23446                        + ", but trying to recover: " + e);
23447                destroyAppDataLeafLIF(pkg, userId, flags);
23448                try {
23449                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23450                            appId, app.seInfo, app.targetSdkVersion);
23451                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23452                } catch (InstallerException e2) {
23453                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23454                }
23455            } else {
23456                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23457            }
23458        }
23459
23460        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23461            // TODO: mark this structure as dirty so we persist it!
23462            synchronized (mPackages) {
23463                final PackageSetting ps = mSettings.mPackages.get(packageName);
23464                if (ps != null) {
23465                    ps.setCeDataInode(ceDataInode, userId);
23466                }
23467            }
23468        }
23469
23470        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23471    }
23472
23473    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23474        if (pkg == null) {
23475            Slog.wtf(TAG, "Package was null!", new Throwable());
23476            return;
23477        }
23478        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23479        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23480        for (int i = 0; i < childCount; i++) {
23481            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23482        }
23483    }
23484
23485    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23486        final String volumeUuid = pkg.volumeUuid;
23487        final String packageName = pkg.packageName;
23488        final ApplicationInfo app = pkg.applicationInfo;
23489
23490        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23491            // Create a native library symlink only if we have native libraries
23492            // and if the native libraries are 32 bit libraries. We do not provide
23493            // this symlink for 64 bit libraries.
23494            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23495                final String nativeLibPath = app.nativeLibraryDir;
23496                try {
23497                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23498                            nativeLibPath, userId);
23499                } catch (InstallerException e) {
23500                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23501                }
23502            }
23503        }
23504    }
23505
23506    /**
23507     * For system apps on non-FBE devices, this method migrates any existing
23508     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23509     * requested by the app.
23510     */
23511    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23512        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23513                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23514            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23515                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23516            try {
23517                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23518                        storageTarget);
23519            } catch (InstallerException e) {
23520                logCriticalInfo(Log.WARN,
23521                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23522            }
23523            return true;
23524        } else {
23525            return false;
23526        }
23527    }
23528
23529    public PackageFreezer freezePackage(String packageName, String killReason) {
23530        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23531    }
23532
23533    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23534        return new PackageFreezer(packageName, userId, killReason);
23535    }
23536
23537    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23538            String killReason) {
23539        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23540    }
23541
23542    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23543            String killReason) {
23544        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23545            return new PackageFreezer();
23546        } else {
23547            return freezePackage(packageName, userId, killReason);
23548        }
23549    }
23550
23551    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23552            String killReason) {
23553        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23554    }
23555
23556    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23557            String killReason) {
23558        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23559            return new PackageFreezer();
23560        } else {
23561            return freezePackage(packageName, userId, killReason);
23562        }
23563    }
23564
23565    /**
23566     * Class that freezes and kills the given package upon creation, and
23567     * unfreezes it upon closing. This is typically used when doing surgery on
23568     * app code/data to prevent the app from running while you're working.
23569     */
23570    private class PackageFreezer implements AutoCloseable {
23571        private final String mPackageName;
23572        private final PackageFreezer[] mChildren;
23573
23574        private final boolean mWeFroze;
23575
23576        private final AtomicBoolean mClosed = new AtomicBoolean();
23577        private final CloseGuard mCloseGuard = CloseGuard.get();
23578
23579        /**
23580         * Create and return a stub freezer that doesn't actually do anything,
23581         * typically used when someone requested
23582         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23583         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23584         */
23585        public PackageFreezer() {
23586            mPackageName = null;
23587            mChildren = null;
23588            mWeFroze = false;
23589            mCloseGuard.open("close");
23590        }
23591
23592        public PackageFreezer(String packageName, int userId, String killReason) {
23593            synchronized (mPackages) {
23594                mPackageName = packageName;
23595                mWeFroze = mFrozenPackages.add(mPackageName);
23596
23597                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23598                if (ps != null) {
23599                    killApplication(ps.name, ps.appId, userId, killReason);
23600                }
23601
23602                final PackageParser.Package p = mPackages.get(packageName);
23603                if (p != null && p.childPackages != null) {
23604                    final int N = p.childPackages.size();
23605                    mChildren = new PackageFreezer[N];
23606                    for (int i = 0; i < N; i++) {
23607                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23608                                userId, killReason);
23609                    }
23610                } else {
23611                    mChildren = null;
23612                }
23613            }
23614            mCloseGuard.open("close");
23615        }
23616
23617        @Override
23618        protected void finalize() throws Throwable {
23619            try {
23620                if (mCloseGuard != null) {
23621                    mCloseGuard.warnIfOpen();
23622                }
23623
23624                close();
23625            } finally {
23626                super.finalize();
23627            }
23628        }
23629
23630        @Override
23631        public void close() {
23632            mCloseGuard.close();
23633            if (mClosed.compareAndSet(false, true)) {
23634                synchronized (mPackages) {
23635                    if (mWeFroze) {
23636                        mFrozenPackages.remove(mPackageName);
23637                    }
23638
23639                    if (mChildren != null) {
23640                        for (PackageFreezer freezer : mChildren) {
23641                            freezer.close();
23642                        }
23643                    }
23644                }
23645            }
23646        }
23647    }
23648
23649    /**
23650     * Verify that given package is currently frozen.
23651     */
23652    private void checkPackageFrozen(String packageName) {
23653        synchronized (mPackages) {
23654            if (!mFrozenPackages.contains(packageName)) {
23655                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23656            }
23657        }
23658    }
23659
23660    @Override
23661    public int movePackage(final String packageName, final String volumeUuid) {
23662        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23663
23664        final int callingUid = Binder.getCallingUid();
23665        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23666        final int moveId = mNextMoveId.getAndIncrement();
23667        mHandler.post(new Runnable() {
23668            @Override
23669            public void run() {
23670                try {
23671                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23672                } catch (PackageManagerException e) {
23673                    Slog.w(TAG, "Failed to move " + packageName, e);
23674                    mMoveCallbacks.notifyStatusChanged(moveId,
23675                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23676                }
23677            }
23678        });
23679        return moveId;
23680    }
23681
23682    private void movePackageInternal(final String packageName, final String volumeUuid,
23683            final int moveId, final int callingUid, UserHandle user)
23684                    throws PackageManagerException {
23685        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23686        final PackageManager pm = mContext.getPackageManager();
23687
23688        final boolean currentAsec;
23689        final String currentVolumeUuid;
23690        final File codeFile;
23691        final String installerPackageName;
23692        final String packageAbiOverride;
23693        final int appId;
23694        final String seinfo;
23695        final String label;
23696        final int targetSdkVersion;
23697        final PackageFreezer freezer;
23698        final int[] installedUserIds;
23699
23700        // reader
23701        synchronized (mPackages) {
23702            final PackageParser.Package pkg = mPackages.get(packageName);
23703            final PackageSetting ps = mSettings.mPackages.get(packageName);
23704            if (pkg == null
23705                    || ps == null
23706                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23707                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23708            }
23709            if (pkg.applicationInfo.isSystemApp()) {
23710                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23711                        "Cannot move system application");
23712            }
23713
23714            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23715            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23716                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23717            if (isInternalStorage && !allow3rdPartyOnInternal) {
23718                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23719                        "3rd party apps are not allowed on internal storage");
23720            }
23721
23722            if (pkg.applicationInfo.isExternalAsec()) {
23723                currentAsec = true;
23724                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23725            } else if (pkg.applicationInfo.isForwardLocked()) {
23726                currentAsec = true;
23727                currentVolumeUuid = "forward_locked";
23728            } else {
23729                currentAsec = false;
23730                currentVolumeUuid = ps.volumeUuid;
23731
23732                final File probe = new File(pkg.codePath);
23733                final File probeOat = new File(probe, "oat");
23734                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23735                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23736                            "Move only supported for modern cluster style installs");
23737                }
23738            }
23739
23740            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23741                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23742                        "Package already moved to " + volumeUuid);
23743            }
23744            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23745                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23746                        "Device admin cannot be moved");
23747            }
23748
23749            if (mFrozenPackages.contains(packageName)) {
23750                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23751                        "Failed to move already frozen package");
23752            }
23753
23754            codeFile = new File(pkg.codePath);
23755            installerPackageName = ps.installerPackageName;
23756            packageAbiOverride = ps.cpuAbiOverrideString;
23757            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23758            seinfo = pkg.applicationInfo.seInfo;
23759            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23760            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23761            freezer = freezePackage(packageName, "movePackageInternal");
23762            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23763        }
23764
23765        final Bundle extras = new Bundle();
23766        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23767        extras.putString(Intent.EXTRA_TITLE, label);
23768        mMoveCallbacks.notifyCreated(moveId, extras);
23769
23770        int installFlags;
23771        final boolean moveCompleteApp;
23772        final File measurePath;
23773
23774        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23775            installFlags = INSTALL_INTERNAL;
23776            moveCompleteApp = !currentAsec;
23777            measurePath = Environment.getDataAppDirectory(volumeUuid);
23778        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23779            installFlags = INSTALL_EXTERNAL;
23780            moveCompleteApp = false;
23781            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23782        } else {
23783            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23784            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23785                    || !volume.isMountedWritable()) {
23786                freezer.close();
23787                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23788                        "Move location not mounted private volume");
23789            }
23790
23791            Preconditions.checkState(!currentAsec);
23792
23793            installFlags = INSTALL_INTERNAL;
23794            moveCompleteApp = true;
23795            measurePath = Environment.getDataAppDirectory(volumeUuid);
23796        }
23797
23798        final PackageStats stats = new PackageStats(null, -1);
23799        synchronized (mInstaller) {
23800            for (int userId : installedUserIds) {
23801                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23802                    freezer.close();
23803                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23804                            "Failed to measure package size");
23805                }
23806            }
23807        }
23808
23809        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23810                + stats.dataSize);
23811
23812        final long startFreeBytes = measurePath.getUsableSpace();
23813        final long sizeBytes;
23814        if (moveCompleteApp) {
23815            sizeBytes = stats.codeSize + stats.dataSize;
23816        } else {
23817            sizeBytes = stats.codeSize;
23818        }
23819
23820        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23821            freezer.close();
23822            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23823                    "Not enough free space to move");
23824        }
23825
23826        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23827
23828        final CountDownLatch installedLatch = new CountDownLatch(1);
23829        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23830            @Override
23831            public void onUserActionRequired(Intent intent) throws RemoteException {
23832                throw new IllegalStateException();
23833            }
23834
23835            @Override
23836            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23837                    Bundle extras) throws RemoteException {
23838                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23839                        + PackageManager.installStatusToString(returnCode, msg));
23840
23841                installedLatch.countDown();
23842                freezer.close();
23843
23844                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23845                switch (status) {
23846                    case PackageInstaller.STATUS_SUCCESS:
23847                        mMoveCallbacks.notifyStatusChanged(moveId,
23848                                PackageManager.MOVE_SUCCEEDED);
23849                        break;
23850                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23851                        mMoveCallbacks.notifyStatusChanged(moveId,
23852                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23853                        break;
23854                    default:
23855                        mMoveCallbacks.notifyStatusChanged(moveId,
23856                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23857                        break;
23858                }
23859            }
23860        };
23861
23862        final MoveInfo move;
23863        if (moveCompleteApp) {
23864            // Kick off a thread to report progress estimates
23865            new Thread() {
23866                @Override
23867                public void run() {
23868                    while (true) {
23869                        try {
23870                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23871                                break;
23872                            }
23873                        } catch (InterruptedException ignored) {
23874                        }
23875
23876                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23877                        final int progress = 10 + (int) MathUtils.constrain(
23878                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23879                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23880                    }
23881                }
23882            }.start();
23883
23884            final String dataAppName = codeFile.getName();
23885            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23886                    dataAppName, appId, seinfo, targetSdkVersion);
23887        } else {
23888            move = null;
23889        }
23890
23891        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23892
23893        final Message msg = mHandler.obtainMessage(INIT_COPY);
23894        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23895        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23896                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23897                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23898                PackageManager.INSTALL_REASON_UNKNOWN);
23899        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23900        msg.obj = params;
23901
23902        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23903                System.identityHashCode(msg.obj));
23904        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23905                System.identityHashCode(msg.obj));
23906
23907        mHandler.sendMessage(msg);
23908    }
23909
23910    @Override
23911    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23912        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23913
23914        final int realMoveId = mNextMoveId.getAndIncrement();
23915        final Bundle extras = new Bundle();
23916        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23917        mMoveCallbacks.notifyCreated(realMoveId, extras);
23918
23919        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23920            @Override
23921            public void onCreated(int moveId, Bundle extras) {
23922                // Ignored
23923            }
23924
23925            @Override
23926            public void onStatusChanged(int moveId, int status, long estMillis) {
23927                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23928            }
23929        };
23930
23931        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23932        storage.setPrimaryStorageUuid(volumeUuid, callback);
23933        return realMoveId;
23934    }
23935
23936    @Override
23937    public int getMoveStatus(int moveId) {
23938        mContext.enforceCallingOrSelfPermission(
23939                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23940        return mMoveCallbacks.mLastStatus.get(moveId);
23941    }
23942
23943    @Override
23944    public void registerMoveCallback(IPackageMoveObserver callback) {
23945        mContext.enforceCallingOrSelfPermission(
23946                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23947        mMoveCallbacks.register(callback);
23948    }
23949
23950    @Override
23951    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23952        mContext.enforceCallingOrSelfPermission(
23953                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23954        mMoveCallbacks.unregister(callback);
23955    }
23956
23957    @Override
23958    public boolean setInstallLocation(int loc) {
23959        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23960                null);
23961        if (getInstallLocation() == loc) {
23962            return true;
23963        }
23964        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23965                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23966            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23967                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23968            return true;
23969        }
23970        return false;
23971   }
23972
23973    @Override
23974    public int getInstallLocation() {
23975        // allow instant app access
23976        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23977                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23978                PackageHelper.APP_INSTALL_AUTO);
23979    }
23980
23981    /** Called by UserManagerService */
23982    void cleanUpUser(UserManagerService userManager, int userHandle) {
23983        synchronized (mPackages) {
23984            mDirtyUsers.remove(userHandle);
23985            mUserNeedsBadging.delete(userHandle);
23986            mSettings.removeUserLPw(userHandle);
23987            mPendingBroadcasts.remove(userHandle);
23988            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23989            removeUnusedPackagesLPw(userManager, userHandle);
23990        }
23991    }
23992
23993    /**
23994     * We're removing userHandle and would like to remove any downloaded packages
23995     * that are no longer in use by any other user.
23996     * @param userHandle the user being removed
23997     */
23998    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23999        final boolean DEBUG_CLEAN_APKS = false;
24000        int [] users = userManager.getUserIds();
24001        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24002        while (psit.hasNext()) {
24003            PackageSetting ps = psit.next();
24004            if (ps.pkg == null) {
24005                continue;
24006            }
24007            final String packageName = ps.pkg.packageName;
24008            // Skip over if system app
24009            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24010                continue;
24011            }
24012            if (DEBUG_CLEAN_APKS) {
24013                Slog.i(TAG, "Checking package " + packageName);
24014            }
24015            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24016            if (keep) {
24017                if (DEBUG_CLEAN_APKS) {
24018                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24019                }
24020            } else {
24021                for (int i = 0; i < users.length; i++) {
24022                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24023                        keep = true;
24024                        if (DEBUG_CLEAN_APKS) {
24025                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24026                                    + users[i]);
24027                        }
24028                        break;
24029                    }
24030                }
24031            }
24032            if (!keep) {
24033                if (DEBUG_CLEAN_APKS) {
24034                    Slog.i(TAG, "  Removing package " + packageName);
24035                }
24036                mHandler.post(new Runnable() {
24037                    public void run() {
24038                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24039                                userHandle, 0);
24040                    } //end run
24041                });
24042            }
24043        }
24044    }
24045
24046    /** Called by UserManagerService */
24047    void createNewUser(int userId, String[] disallowedPackages) {
24048        synchronized (mInstallLock) {
24049            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24050        }
24051        synchronized (mPackages) {
24052            scheduleWritePackageRestrictionsLocked(userId);
24053            scheduleWritePackageListLocked(userId);
24054            applyFactoryDefaultBrowserLPw(userId);
24055            primeDomainVerificationsLPw(userId);
24056        }
24057    }
24058
24059    void onNewUserCreated(final int userId) {
24060        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24061        // If permission review for legacy apps is required, we represent
24062        // dagerous permissions for such apps as always granted runtime
24063        // permissions to keep per user flag state whether review is needed.
24064        // Hence, if a new user is added we have to propagate dangerous
24065        // permission grants for these legacy apps.
24066        if (mPermissionReviewRequired) {
24067            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24068                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24069        }
24070    }
24071
24072    @Override
24073    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24074        mContext.enforceCallingOrSelfPermission(
24075                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24076                "Only package verification agents can read the verifier device identity");
24077
24078        synchronized (mPackages) {
24079            return mSettings.getVerifierDeviceIdentityLPw();
24080        }
24081    }
24082
24083    @Override
24084    public void setPermissionEnforced(String permission, boolean enforced) {
24085        // TODO: Now that we no longer change GID for storage, this should to away.
24086        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24087                "setPermissionEnforced");
24088        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24089            synchronized (mPackages) {
24090                if (mSettings.mReadExternalStorageEnforced == null
24091                        || mSettings.mReadExternalStorageEnforced != enforced) {
24092                    mSettings.mReadExternalStorageEnforced = enforced;
24093                    mSettings.writeLPr();
24094                }
24095            }
24096            // kill any non-foreground processes so we restart them and
24097            // grant/revoke the GID.
24098            final IActivityManager am = ActivityManager.getService();
24099            if (am != null) {
24100                final long token = Binder.clearCallingIdentity();
24101                try {
24102                    am.killProcessesBelowForeground("setPermissionEnforcement");
24103                } catch (RemoteException e) {
24104                } finally {
24105                    Binder.restoreCallingIdentity(token);
24106                }
24107            }
24108        } else {
24109            throw new IllegalArgumentException("No selective enforcement for " + permission);
24110        }
24111    }
24112
24113    @Override
24114    @Deprecated
24115    public boolean isPermissionEnforced(String permission) {
24116        // allow instant applications
24117        return true;
24118    }
24119
24120    @Override
24121    public boolean isStorageLow() {
24122        // allow instant applications
24123        final long token = Binder.clearCallingIdentity();
24124        try {
24125            final DeviceStorageMonitorInternal
24126                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24127            if (dsm != null) {
24128                return dsm.isMemoryLow();
24129            } else {
24130                return false;
24131            }
24132        } finally {
24133            Binder.restoreCallingIdentity(token);
24134        }
24135    }
24136
24137    @Override
24138    public IPackageInstaller getPackageInstaller() {
24139        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24140            return null;
24141        }
24142        return mInstallerService;
24143    }
24144
24145    private boolean userNeedsBadging(int userId) {
24146        int index = mUserNeedsBadging.indexOfKey(userId);
24147        if (index < 0) {
24148            final UserInfo userInfo;
24149            final long token = Binder.clearCallingIdentity();
24150            try {
24151                userInfo = sUserManager.getUserInfo(userId);
24152            } finally {
24153                Binder.restoreCallingIdentity(token);
24154            }
24155            final boolean b;
24156            if (userInfo != null && userInfo.isManagedProfile()) {
24157                b = true;
24158            } else {
24159                b = false;
24160            }
24161            mUserNeedsBadging.put(userId, b);
24162            return b;
24163        }
24164        return mUserNeedsBadging.valueAt(index);
24165    }
24166
24167    @Override
24168    public KeySet getKeySetByAlias(String packageName, String alias) {
24169        if (packageName == null || alias == null) {
24170            return null;
24171        }
24172        synchronized(mPackages) {
24173            final PackageParser.Package pkg = mPackages.get(packageName);
24174            if (pkg == null) {
24175                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24176                throw new IllegalArgumentException("Unknown package: " + packageName);
24177            }
24178            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24179            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24180                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24181                throw new IllegalArgumentException("Unknown package: " + packageName);
24182            }
24183            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24184            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24185        }
24186    }
24187
24188    @Override
24189    public KeySet getSigningKeySet(String packageName) {
24190        if (packageName == null) {
24191            return null;
24192        }
24193        synchronized(mPackages) {
24194            final int callingUid = Binder.getCallingUid();
24195            final int callingUserId = UserHandle.getUserId(callingUid);
24196            final PackageParser.Package pkg = mPackages.get(packageName);
24197            if (pkg == null) {
24198                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24199                throw new IllegalArgumentException("Unknown package: " + packageName);
24200            }
24201            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24202            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24203                // filter and pretend the package doesn't exist
24204                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24205                        + ", uid:" + callingUid);
24206                throw new IllegalArgumentException("Unknown package: " + packageName);
24207            }
24208            if (pkg.applicationInfo.uid != callingUid
24209                    && Process.SYSTEM_UID != callingUid) {
24210                throw new SecurityException("May not access signing KeySet of other apps.");
24211            }
24212            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24213            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24214        }
24215    }
24216
24217    @Override
24218    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24219        final int callingUid = Binder.getCallingUid();
24220        if (getInstantAppPackageName(callingUid) != null) {
24221            return false;
24222        }
24223        if (packageName == null || ks == null) {
24224            return false;
24225        }
24226        synchronized(mPackages) {
24227            final PackageParser.Package pkg = mPackages.get(packageName);
24228            if (pkg == null
24229                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24230                            UserHandle.getUserId(callingUid))) {
24231                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24232                throw new IllegalArgumentException("Unknown package: " + packageName);
24233            }
24234            IBinder ksh = ks.getToken();
24235            if (ksh instanceof KeySetHandle) {
24236                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24237                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24238            }
24239            return false;
24240        }
24241    }
24242
24243    @Override
24244    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24245        final int callingUid = Binder.getCallingUid();
24246        if (getInstantAppPackageName(callingUid) != null) {
24247            return false;
24248        }
24249        if (packageName == null || ks == null) {
24250            return false;
24251        }
24252        synchronized(mPackages) {
24253            final PackageParser.Package pkg = mPackages.get(packageName);
24254            if (pkg == null
24255                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24256                            UserHandle.getUserId(callingUid))) {
24257                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24258                throw new IllegalArgumentException("Unknown package: " + packageName);
24259            }
24260            IBinder ksh = ks.getToken();
24261            if (ksh instanceof KeySetHandle) {
24262                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24263                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24264            }
24265            return false;
24266        }
24267    }
24268
24269    private void deletePackageIfUnusedLPr(final String packageName) {
24270        PackageSetting ps = mSettings.mPackages.get(packageName);
24271        if (ps == null) {
24272            return;
24273        }
24274        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24275            // TODO Implement atomic delete if package is unused
24276            // It is currently possible that the package will be deleted even if it is installed
24277            // after this method returns.
24278            mHandler.post(new Runnable() {
24279                public void run() {
24280                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24281                            0, PackageManager.DELETE_ALL_USERS);
24282                }
24283            });
24284        }
24285    }
24286
24287    /**
24288     * Check and throw if the given before/after packages would be considered a
24289     * downgrade.
24290     */
24291    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24292            throws PackageManagerException {
24293        if (after.versionCode < before.mVersionCode) {
24294            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24295                    "Update version code " + after.versionCode + " is older than current "
24296                    + before.mVersionCode);
24297        } else if (after.versionCode == before.mVersionCode) {
24298            if (after.baseRevisionCode < before.baseRevisionCode) {
24299                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24300                        "Update base revision code " + after.baseRevisionCode
24301                        + " is older than current " + before.baseRevisionCode);
24302            }
24303
24304            if (!ArrayUtils.isEmpty(after.splitNames)) {
24305                for (int i = 0; i < after.splitNames.length; i++) {
24306                    final String splitName = after.splitNames[i];
24307                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24308                    if (j != -1) {
24309                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24310                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24311                                    "Update split " + splitName + " revision code "
24312                                    + after.splitRevisionCodes[i] + " is older than current "
24313                                    + before.splitRevisionCodes[j]);
24314                        }
24315                    }
24316                }
24317            }
24318        }
24319    }
24320
24321    private static class MoveCallbacks extends Handler {
24322        private static final int MSG_CREATED = 1;
24323        private static final int MSG_STATUS_CHANGED = 2;
24324
24325        private final RemoteCallbackList<IPackageMoveObserver>
24326                mCallbacks = new RemoteCallbackList<>();
24327
24328        private final SparseIntArray mLastStatus = new SparseIntArray();
24329
24330        public MoveCallbacks(Looper looper) {
24331            super(looper);
24332        }
24333
24334        public void register(IPackageMoveObserver callback) {
24335            mCallbacks.register(callback);
24336        }
24337
24338        public void unregister(IPackageMoveObserver callback) {
24339            mCallbacks.unregister(callback);
24340        }
24341
24342        @Override
24343        public void handleMessage(Message msg) {
24344            final SomeArgs args = (SomeArgs) msg.obj;
24345            final int n = mCallbacks.beginBroadcast();
24346            for (int i = 0; i < n; i++) {
24347                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24348                try {
24349                    invokeCallback(callback, msg.what, args);
24350                } catch (RemoteException ignored) {
24351                }
24352            }
24353            mCallbacks.finishBroadcast();
24354            args.recycle();
24355        }
24356
24357        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24358                throws RemoteException {
24359            switch (what) {
24360                case MSG_CREATED: {
24361                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24362                    break;
24363                }
24364                case MSG_STATUS_CHANGED: {
24365                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24366                    break;
24367                }
24368            }
24369        }
24370
24371        private void notifyCreated(int moveId, Bundle extras) {
24372            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24373
24374            final SomeArgs args = SomeArgs.obtain();
24375            args.argi1 = moveId;
24376            args.arg2 = extras;
24377            obtainMessage(MSG_CREATED, args).sendToTarget();
24378        }
24379
24380        private void notifyStatusChanged(int moveId, int status) {
24381            notifyStatusChanged(moveId, status, -1);
24382        }
24383
24384        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24385            Slog.v(TAG, "Move " + moveId + " status " + status);
24386
24387            final SomeArgs args = SomeArgs.obtain();
24388            args.argi1 = moveId;
24389            args.argi2 = status;
24390            args.arg3 = estMillis;
24391            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24392
24393            synchronized (mLastStatus) {
24394                mLastStatus.put(moveId, status);
24395            }
24396        }
24397    }
24398
24399    private final static class OnPermissionChangeListeners extends Handler {
24400        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24401
24402        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24403                new RemoteCallbackList<>();
24404
24405        public OnPermissionChangeListeners(Looper looper) {
24406            super(looper);
24407        }
24408
24409        @Override
24410        public void handleMessage(Message msg) {
24411            switch (msg.what) {
24412                case MSG_ON_PERMISSIONS_CHANGED: {
24413                    final int uid = msg.arg1;
24414                    handleOnPermissionsChanged(uid);
24415                } break;
24416            }
24417        }
24418
24419        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24420            mPermissionListeners.register(listener);
24421
24422        }
24423
24424        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24425            mPermissionListeners.unregister(listener);
24426        }
24427
24428        public void onPermissionsChanged(int uid) {
24429            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24430                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24431            }
24432        }
24433
24434        private void handleOnPermissionsChanged(int uid) {
24435            final int count = mPermissionListeners.beginBroadcast();
24436            try {
24437                for (int i = 0; i < count; i++) {
24438                    IOnPermissionsChangeListener callback = mPermissionListeners
24439                            .getBroadcastItem(i);
24440                    try {
24441                        callback.onPermissionsChanged(uid);
24442                    } catch (RemoteException e) {
24443                        Log.e(TAG, "Permission listener is dead", e);
24444                    }
24445                }
24446            } finally {
24447                mPermissionListeners.finishBroadcast();
24448            }
24449        }
24450    }
24451
24452    private class PackageManagerInternalImpl extends PackageManagerInternal {
24453        @Override
24454        public void setLocationPackagesProvider(PackagesProvider provider) {
24455            synchronized (mPackages) {
24456                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24457            }
24458        }
24459
24460        @Override
24461        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24462            synchronized (mPackages) {
24463                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24464            }
24465        }
24466
24467        @Override
24468        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24469            synchronized (mPackages) {
24470                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24471            }
24472        }
24473
24474        @Override
24475        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24476            synchronized (mPackages) {
24477                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24478            }
24479        }
24480
24481        @Override
24482        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24483            synchronized (mPackages) {
24484                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24485            }
24486        }
24487
24488        @Override
24489        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24490            synchronized (mPackages) {
24491                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24492            }
24493        }
24494
24495        @Override
24496        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24497            synchronized (mPackages) {
24498                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24499                        packageName, userId);
24500            }
24501        }
24502
24503        @Override
24504        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24505            synchronized (mPackages) {
24506                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24507                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24508                        packageName, userId);
24509            }
24510        }
24511
24512        @Override
24513        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24514            synchronized (mPackages) {
24515                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24516                        packageName, userId);
24517            }
24518        }
24519
24520        @Override
24521        public void setKeepUninstalledPackages(final List<String> packageList) {
24522            Preconditions.checkNotNull(packageList);
24523            List<String> removedFromList = null;
24524            synchronized (mPackages) {
24525                if (mKeepUninstalledPackages != null) {
24526                    final int packagesCount = mKeepUninstalledPackages.size();
24527                    for (int i = 0; i < packagesCount; i++) {
24528                        String oldPackage = mKeepUninstalledPackages.get(i);
24529                        if (packageList != null && packageList.contains(oldPackage)) {
24530                            continue;
24531                        }
24532                        if (removedFromList == null) {
24533                            removedFromList = new ArrayList<>();
24534                        }
24535                        removedFromList.add(oldPackage);
24536                    }
24537                }
24538                mKeepUninstalledPackages = new ArrayList<>(packageList);
24539                if (removedFromList != null) {
24540                    final int removedCount = removedFromList.size();
24541                    for (int i = 0; i < removedCount; i++) {
24542                        deletePackageIfUnusedLPr(removedFromList.get(i));
24543                    }
24544                }
24545            }
24546        }
24547
24548        @Override
24549        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24550            synchronized (mPackages) {
24551                // If we do not support permission review, done.
24552                if (!mPermissionReviewRequired) {
24553                    return false;
24554                }
24555
24556                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24557                if (packageSetting == null) {
24558                    return false;
24559                }
24560
24561                // Permission review applies only to apps not supporting the new permission model.
24562                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24563                    return false;
24564                }
24565
24566                // Legacy apps have the permission and get user consent on launch.
24567                PermissionsState permissionsState = packageSetting.getPermissionsState();
24568                return permissionsState.isPermissionReviewRequired(userId);
24569            }
24570        }
24571
24572        @Override
24573        public PackageInfo getPackageInfo(
24574                String packageName, int flags, int filterCallingUid, int userId) {
24575            return PackageManagerService.this
24576                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24577                            flags, filterCallingUid, userId);
24578        }
24579
24580        @Override
24581        public ApplicationInfo getApplicationInfo(
24582                String packageName, int flags, int filterCallingUid, int userId) {
24583            return PackageManagerService.this
24584                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24585        }
24586
24587        @Override
24588        public ActivityInfo getActivityInfo(
24589                ComponentName component, int flags, int filterCallingUid, int userId) {
24590            return PackageManagerService.this
24591                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24592        }
24593
24594        @Override
24595        public List<ResolveInfo> queryIntentActivities(
24596                Intent intent, int flags, int filterCallingUid, int userId) {
24597            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24598            return PackageManagerService.this
24599                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24600                            userId, false /*resolveForStart*/);
24601        }
24602
24603        @Override
24604        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24605                int userId) {
24606            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24607        }
24608
24609        @Override
24610        public void setDeviceAndProfileOwnerPackages(
24611                int deviceOwnerUserId, String deviceOwnerPackage,
24612                SparseArray<String> profileOwnerPackages) {
24613            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24614                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24615        }
24616
24617        @Override
24618        public boolean isPackageDataProtected(int userId, String packageName) {
24619            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24620        }
24621
24622        @Override
24623        public boolean isPackageEphemeral(int userId, String packageName) {
24624            synchronized (mPackages) {
24625                final PackageSetting ps = mSettings.mPackages.get(packageName);
24626                return ps != null ? ps.getInstantApp(userId) : false;
24627            }
24628        }
24629
24630        @Override
24631        public boolean wasPackageEverLaunched(String packageName, int userId) {
24632            synchronized (mPackages) {
24633                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24634            }
24635        }
24636
24637        @Override
24638        public void grantRuntimePermission(String packageName, String name, int userId,
24639                boolean overridePolicy) {
24640            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24641                    overridePolicy);
24642        }
24643
24644        @Override
24645        public void revokeRuntimePermission(String packageName, String name, int userId,
24646                boolean overridePolicy) {
24647            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24648                    overridePolicy);
24649        }
24650
24651        @Override
24652        public String getNameForUid(int uid) {
24653            return PackageManagerService.this.getNameForUid(uid);
24654        }
24655
24656        @Override
24657        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24658                Intent origIntent, String resolvedType, String callingPackage,
24659                Bundle verificationBundle, int userId) {
24660            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24661                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24662                    userId);
24663        }
24664
24665        @Override
24666        public void grantEphemeralAccess(int userId, Intent intent,
24667                int targetAppId, int ephemeralAppId) {
24668            synchronized (mPackages) {
24669                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24670                        targetAppId, ephemeralAppId);
24671            }
24672        }
24673
24674        @Override
24675        public boolean isInstantAppInstallerComponent(ComponentName component) {
24676            synchronized (mPackages) {
24677                return mInstantAppInstallerActivity != null
24678                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24679            }
24680        }
24681
24682        @Override
24683        public void pruneInstantApps() {
24684            mInstantAppRegistry.pruneInstantApps();
24685        }
24686
24687        @Override
24688        public String getSetupWizardPackageName() {
24689            return mSetupWizardPackage;
24690        }
24691
24692        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24693            if (policy != null) {
24694                mExternalSourcesPolicy = policy;
24695            }
24696        }
24697
24698        @Override
24699        public boolean isPackagePersistent(String packageName) {
24700            synchronized (mPackages) {
24701                PackageParser.Package pkg = mPackages.get(packageName);
24702                return pkg != null
24703                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24704                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24705                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24706                        : false;
24707            }
24708        }
24709
24710        @Override
24711        public List<PackageInfo> getOverlayPackages(int userId) {
24712            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24713            synchronized (mPackages) {
24714                for (PackageParser.Package p : mPackages.values()) {
24715                    if (p.mOverlayTarget != null) {
24716                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24717                        if (pkg != null) {
24718                            overlayPackages.add(pkg);
24719                        }
24720                    }
24721                }
24722            }
24723            return overlayPackages;
24724        }
24725
24726        @Override
24727        public List<String> getTargetPackageNames(int userId) {
24728            List<String> targetPackages = new ArrayList<>();
24729            synchronized (mPackages) {
24730                for (PackageParser.Package p : mPackages.values()) {
24731                    if (p.mOverlayTarget == null) {
24732                        targetPackages.add(p.packageName);
24733                    }
24734                }
24735            }
24736            return targetPackages;
24737        }
24738
24739        @Override
24740        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24741                @Nullable List<String> overlayPackageNames) {
24742            synchronized (mPackages) {
24743                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24744                    Slog.e(TAG, "failed to find package " + targetPackageName);
24745                    return false;
24746                }
24747
24748                ArrayList<String> paths = null;
24749                if (overlayPackageNames != null) {
24750                    final int N = overlayPackageNames.size();
24751                    paths = new ArrayList<>(N);
24752                    for (int i = 0; i < N; i++) {
24753                        final String packageName = overlayPackageNames.get(i);
24754                        final PackageParser.Package pkg = mPackages.get(packageName);
24755                        if (pkg == null) {
24756                            Slog.e(TAG, "failed to find package " + packageName);
24757                            return false;
24758                        }
24759                        paths.add(pkg.baseCodePath);
24760                    }
24761                }
24762
24763                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
24764                    mEnabledOverlayPaths.get(userId);
24765                if (userSpecificOverlays == null) {
24766                    userSpecificOverlays = new ArrayMap<>();
24767                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
24768                }
24769
24770                if (paths != null && paths.size() > 0) {
24771                    userSpecificOverlays.put(targetPackageName, paths);
24772                } else {
24773                    userSpecificOverlays.remove(targetPackageName);
24774                }
24775                return true;
24776            }
24777        }
24778
24779        @Override
24780        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24781                int flags, int userId) {
24782            return resolveIntentInternal(
24783                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24784        }
24785
24786        @Override
24787        public ResolveInfo resolveService(Intent intent, String resolvedType,
24788                int flags, int userId, int callingUid) {
24789            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24790        }
24791
24792        @Override
24793        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24794            synchronized (mPackages) {
24795                mIsolatedOwners.put(isolatedUid, ownerUid);
24796            }
24797        }
24798
24799        @Override
24800        public void removeIsolatedUid(int isolatedUid) {
24801            synchronized (mPackages) {
24802                mIsolatedOwners.delete(isolatedUid);
24803            }
24804        }
24805
24806        @Override
24807        public int getUidTargetSdkVersion(int uid) {
24808            synchronized (mPackages) {
24809                return getUidTargetSdkVersionLockedLPr(uid);
24810            }
24811        }
24812
24813        @Override
24814        public boolean canAccessInstantApps(int callingUid, int userId) {
24815            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24816        }
24817    }
24818
24819    @Override
24820    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24821        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24822        synchronized (mPackages) {
24823            final long identity = Binder.clearCallingIdentity();
24824            try {
24825                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24826                        packageNames, userId);
24827            } finally {
24828                Binder.restoreCallingIdentity(identity);
24829            }
24830        }
24831    }
24832
24833    @Override
24834    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24835        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24836        synchronized (mPackages) {
24837            final long identity = Binder.clearCallingIdentity();
24838            try {
24839                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24840                        packageNames, userId);
24841            } finally {
24842                Binder.restoreCallingIdentity(identity);
24843            }
24844        }
24845    }
24846
24847    private static void enforceSystemOrPhoneCaller(String tag) {
24848        int callingUid = Binder.getCallingUid();
24849        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24850            throw new SecurityException(
24851                    "Cannot call " + tag + " from UID " + callingUid);
24852        }
24853    }
24854
24855    boolean isHistoricalPackageUsageAvailable() {
24856        return mPackageUsage.isHistoricalPackageUsageAvailable();
24857    }
24858
24859    /**
24860     * Return a <b>copy</b> of the collection of packages known to the package manager.
24861     * @return A copy of the values of mPackages.
24862     */
24863    Collection<PackageParser.Package> getPackages() {
24864        synchronized (mPackages) {
24865            return new ArrayList<>(mPackages.values());
24866        }
24867    }
24868
24869    /**
24870     * Logs process start information (including base APK hash) to the security log.
24871     * @hide
24872     */
24873    @Override
24874    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24875            String apkFile, int pid) {
24876        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24877            return;
24878        }
24879        if (!SecurityLog.isLoggingEnabled()) {
24880            return;
24881        }
24882        Bundle data = new Bundle();
24883        data.putLong("startTimestamp", System.currentTimeMillis());
24884        data.putString("processName", processName);
24885        data.putInt("uid", uid);
24886        data.putString("seinfo", seinfo);
24887        data.putString("apkFile", apkFile);
24888        data.putInt("pid", pid);
24889        Message msg = mProcessLoggingHandler.obtainMessage(
24890                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24891        msg.setData(data);
24892        mProcessLoggingHandler.sendMessage(msg);
24893    }
24894
24895    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24896        return mCompilerStats.getPackageStats(pkgName);
24897    }
24898
24899    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24900        return getOrCreateCompilerPackageStats(pkg.packageName);
24901    }
24902
24903    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24904        return mCompilerStats.getOrCreatePackageStats(pkgName);
24905    }
24906
24907    public void deleteCompilerPackageStats(String pkgName) {
24908        mCompilerStats.deletePackageStats(pkgName);
24909    }
24910
24911    @Override
24912    public int getInstallReason(String packageName, int userId) {
24913        final int callingUid = Binder.getCallingUid();
24914        enforceCrossUserPermission(callingUid, userId,
24915                true /* requireFullPermission */, false /* checkShell */,
24916                "get install reason");
24917        synchronized (mPackages) {
24918            final PackageSetting ps = mSettings.mPackages.get(packageName);
24919            if (filterAppAccessLPr(ps, callingUid, userId)) {
24920                return PackageManager.INSTALL_REASON_UNKNOWN;
24921            }
24922            if (ps != null) {
24923                return ps.getInstallReason(userId);
24924            }
24925        }
24926        return PackageManager.INSTALL_REASON_UNKNOWN;
24927    }
24928
24929    @Override
24930    public boolean canRequestPackageInstalls(String packageName, int userId) {
24931        return canRequestPackageInstallsInternal(packageName, 0, userId,
24932                true /* throwIfPermNotDeclared*/);
24933    }
24934
24935    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24936            boolean throwIfPermNotDeclared) {
24937        int callingUid = Binder.getCallingUid();
24938        int uid = getPackageUid(packageName, 0, userId);
24939        if (callingUid != uid && callingUid != Process.ROOT_UID
24940                && callingUid != Process.SYSTEM_UID) {
24941            throw new SecurityException(
24942                    "Caller uid " + callingUid + " does not own package " + packageName);
24943        }
24944        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24945        if (info == null) {
24946            return false;
24947        }
24948        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24949            return false;
24950        }
24951        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24952        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24953        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24954            if (throwIfPermNotDeclared) {
24955                throw new SecurityException("Need to declare " + appOpPermission
24956                        + " to call this api");
24957            } else {
24958                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24959                return false;
24960            }
24961        }
24962        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24963            return false;
24964        }
24965        if (mExternalSourcesPolicy != null) {
24966            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24967            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24968                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24969            }
24970        }
24971        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24972    }
24973
24974    @Override
24975    public ComponentName getInstantAppResolverSettingsComponent() {
24976        return mInstantAppResolverSettingsComponent;
24977    }
24978
24979    @Override
24980    public ComponentName getInstantAppInstallerComponent() {
24981        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24982            return null;
24983        }
24984        return mInstantAppInstallerActivity == null
24985                ? null : mInstantAppInstallerActivity.getComponentName();
24986    }
24987
24988    @Override
24989    public String getInstantAppAndroidId(String packageName, int userId) {
24990        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24991                "getInstantAppAndroidId");
24992        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24993                true /* requireFullPermission */, false /* checkShell */,
24994                "getInstantAppAndroidId");
24995        // Make sure the target is an Instant App.
24996        if (!isInstantApp(packageName, userId)) {
24997            return null;
24998        }
24999        synchronized (mPackages) {
25000            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25001        }
25002    }
25003}
25004
25005interface PackageSender {
25006    void sendPackageBroadcast(final String action, final String pkg,
25007        final Bundle extras, final int flags, final String targetPkg,
25008        final IIntentReceiver finishedReceiver, final int[] userIds);
25009    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
25010        int appId, int... userIds);
25011}
25012