PackageManagerService.java revision 6044d6ccaeb7dcc60d747113f77e0aa131211074
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_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
106
107import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
108
109import android.Manifest;
110import android.annotation.IntDef;
111import android.annotation.NonNull;
112import android.annotation.Nullable;
113import android.app.ActivityManager;
114import android.app.AppOpsManager;
115import android.app.IActivityManager;
116import android.app.ResourcesManager;
117import android.app.admin.IDevicePolicyManager;
118import android.app.admin.SecurityLog;
119import android.app.backup.IBackupManager;
120import android.content.BroadcastReceiver;
121import android.content.ComponentName;
122import android.content.ContentResolver;
123import android.content.Context;
124import android.content.IIntentReceiver;
125import android.content.Intent;
126import android.content.IntentFilter;
127import android.content.IntentSender;
128import android.content.IntentSender.SendIntentException;
129import android.content.ServiceConnection;
130import android.content.pm.ActivityInfo;
131import android.content.pm.ApplicationInfo;
132import android.content.pm.AppsQueryHelper;
133import android.content.pm.AuxiliaryResolveInfo;
134import android.content.pm.ChangedPackages;
135import android.content.pm.ComponentInfo;
136import android.content.pm.FallbackCategoryProvider;
137import android.content.pm.FeatureInfo;
138import android.content.pm.IDexModuleRegisterCallback;
139import android.content.pm.IOnPermissionsChangeListener;
140import android.content.pm.IPackageDataObserver;
141import android.content.pm.IPackageDeleteObserver;
142import android.content.pm.IPackageDeleteObserver2;
143import android.content.pm.IPackageInstallObserver2;
144import android.content.pm.IPackageInstaller;
145import android.content.pm.IPackageManager;
146import android.content.pm.IPackageMoveObserver;
147import android.content.pm.IPackageStatsObserver;
148import android.content.pm.InstantAppInfo;
149import android.content.pm.InstantAppRequest;
150import android.content.pm.InstantAppResolveInfo;
151import android.content.pm.InstrumentationInfo;
152import android.content.pm.IntentFilterVerificationInfo;
153import android.content.pm.KeySet;
154import android.content.pm.PackageCleanItem;
155import android.content.pm.PackageInfo;
156import android.content.pm.PackageInfoLite;
157import android.content.pm.PackageInstaller;
158import android.content.pm.PackageManager;
159import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
160import android.content.pm.PackageManagerInternal;
161import android.content.pm.PackageParser;
162import android.content.pm.PackageParser.ActivityIntentInfo;
163import android.content.pm.PackageParser.PackageLite;
164import android.content.pm.PackageParser.PackageParserException;
165import android.content.pm.PackageStats;
166import android.content.pm.PackageUserState;
167import android.content.pm.ParceledListSlice;
168import android.content.pm.PermissionGroupInfo;
169import android.content.pm.PermissionInfo;
170import android.content.pm.ProviderInfo;
171import android.content.pm.ResolveInfo;
172import android.content.pm.ServiceInfo;
173import android.content.pm.SharedLibraryInfo;
174import android.content.pm.Signature;
175import android.content.pm.UserInfo;
176import android.content.pm.VerifierDeviceIdentity;
177import android.content.pm.VerifierInfo;
178import android.content.pm.VersionedPackage;
179import android.content.res.Resources;
180import android.database.ContentObserver;
181import android.graphics.Bitmap;
182import android.hardware.display.DisplayManager;
183import android.net.Uri;
184import android.os.Binder;
185import android.os.Build;
186import android.os.Bundle;
187import android.os.Debug;
188import android.os.Environment;
189import android.os.Environment.UserEnvironment;
190import android.os.FileUtils;
191import android.os.Handler;
192import android.os.IBinder;
193import android.os.Looper;
194import android.os.Message;
195import android.os.Parcel;
196import android.os.ParcelFileDescriptor;
197import android.os.PatternMatcher;
198import android.os.Process;
199import android.os.RemoteCallbackList;
200import android.os.RemoteException;
201import android.os.ResultReceiver;
202import android.os.SELinux;
203import android.os.ServiceManager;
204import android.os.ShellCallback;
205import android.os.SystemClock;
206import android.os.SystemProperties;
207import android.os.Trace;
208import android.os.UserHandle;
209import android.os.UserManager;
210import android.os.UserManagerInternal;
211import android.os.storage.IStorageManager;
212import android.os.storage.StorageEventListener;
213import android.os.storage.StorageManager;
214import android.os.storage.StorageManagerInternal;
215import android.os.storage.VolumeInfo;
216import android.os.storage.VolumeRecord;
217import android.provider.Settings.Global;
218import android.provider.Settings.Secure;
219import android.security.KeyStore;
220import android.security.SystemKeyStore;
221import android.service.pm.PackageServiceDumpProto;
222import android.system.ErrnoException;
223import android.system.Os;
224import android.text.TextUtils;
225import android.text.format.DateUtils;
226import android.util.ArrayMap;
227import android.util.ArraySet;
228import android.util.Base64;
229import android.util.BootTimingsTraceLog;
230import android.util.DisplayMetrics;
231import android.util.EventLog;
232import android.util.ExceptionUtils;
233import android.util.Log;
234import android.util.LogPrinter;
235import android.util.MathUtils;
236import android.util.PackageUtils;
237import android.util.Pair;
238import android.util.PrintStreamPrinter;
239import android.util.Slog;
240import android.util.SparseArray;
241import android.util.SparseBooleanArray;
242import android.util.SparseIntArray;
243import android.util.Xml;
244import android.util.jar.StrictJarFile;
245import android.util.proto.ProtoOutputStream;
246import android.view.Display;
247
248import com.android.internal.R;
249import com.android.internal.annotations.GuardedBy;
250import com.android.internal.app.IMediaContainerService;
251import com.android.internal.app.ResolverActivity;
252import com.android.internal.content.NativeLibraryHelper;
253import com.android.internal.content.PackageHelper;
254import com.android.internal.logging.MetricsLogger;
255import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
256import com.android.internal.os.IParcelFileDescriptorFactory;
257import com.android.internal.os.RoSystemProperties;
258import com.android.internal.os.SomeArgs;
259import com.android.internal.os.Zygote;
260import com.android.internal.telephony.CarrierAppUtils;
261import com.android.internal.util.ArrayUtils;
262import com.android.internal.util.ConcurrentUtils;
263import com.android.internal.util.DumpUtils;
264import com.android.internal.util.FastPrintWriter;
265import com.android.internal.util.FastXmlSerializer;
266import com.android.internal.util.IndentingPrintWriter;
267import com.android.internal.util.Preconditions;
268import com.android.internal.util.XmlUtils;
269import com.android.server.AttributeCache;
270import com.android.server.DeviceIdleController;
271import com.android.server.EventLogTags;
272import com.android.server.FgThread;
273import com.android.server.IntentResolver;
274import com.android.server.LocalServices;
275import com.android.server.LockGuard;
276import com.android.server.ServiceThread;
277import com.android.server.SystemConfig;
278import com.android.server.SystemServerInitThreadPool;
279import com.android.server.Watchdog;
280import com.android.server.net.NetworkPolicyManagerInternal;
281import com.android.server.pm.Installer.InstallerException;
282import com.android.server.pm.PermissionsState.PermissionState;
283import com.android.server.pm.Settings.DatabaseVersion;
284import com.android.server.pm.Settings.VersionInfo;
285import com.android.server.pm.dex.DexManager;
286import com.android.server.storage.DeviceStorageMonitorInternal;
287
288import dalvik.system.CloseGuard;
289import dalvik.system.DexFile;
290import dalvik.system.VMRuntime;
291
292import libcore.io.IoUtils;
293import libcore.util.EmptyArray;
294
295import org.xmlpull.v1.XmlPullParser;
296import org.xmlpull.v1.XmlPullParserException;
297import org.xmlpull.v1.XmlSerializer;
298
299import java.io.BufferedOutputStream;
300import java.io.BufferedReader;
301import java.io.ByteArrayInputStream;
302import java.io.ByteArrayOutputStream;
303import java.io.File;
304import java.io.FileDescriptor;
305import java.io.FileInputStream;
306import java.io.FileOutputStream;
307import java.io.FileReader;
308import java.io.FilenameFilter;
309import java.io.IOException;
310import java.io.PrintWriter;
311import java.lang.annotation.Retention;
312import java.lang.annotation.RetentionPolicy;
313import java.nio.charset.StandardCharsets;
314import java.security.DigestInputStream;
315import java.security.MessageDigest;
316import java.security.NoSuchAlgorithmException;
317import java.security.PublicKey;
318import java.security.SecureRandom;
319import java.security.cert.Certificate;
320import java.security.cert.CertificateEncodingException;
321import java.security.cert.CertificateException;
322import java.text.SimpleDateFormat;
323import java.util.ArrayList;
324import java.util.Arrays;
325import java.util.Collection;
326import java.util.Collections;
327import java.util.Comparator;
328import java.util.Date;
329import java.util.HashMap;
330import java.util.HashSet;
331import java.util.Iterator;
332import java.util.List;
333import java.util.Map;
334import java.util.Objects;
335import java.util.Set;
336import java.util.concurrent.CountDownLatch;
337import java.util.concurrent.Future;
338import java.util.concurrent.TimeUnit;
339import java.util.concurrent.atomic.AtomicBoolean;
340import java.util.concurrent.atomic.AtomicInteger;
341
342/**
343 * Keep track of all those APKs everywhere.
344 * <p>
345 * Internally there are two important locks:
346 * <ul>
347 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
348 * and other related state. It is a fine-grained lock that should only be held
349 * momentarily, as it's one of the most contended locks in the system.
350 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
351 * operations typically involve heavy lifting of application data on disk. Since
352 * {@code installd} is single-threaded, and it's operations can often be slow,
353 * this lock should never be acquired while already holding {@link #mPackages}.
354 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
355 * holding {@link #mInstallLock}.
356 * </ul>
357 * Many internal methods rely on the caller to hold the appropriate locks, and
358 * this contract is expressed through method name suffixes:
359 * <ul>
360 * <li>fooLI(): the caller must hold {@link #mInstallLock}
361 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
362 * being modified must be frozen
363 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
364 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
365 * </ul>
366 * <p>
367 * Because this class is very central to the platform's security; please run all
368 * CTS and unit tests whenever making modifications:
369 *
370 * <pre>
371 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
372 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
373 * </pre>
374 */
375public class PackageManagerService extends IPackageManager.Stub
376        implements PackageSender {
377    static final String TAG = "PackageManager";
378    static final boolean DEBUG_SETTINGS = false;
379    static final boolean DEBUG_PREFERRED = false;
380    static final boolean DEBUG_UPGRADE = false;
381    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
382    private static final boolean DEBUG_BACKUP = false;
383    private static final boolean DEBUG_INSTALL = false;
384    private static final boolean DEBUG_REMOVE = false;
385    private static final boolean DEBUG_BROADCASTS = false;
386    private static final boolean DEBUG_SHOW_INFO = false;
387    private static final boolean DEBUG_PACKAGE_INFO = false;
388    private static final boolean DEBUG_INTENT_MATCHING = false;
389    private static final boolean DEBUG_PACKAGE_SCANNING = false;
390    private static final boolean DEBUG_VERIFY = false;
391    private static final boolean DEBUG_FILTERS = false;
392    private static final boolean DEBUG_PERMISSIONS = false;
393    private static final boolean DEBUG_SHARED_LIBRARIES = false;
394
395    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
396    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
397    // user, but by default initialize to this.
398    public static final boolean DEBUG_DEXOPT = false;
399
400    private static final boolean DEBUG_ABI_SELECTION = false;
401    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
402    private static final boolean DEBUG_TRIAGED_MISSING = false;
403    private static final boolean DEBUG_APP_DATA = false;
404
405    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
406    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
407
408    private static final boolean HIDE_EPHEMERAL_APIS = false;
409
410    private static final boolean ENABLE_FREE_CACHE_V2 =
411            SystemProperties.getBoolean("fw.free_cache_v2", true);
412
413    private static final int RADIO_UID = Process.PHONE_UID;
414    private static final int LOG_UID = Process.LOG_UID;
415    private static final int NFC_UID = Process.NFC_UID;
416    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
417    private static final int SHELL_UID = Process.SHELL_UID;
418
419    // Cap the size of permission trees that 3rd party apps can define
420    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
421
422    // Suffix used during package installation when copying/moving
423    // package apks to install directory.
424    private static final String INSTALL_PACKAGE_SUFFIX = "-";
425
426    static final int SCAN_NO_DEX = 1<<1;
427    static final int SCAN_FORCE_DEX = 1<<2;
428    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
429    static final int SCAN_NEW_INSTALL = 1<<4;
430    static final int SCAN_UPDATE_TIME = 1<<5;
431    static final int SCAN_BOOTING = 1<<6;
432    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
433    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
434    static final int SCAN_REPLACING = 1<<9;
435    static final int SCAN_REQUIRE_KNOWN = 1<<10;
436    static final int SCAN_MOVE = 1<<11;
437    static final int SCAN_INITIAL = 1<<12;
438    static final int SCAN_CHECK_ONLY = 1<<13;
439    static final int SCAN_DONT_KILL_APP = 1<<14;
440    static final int SCAN_IGNORE_FROZEN = 1<<15;
441    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
442    static final int SCAN_AS_INSTANT_APP = 1<<17;
443    static final int SCAN_AS_FULL_APP = 1<<18;
444    /** Should not be with the scan flags */
445    static final int FLAGS_REMOVE_CHATTY = 1<<31;
446
447    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
448
449    private static final int[] EMPTY_INT_ARRAY = new int[0];
450
451    private static final int TYPE_UNKNOWN = 0;
452    private static final int TYPE_ACTIVITY = 1;
453    private static final int TYPE_RECEIVER = 2;
454    private static final int TYPE_SERVICE = 3;
455    private static final int TYPE_PROVIDER = 4;
456    @IntDef(prefix = { "TYPE_" }, value = {
457            TYPE_UNKNOWN,
458            TYPE_ACTIVITY,
459            TYPE_RECEIVER,
460            TYPE_SERVICE,
461            TYPE_PROVIDER,
462    })
463    @Retention(RetentionPolicy.SOURCE)
464    public @interface ComponentType {}
465
466    /**
467     * Timeout (in milliseconds) after which the watchdog should declare that
468     * our handler thread is wedged.  The usual default for such things is one
469     * minute but we sometimes do very lengthy I/O operations on this thread,
470     * such as installing multi-gigabyte applications, so ours needs to be longer.
471     */
472    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
473
474    /**
475     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
476     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
477     * settings entry if available, otherwise we use the hardcoded default.  If it's been
478     * more than this long since the last fstrim, we force one during the boot sequence.
479     *
480     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
481     * one gets run at the next available charging+idle time.  This final mandatory
482     * no-fstrim check kicks in only of the other scheduling criteria is never met.
483     */
484    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
485
486    /**
487     * Whether verification is enabled by default.
488     */
489    private static final boolean DEFAULT_VERIFY_ENABLE = true;
490
491    /**
492     * The default maximum time to wait for the verification agent to return in
493     * milliseconds.
494     */
495    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
496
497    /**
498     * The default response for package verification timeout.
499     *
500     * This can be either PackageManager.VERIFICATION_ALLOW or
501     * PackageManager.VERIFICATION_REJECT.
502     */
503    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
504
505    static final String PLATFORM_PACKAGE_NAME = "android";
506
507    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
508
509    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
510            DEFAULT_CONTAINER_PACKAGE,
511            "com.android.defcontainer.DefaultContainerService");
512
513    private static final String KILL_APP_REASON_GIDS_CHANGED =
514            "permission grant or revoke changed gids";
515
516    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
517            "permissions revoked";
518
519    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
520
521    private static final String PACKAGE_SCHEME = "package";
522
523    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
524
525    /** Permission grant: not grant the permission. */
526    private static final int GRANT_DENIED = 1;
527
528    /** Permission grant: grant the permission as an install permission. */
529    private static final int GRANT_INSTALL = 2;
530
531    /** Permission grant: grant the permission as a runtime one. */
532    private static final int GRANT_RUNTIME = 3;
533
534    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
535    private static final int GRANT_UPGRADE = 4;
536
537    /** Canonical intent used to identify what counts as a "web browser" app */
538    private static final Intent sBrowserIntent;
539    static {
540        sBrowserIntent = new Intent();
541        sBrowserIntent.setAction(Intent.ACTION_VIEW);
542        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
543        sBrowserIntent.setData(Uri.parse("http:"));
544    }
545
546    /**
547     * The set of all protected actions [i.e. those actions for which a high priority
548     * intent filter is disallowed].
549     */
550    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
551    static {
552        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
553        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
554        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
555        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
556    }
557
558    // Compilation reasons.
559    public static final int REASON_FIRST_BOOT = 0;
560    public static final int REASON_BOOT = 1;
561    public static final int REASON_INSTALL = 2;
562    public static final int REASON_BACKGROUND_DEXOPT = 3;
563    public static final int REASON_AB_OTA = 4;
564
565    public static final int REASON_LAST = REASON_AB_OTA;
566
567    /** All dangerous permission names in the same order as the events in MetricsEvent */
568    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
569            Manifest.permission.READ_CALENDAR,
570            Manifest.permission.WRITE_CALENDAR,
571            Manifest.permission.CAMERA,
572            Manifest.permission.READ_CONTACTS,
573            Manifest.permission.WRITE_CONTACTS,
574            Manifest.permission.GET_ACCOUNTS,
575            Manifest.permission.ACCESS_FINE_LOCATION,
576            Manifest.permission.ACCESS_COARSE_LOCATION,
577            Manifest.permission.RECORD_AUDIO,
578            Manifest.permission.READ_PHONE_STATE,
579            Manifest.permission.CALL_PHONE,
580            Manifest.permission.READ_CALL_LOG,
581            Manifest.permission.WRITE_CALL_LOG,
582            Manifest.permission.ADD_VOICEMAIL,
583            Manifest.permission.USE_SIP,
584            Manifest.permission.PROCESS_OUTGOING_CALLS,
585            Manifest.permission.READ_CELL_BROADCASTS,
586            Manifest.permission.BODY_SENSORS,
587            Manifest.permission.SEND_SMS,
588            Manifest.permission.RECEIVE_SMS,
589            Manifest.permission.READ_SMS,
590            Manifest.permission.RECEIVE_WAP_PUSH,
591            Manifest.permission.RECEIVE_MMS,
592            Manifest.permission.READ_EXTERNAL_STORAGE,
593            Manifest.permission.WRITE_EXTERNAL_STORAGE,
594            Manifest.permission.READ_PHONE_NUMBERS,
595            Manifest.permission.ANSWER_PHONE_CALLS);
596
597
598    /**
599     * Version number for the package parser cache. Increment this whenever the format or
600     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
601     */
602    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
603
604    /**
605     * Whether the package parser cache is enabled.
606     */
607    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
608
609    final ServiceThread mHandlerThread;
610
611    final PackageHandler mHandler;
612
613    private final ProcessLoggingHandler mProcessLoggingHandler;
614
615    /**
616     * Messages for {@link #mHandler} that need to wait for system ready before
617     * being dispatched.
618     */
619    private ArrayList<Message> mPostSystemReadyMessages;
620
621    final int mSdkVersion = Build.VERSION.SDK_INT;
622
623    final Context mContext;
624    final boolean mFactoryTest;
625    final boolean mOnlyCore;
626    final DisplayMetrics mMetrics;
627    final int mDefParseFlags;
628    final String[] mSeparateProcesses;
629    final boolean mIsUpgrade;
630    final boolean mIsPreNUpgrade;
631    final boolean mIsPreNMR1Upgrade;
632
633    // Have we told the Activity Manager to whitelist the default container service by uid yet?
634    @GuardedBy("mPackages")
635    boolean mDefaultContainerWhitelisted = false;
636
637    @GuardedBy("mPackages")
638    private boolean mDexOptDialogShown;
639
640    /** The location for ASEC container files on internal storage. */
641    final String mAsecInternalPath;
642
643    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
644    // LOCK HELD.  Can be called with mInstallLock held.
645    @GuardedBy("mInstallLock")
646    final Installer mInstaller;
647
648    /** Directory where installed third-party apps stored */
649    final File mAppInstallDir;
650
651    /**
652     * Directory to which applications installed internally have their
653     * 32 bit native libraries copied.
654     */
655    private File mAppLib32InstallDir;
656
657    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
658    // apps.
659    final File mDrmAppPrivateInstallDir;
660
661    // ----------------------------------------------------------------
662
663    // Lock for state used when installing and doing other long running
664    // operations.  Methods that must be called with this lock held have
665    // the suffix "LI".
666    final Object mInstallLock = new Object();
667
668    // ----------------------------------------------------------------
669
670    // Keys are String (package name), values are Package.  This also serves
671    // as the lock for the global state.  Methods that must be called with
672    // this lock held have the prefix "LP".
673    @GuardedBy("mPackages")
674    final ArrayMap<String, PackageParser.Package> mPackages =
675            new ArrayMap<String, PackageParser.Package>();
676
677    final ArrayMap<String, Set<String>> mKnownCodebase =
678            new ArrayMap<String, Set<String>>();
679
680    // Keys are isolated uids and values are the uid of the application
681    // that created the isolated proccess.
682    @GuardedBy("mPackages")
683    final SparseIntArray mIsolatedOwners = new SparseIntArray();
684
685    /**
686     * Tracks new system packages [received in an OTA] that we expect to
687     * find updated user-installed versions. Keys are package name, values
688     * are package location.
689     */
690    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
691    /**
692     * Tracks high priority intent filters for protected actions. During boot, certain
693     * filter actions are protected and should never be allowed to have a high priority
694     * intent filter for them. However, there is one, and only one exception -- the
695     * setup wizard. It must be able to define a high priority intent filter for these
696     * actions to ensure there are no escapes from the wizard. We need to delay processing
697     * of these during boot as we need to look at all of the system packages in order
698     * to know which component is the setup wizard.
699     */
700    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
701    /**
702     * Whether or not processing protected filters should be deferred.
703     */
704    private boolean mDeferProtectedFilters = true;
705
706    /**
707     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
708     */
709    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
710    /**
711     * Whether or not system app permissions should be promoted from install to runtime.
712     */
713    boolean mPromoteSystemApps;
714
715    @GuardedBy("mPackages")
716    final Settings mSettings;
717
718    /**
719     * Set of package names that are currently "frozen", which means active
720     * surgery is being done on the code/data for that package. The platform
721     * will refuse to launch frozen packages to avoid race conditions.
722     *
723     * @see PackageFreezer
724     */
725    @GuardedBy("mPackages")
726    final ArraySet<String> mFrozenPackages = new ArraySet<>();
727
728    final ProtectedPackages mProtectedPackages;
729
730    @GuardedBy("mLoadedVolumes")
731    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
732
733    boolean mFirstBoot;
734
735    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
736
737    // System configuration read by SystemConfig.
738    final int[] mGlobalGids;
739    final SparseArray<ArraySet<String>> mSystemPermissions;
740    @GuardedBy("mAvailableFeatures")
741    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
742
743    // If mac_permissions.xml was found for seinfo labeling.
744    boolean mFoundPolicyFile;
745
746    private final InstantAppRegistry mInstantAppRegistry;
747
748    @GuardedBy("mPackages")
749    int mChangedPackagesSequenceNumber;
750    /**
751     * List of changed [installed, removed or updated] packages.
752     * mapping from user id -> sequence number -> package name
753     */
754    @GuardedBy("mPackages")
755    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
756    /**
757     * The sequence number of the last change to a package.
758     * mapping from user id -> package name -> sequence number
759     */
760    @GuardedBy("mPackages")
761    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
762
763    class PackageParserCallback implements PackageParser.Callback {
764        @Override public final boolean hasFeature(String feature) {
765            return PackageManagerService.this.hasSystemFeature(feature, 0);
766        }
767
768        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
769                Collection<PackageParser.Package> allPackages, String targetPackageName) {
770            List<PackageParser.Package> overlayPackages = null;
771            for (PackageParser.Package p : allPackages) {
772                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
773                    if (overlayPackages == null) {
774                        overlayPackages = new ArrayList<PackageParser.Package>();
775                    }
776                    overlayPackages.add(p);
777                }
778            }
779            if (overlayPackages != null) {
780                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
781                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
782                        return p1.mOverlayPriority - p2.mOverlayPriority;
783                    }
784                };
785                Collections.sort(overlayPackages, cmp);
786            }
787            return overlayPackages;
788        }
789
790        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
791                String targetPackageName, String targetPath) {
792            if ("android".equals(targetPackageName)) {
793                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
794                // native AssetManager.
795                return null;
796            }
797            List<PackageParser.Package> overlayPackages =
798                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
799            if (overlayPackages == null || overlayPackages.isEmpty()) {
800                return null;
801            }
802            List<String> overlayPathList = null;
803            for (PackageParser.Package overlayPackage : overlayPackages) {
804                if (targetPath == null) {
805                    if (overlayPathList == null) {
806                        overlayPathList = new ArrayList<String>();
807                    }
808                    overlayPathList.add(overlayPackage.baseCodePath);
809                    continue;
810                }
811
812                try {
813                    // Creates idmaps for system to parse correctly the Android manifest of the
814                    // target package.
815                    //
816                    // OverlayManagerService will update each of them with a correct gid from its
817                    // target package app id.
818                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
819                            UserHandle.getSharedAppGid(
820                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
821                    if (overlayPathList == null) {
822                        overlayPathList = new ArrayList<String>();
823                    }
824                    overlayPathList.add(overlayPackage.baseCodePath);
825                } catch (InstallerException e) {
826                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
827                            overlayPackage.baseCodePath);
828                }
829            }
830            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
831        }
832
833        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
834            synchronized (mPackages) {
835                return getStaticOverlayPathsLocked(
836                        mPackages.values(), targetPackageName, targetPath);
837            }
838        }
839
840        @Override public final String[] getOverlayApks(String targetPackageName) {
841            return getStaticOverlayPaths(targetPackageName, null);
842        }
843
844        @Override public final String[] getOverlayPaths(String targetPackageName,
845                String targetPath) {
846            return getStaticOverlayPaths(targetPackageName, targetPath);
847        }
848    };
849
850    class ParallelPackageParserCallback extends PackageParserCallback {
851        List<PackageParser.Package> mOverlayPackages = null;
852
853        void findStaticOverlayPackages() {
854            synchronized (mPackages) {
855                for (PackageParser.Package p : mPackages.values()) {
856                    if (p.mIsStaticOverlay) {
857                        if (mOverlayPackages == null) {
858                            mOverlayPackages = new ArrayList<PackageParser.Package>();
859                        }
860                        mOverlayPackages.add(p);
861                    }
862                }
863            }
864        }
865
866        @Override
867        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
868            // We can trust mOverlayPackages without holding mPackages because package uninstall
869            // can't happen while running parallel parsing.
870            // Moreover holding mPackages on each parsing thread causes dead-lock.
871            return mOverlayPackages == null ? null :
872                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
873        }
874    }
875
876    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
877    final ParallelPackageParserCallback mParallelPackageParserCallback =
878            new ParallelPackageParserCallback();
879
880    public static final class SharedLibraryEntry {
881        public final @Nullable String path;
882        public final @Nullable String apk;
883        public final @NonNull SharedLibraryInfo info;
884
885        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
886                String declaringPackageName, int declaringPackageVersionCode) {
887            path = _path;
888            apk = _apk;
889            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
890                    declaringPackageName, declaringPackageVersionCode), null);
891        }
892    }
893
894    // Currently known shared libraries.
895    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
896    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
897            new ArrayMap<>();
898
899    // All available activities, for your resolving pleasure.
900    final ActivityIntentResolver mActivities =
901            new ActivityIntentResolver();
902
903    // All available receivers, for your resolving pleasure.
904    final ActivityIntentResolver mReceivers =
905            new ActivityIntentResolver();
906
907    // All available services, for your resolving pleasure.
908    final ServiceIntentResolver mServices = new ServiceIntentResolver();
909
910    // All available providers, for your resolving pleasure.
911    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
912
913    // Mapping from provider base names (first directory in content URI codePath)
914    // to the provider information.
915    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
916            new ArrayMap<String, PackageParser.Provider>();
917
918    // Mapping from instrumentation class names to info about them.
919    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
920            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
921
922    // Mapping from permission names to info about them.
923    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
924            new ArrayMap<String, PackageParser.PermissionGroup>();
925
926    // Packages whose data we have transfered into another package, thus
927    // should no longer exist.
928    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
929
930    // Broadcast actions that are only available to the system.
931    @GuardedBy("mProtectedBroadcasts")
932    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
933
934    /** List of packages waiting for verification. */
935    final SparseArray<PackageVerificationState> mPendingVerification
936            = new SparseArray<PackageVerificationState>();
937
938    /** Set of packages associated with each app op permission. */
939    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
940
941    final PackageInstallerService mInstallerService;
942
943    private final PackageDexOptimizer mPackageDexOptimizer;
944    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
945    // is used by other apps).
946    private final DexManager mDexManager;
947
948    private AtomicInteger mNextMoveId = new AtomicInteger();
949    private final MoveCallbacks mMoveCallbacks;
950
951    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
952
953    // Cache of users who need badging.
954    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
955
956    /** Token for keys in mPendingVerification. */
957    private int mPendingVerificationToken = 0;
958
959    volatile boolean mSystemReady;
960    volatile boolean mSafeMode;
961    volatile boolean mHasSystemUidErrors;
962    private volatile boolean mEphemeralAppsDisabled;
963
964    ApplicationInfo mAndroidApplication;
965    final ActivityInfo mResolveActivity = new ActivityInfo();
966    final ResolveInfo mResolveInfo = new ResolveInfo();
967    ComponentName mResolveComponentName;
968    PackageParser.Package mPlatformPackage;
969    ComponentName mCustomResolverComponentName;
970
971    boolean mResolverReplaced = false;
972
973    private final @Nullable ComponentName mIntentFilterVerifierComponent;
974    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
975
976    private int mIntentFilterVerificationToken = 0;
977
978    /** The service connection to the ephemeral resolver */
979    final EphemeralResolverConnection mInstantAppResolverConnection;
980    /** Component used to show resolver settings for Instant Apps */
981    final ComponentName mInstantAppResolverSettingsComponent;
982
983    /** Activity used to install instant applications */
984    ActivityInfo mInstantAppInstallerActivity;
985    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
986
987    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
988            = new SparseArray<IntentFilterVerificationState>();
989
990    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
991
992    // List of packages names to keep cached, even if they are uninstalled for all users
993    private List<String> mKeepUninstalledPackages;
994
995    private UserManagerInternal mUserManagerInternal;
996
997    private DeviceIdleController.LocalService mDeviceIdleController;
998
999    private File mCacheDir;
1000
1001    private ArraySet<String> mPrivappPermissionsViolations;
1002
1003    private Future<?> mPrepareAppDataFuture;
1004
1005    private static class IFVerificationParams {
1006        PackageParser.Package pkg;
1007        boolean replacing;
1008        int userId;
1009        int verifierUid;
1010
1011        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1012                int _userId, int _verifierUid) {
1013            pkg = _pkg;
1014            replacing = _replacing;
1015            userId = _userId;
1016            replacing = _replacing;
1017            verifierUid = _verifierUid;
1018        }
1019    }
1020
1021    private interface IntentFilterVerifier<T extends IntentFilter> {
1022        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1023                                               T filter, String packageName);
1024        void startVerifications(int userId);
1025        void receiveVerificationResponse(int verificationId);
1026    }
1027
1028    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1029        private Context mContext;
1030        private ComponentName mIntentFilterVerifierComponent;
1031        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1032
1033        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1034            mContext = context;
1035            mIntentFilterVerifierComponent = verifierComponent;
1036        }
1037
1038        private String getDefaultScheme() {
1039            return IntentFilter.SCHEME_HTTPS;
1040        }
1041
1042        @Override
1043        public void startVerifications(int userId) {
1044            // Launch verifications requests
1045            int count = mCurrentIntentFilterVerifications.size();
1046            for (int n=0; n<count; n++) {
1047                int verificationId = mCurrentIntentFilterVerifications.get(n);
1048                final IntentFilterVerificationState ivs =
1049                        mIntentFilterVerificationStates.get(verificationId);
1050
1051                String packageName = ivs.getPackageName();
1052
1053                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1054                final int filterCount = filters.size();
1055                ArraySet<String> domainsSet = new ArraySet<>();
1056                for (int m=0; m<filterCount; m++) {
1057                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1058                    domainsSet.addAll(filter.getHostsList());
1059                }
1060                synchronized (mPackages) {
1061                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1062                            packageName, domainsSet) != null) {
1063                        scheduleWriteSettingsLocked();
1064                    }
1065                }
1066                sendVerificationRequest(verificationId, ivs);
1067            }
1068            mCurrentIntentFilterVerifications.clear();
1069        }
1070
1071        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
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                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1092
1093            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1094            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1095                    "Sending IntentFilter verification broadcast");
1096        }
1097
1098        public void receiveVerificationResponse(int verificationId) {
1099            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1100
1101            final boolean verified = ivs.isVerified();
1102
1103            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1104            final int count = filters.size();
1105            if (DEBUG_DOMAIN_VERIFICATION) {
1106                Slog.i(TAG, "Received verification response " + verificationId
1107                        + " for " + count + " filters, verified=" + verified);
1108            }
1109            for (int n=0; n<count; n++) {
1110                PackageParser.ActivityIntentInfo filter = filters.get(n);
1111                filter.setVerified(verified);
1112
1113                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1114                        + " verified with result:" + verified + " and hosts:"
1115                        + ivs.getHostsString());
1116            }
1117
1118            mIntentFilterVerificationStates.remove(verificationId);
1119
1120            final String packageName = ivs.getPackageName();
1121            IntentFilterVerificationInfo ivi = null;
1122
1123            synchronized (mPackages) {
1124                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1125            }
1126            if (ivi == null) {
1127                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1128                        + verificationId + " packageName:" + packageName);
1129                return;
1130            }
1131            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1132                    "Updating IntentFilterVerificationInfo for package " + packageName
1133                            +" verificationId:" + verificationId);
1134
1135            synchronized (mPackages) {
1136                if (verified) {
1137                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1138                } else {
1139                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1140                }
1141                scheduleWriteSettingsLocked();
1142
1143                final int userId = ivs.getUserId();
1144                if (userId != UserHandle.USER_ALL) {
1145                    final int userStatus =
1146                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1147
1148                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1149                    boolean needUpdate = false;
1150
1151                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1152                    // already been set by the User thru the Disambiguation dialog
1153                    switch (userStatus) {
1154                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1155                            if (verified) {
1156                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1157                            } else {
1158                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1159                            }
1160                            needUpdate = true;
1161                            break;
1162
1163                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1164                            if (verified) {
1165                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1166                                needUpdate = true;
1167                            }
1168                            break;
1169
1170                        default:
1171                            // Nothing to do
1172                    }
1173
1174                    if (needUpdate) {
1175                        mSettings.updateIntentFilterVerificationStatusLPw(
1176                                packageName, updatedStatus, userId);
1177                        scheduleWritePackageRestrictionsLocked(userId);
1178                    }
1179                }
1180            }
1181        }
1182
1183        @Override
1184        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1185                    ActivityIntentInfo filter, String packageName) {
1186            if (!hasValidDomains(filter)) {
1187                return false;
1188            }
1189            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1190            if (ivs == null) {
1191                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1192                        packageName);
1193            }
1194            if (DEBUG_DOMAIN_VERIFICATION) {
1195                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1196            }
1197            ivs.addFilter(filter);
1198            return true;
1199        }
1200
1201        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1202                int userId, int verificationId, String packageName) {
1203            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1204                    verifierUid, userId, packageName);
1205            ivs.setPendingState();
1206            synchronized (mPackages) {
1207                mIntentFilterVerificationStates.append(verificationId, ivs);
1208                mCurrentIntentFilterVerifications.add(verificationId);
1209            }
1210            return ivs;
1211        }
1212    }
1213
1214    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1215        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1216                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1217                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1218    }
1219
1220    // Set of pending broadcasts for aggregating enable/disable of components.
1221    static class PendingPackageBroadcasts {
1222        // for each user id, a map of <package name -> components within that package>
1223        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1224
1225        public PendingPackageBroadcasts() {
1226            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1227        }
1228
1229        public ArrayList<String> get(int userId, String packageName) {
1230            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1231            return packages.get(packageName);
1232        }
1233
1234        public void put(int userId, String packageName, ArrayList<String> components) {
1235            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1236            packages.put(packageName, components);
1237        }
1238
1239        public void remove(int userId, String packageName) {
1240            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1241            if (packages != null) {
1242                packages.remove(packageName);
1243            }
1244        }
1245
1246        public void remove(int userId) {
1247            mUidMap.remove(userId);
1248        }
1249
1250        public int userIdCount() {
1251            return mUidMap.size();
1252        }
1253
1254        public int userIdAt(int n) {
1255            return mUidMap.keyAt(n);
1256        }
1257
1258        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1259            return mUidMap.get(userId);
1260        }
1261
1262        public int size() {
1263            // total number of pending broadcast entries across all userIds
1264            int num = 0;
1265            for (int i = 0; i< mUidMap.size(); i++) {
1266                num += mUidMap.valueAt(i).size();
1267            }
1268            return num;
1269        }
1270
1271        public void clear() {
1272            mUidMap.clear();
1273        }
1274
1275        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1276            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1277            if (map == null) {
1278                map = new ArrayMap<String, ArrayList<String>>();
1279                mUidMap.put(userId, map);
1280            }
1281            return map;
1282        }
1283    }
1284    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1285
1286    // Service Connection to remote media container service to copy
1287    // package uri's from external media onto secure containers
1288    // or internal storage.
1289    private IMediaContainerService mContainerService = null;
1290
1291    static final int SEND_PENDING_BROADCAST = 1;
1292    static final int MCS_BOUND = 3;
1293    static final int END_COPY = 4;
1294    static final int INIT_COPY = 5;
1295    static final int MCS_UNBIND = 6;
1296    static final int START_CLEANING_PACKAGE = 7;
1297    static final int FIND_INSTALL_LOC = 8;
1298    static final int POST_INSTALL = 9;
1299    static final int MCS_RECONNECT = 10;
1300    static final int MCS_GIVE_UP = 11;
1301    static final int UPDATED_MEDIA_STATUS = 12;
1302    static final int WRITE_SETTINGS = 13;
1303    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1304    static final int PACKAGE_VERIFIED = 15;
1305    static final int CHECK_PENDING_VERIFICATION = 16;
1306    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1307    static final int INTENT_FILTER_VERIFIED = 18;
1308    static final int WRITE_PACKAGE_LIST = 19;
1309    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1310
1311    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1312
1313    // Delay time in millisecs
1314    static final int BROADCAST_DELAY = 10 * 1000;
1315
1316    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1317            2 * 60 * 60 * 1000L; /* two hours */
1318
1319    static UserManagerService sUserManager;
1320
1321    // Stores a list of users whose package restrictions file needs to be updated
1322    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1323
1324    final private DefaultContainerConnection mDefContainerConn =
1325            new DefaultContainerConnection();
1326    class DefaultContainerConnection implements ServiceConnection {
1327        public void onServiceConnected(ComponentName name, IBinder service) {
1328            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1329            final IMediaContainerService imcs = IMediaContainerService.Stub
1330                    .asInterface(Binder.allowBlocking(service));
1331            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1332        }
1333
1334        public void onServiceDisconnected(ComponentName name) {
1335            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1336        }
1337    }
1338
1339    // Recordkeeping of restore-after-install operations that are currently in flight
1340    // between the Package Manager and the Backup Manager
1341    static class PostInstallData {
1342        public InstallArgs args;
1343        public PackageInstalledInfo res;
1344
1345        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1346            args = _a;
1347            res = _r;
1348        }
1349    }
1350
1351    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1352    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1353
1354    // XML tags for backup/restore of various bits of state
1355    private static final String TAG_PREFERRED_BACKUP = "pa";
1356    private static final String TAG_DEFAULT_APPS = "da";
1357    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1358
1359    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1360    private static final String TAG_ALL_GRANTS = "rt-grants";
1361    private static final String TAG_GRANT = "grant";
1362    private static final String ATTR_PACKAGE_NAME = "pkg";
1363
1364    private static final String TAG_PERMISSION = "perm";
1365    private static final String ATTR_PERMISSION_NAME = "name";
1366    private static final String ATTR_IS_GRANTED = "g";
1367    private static final String ATTR_USER_SET = "set";
1368    private static final String ATTR_USER_FIXED = "fixed";
1369    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1370
1371    // System/policy permission grants are not backed up
1372    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1373            FLAG_PERMISSION_POLICY_FIXED
1374            | FLAG_PERMISSION_SYSTEM_FIXED
1375            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1376
1377    // And we back up these user-adjusted states
1378    private static final int USER_RUNTIME_GRANT_MASK =
1379            FLAG_PERMISSION_USER_SET
1380            | FLAG_PERMISSION_USER_FIXED
1381            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1382
1383    final @Nullable String mRequiredVerifierPackage;
1384    final @NonNull String mRequiredInstallerPackage;
1385    final @NonNull String mRequiredUninstallerPackage;
1386    final @Nullable String mSetupWizardPackage;
1387    final @Nullable String mStorageManagerPackage;
1388    final @NonNull String mServicesSystemSharedLibraryPackageName;
1389    final @NonNull String mSharedSystemSharedLibraryPackageName;
1390
1391    final boolean mPermissionReviewRequired;
1392
1393    private final PackageUsage mPackageUsage = new PackageUsage();
1394    private final CompilerStats mCompilerStats = new CompilerStats();
1395
1396    class PackageHandler extends Handler {
1397        private boolean mBound = false;
1398        final ArrayList<HandlerParams> mPendingInstalls =
1399            new ArrayList<HandlerParams>();
1400
1401        private boolean connectToService() {
1402            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1403                    " DefaultContainerService");
1404            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1405            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1406            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1407                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1408                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1409                mBound = true;
1410                return true;
1411            }
1412            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1413            return false;
1414        }
1415
1416        private void disconnectService() {
1417            mContainerService = null;
1418            mBound = false;
1419            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1420            mContext.unbindService(mDefContainerConn);
1421            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1422        }
1423
1424        PackageHandler(Looper looper) {
1425            super(looper);
1426        }
1427
1428        public void handleMessage(Message msg) {
1429            try {
1430                doHandleMessage(msg);
1431            } finally {
1432                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1433            }
1434        }
1435
1436        void doHandleMessage(Message msg) {
1437            switch (msg.what) {
1438                case INIT_COPY: {
1439                    HandlerParams params = (HandlerParams) msg.obj;
1440                    int idx = mPendingInstalls.size();
1441                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1442                    // If a bind was already initiated we dont really
1443                    // need to do anything. The pending install
1444                    // will be processed later on.
1445                    if (!mBound) {
1446                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1447                                System.identityHashCode(mHandler));
1448                        // If this is the only one pending we might
1449                        // have to bind to the service again.
1450                        if (!connectToService()) {
1451                            Slog.e(TAG, "Failed to bind to media container service");
1452                            params.serviceError();
1453                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1454                                    System.identityHashCode(mHandler));
1455                            if (params.traceMethod != null) {
1456                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1457                                        params.traceCookie);
1458                            }
1459                            return;
1460                        } else {
1461                            // Once we bind to the service, the first
1462                            // pending request will be processed.
1463                            mPendingInstalls.add(idx, params);
1464                        }
1465                    } else {
1466                        mPendingInstalls.add(idx, params);
1467                        // Already bound to the service. Just make
1468                        // sure we trigger off processing the first request.
1469                        if (idx == 0) {
1470                            mHandler.sendEmptyMessage(MCS_BOUND);
1471                        }
1472                    }
1473                    break;
1474                }
1475                case MCS_BOUND: {
1476                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1477                    if (msg.obj != null) {
1478                        mContainerService = (IMediaContainerService) msg.obj;
1479                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1480                                System.identityHashCode(mHandler));
1481                    }
1482                    if (mContainerService == null) {
1483                        if (!mBound) {
1484                            // Something seriously wrong since we are not bound and we are not
1485                            // waiting for connection. Bail out.
1486                            Slog.e(TAG, "Cannot bind to media container service");
1487                            for (HandlerParams params : mPendingInstalls) {
1488                                // Indicate service bind error
1489                                params.serviceError();
1490                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1491                                        System.identityHashCode(params));
1492                                if (params.traceMethod != null) {
1493                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1494                                            params.traceMethod, params.traceCookie);
1495                                }
1496                                return;
1497                            }
1498                            mPendingInstalls.clear();
1499                        } else {
1500                            Slog.w(TAG, "Waiting to connect to media container service");
1501                        }
1502                    } else if (mPendingInstalls.size() > 0) {
1503                        HandlerParams params = mPendingInstalls.get(0);
1504                        if (params != null) {
1505                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1506                                    System.identityHashCode(params));
1507                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1508                            if (params.startCopy()) {
1509                                // We are done...  look for more work or to
1510                                // go idle.
1511                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1512                                        "Checking for more work or unbind...");
1513                                // Delete pending install
1514                                if (mPendingInstalls.size() > 0) {
1515                                    mPendingInstalls.remove(0);
1516                                }
1517                                if (mPendingInstalls.size() == 0) {
1518                                    if (mBound) {
1519                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1520                                                "Posting delayed MCS_UNBIND");
1521                                        removeMessages(MCS_UNBIND);
1522                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1523                                        // Unbind after a little delay, to avoid
1524                                        // continual thrashing.
1525                                        sendMessageDelayed(ubmsg, 10000);
1526                                    }
1527                                } else {
1528                                    // There are more pending requests in queue.
1529                                    // Just post MCS_BOUND message to trigger processing
1530                                    // of next pending install.
1531                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1532                                            "Posting MCS_BOUND for next work");
1533                                    mHandler.sendEmptyMessage(MCS_BOUND);
1534                                }
1535                            }
1536                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1537                        }
1538                    } else {
1539                        // Should never happen ideally.
1540                        Slog.w(TAG, "Empty queue");
1541                    }
1542                    break;
1543                }
1544                case MCS_RECONNECT: {
1545                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1546                    if (mPendingInstalls.size() > 0) {
1547                        if (mBound) {
1548                            disconnectService();
1549                        }
1550                        if (!connectToService()) {
1551                            Slog.e(TAG, "Failed to bind to media container service");
1552                            for (HandlerParams params : mPendingInstalls) {
1553                                // Indicate service bind error
1554                                params.serviceError();
1555                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1556                                        System.identityHashCode(params));
1557                            }
1558                            mPendingInstalls.clear();
1559                        }
1560                    }
1561                    break;
1562                }
1563                case MCS_UNBIND: {
1564                    // If there is no actual work left, then time to unbind.
1565                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1566
1567                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1568                        if (mBound) {
1569                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1570
1571                            disconnectService();
1572                        }
1573                    } else if (mPendingInstalls.size() > 0) {
1574                        // There are more pending requests in queue.
1575                        // Just post MCS_BOUND message to trigger processing
1576                        // of next pending install.
1577                        mHandler.sendEmptyMessage(MCS_BOUND);
1578                    }
1579
1580                    break;
1581                }
1582                case MCS_GIVE_UP: {
1583                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1584                    HandlerParams params = mPendingInstalls.remove(0);
1585                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1586                            System.identityHashCode(params));
1587                    break;
1588                }
1589                case SEND_PENDING_BROADCAST: {
1590                    String packages[];
1591                    ArrayList<String> components[];
1592                    int size = 0;
1593                    int uids[];
1594                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1595                    synchronized (mPackages) {
1596                        if (mPendingBroadcasts == null) {
1597                            return;
1598                        }
1599                        size = mPendingBroadcasts.size();
1600                        if (size <= 0) {
1601                            // Nothing to be done. Just return
1602                            return;
1603                        }
1604                        packages = new String[size];
1605                        components = new ArrayList[size];
1606                        uids = new int[size];
1607                        int i = 0;  // filling out the above arrays
1608
1609                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1610                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1611                            Iterator<Map.Entry<String, ArrayList<String>>> it
1612                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1613                                            .entrySet().iterator();
1614                            while (it.hasNext() && i < size) {
1615                                Map.Entry<String, ArrayList<String>> ent = it.next();
1616                                packages[i] = ent.getKey();
1617                                components[i] = ent.getValue();
1618                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1619                                uids[i] = (ps != null)
1620                                        ? UserHandle.getUid(packageUserId, ps.appId)
1621                                        : -1;
1622                                i++;
1623                            }
1624                        }
1625                        size = i;
1626                        mPendingBroadcasts.clear();
1627                    }
1628                    // Send broadcasts
1629                    for (int i = 0; i < size; i++) {
1630                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1631                    }
1632                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1633                    break;
1634                }
1635                case START_CLEANING_PACKAGE: {
1636                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1637                    final String packageName = (String)msg.obj;
1638                    final int userId = msg.arg1;
1639                    final boolean andCode = msg.arg2 != 0;
1640                    synchronized (mPackages) {
1641                        if (userId == UserHandle.USER_ALL) {
1642                            int[] users = sUserManager.getUserIds();
1643                            for (int user : users) {
1644                                mSettings.addPackageToCleanLPw(
1645                                        new PackageCleanItem(user, packageName, andCode));
1646                            }
1647                        } else {
1648                            mSettings.addPackageToCleanLPw(
1649                                    new PackageCleanItem(userId, packageName, andCode));
1650                        }
1651                    }
1652                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1653                    startCleaningPackages();
1654                } break;
1655                case POST_INSTALL: {
1656                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1657
1658                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1659                    final boolean didRestore = (msg.arg2 != 0);
1660                    mRunningInstalls.delete(msg.arg1);
1661
1662                    if (data != null) {
1663                        InstallArgs args = data.args;
1664                        PackageInstalledInfo parentRes = data.res;
1665
1666                        final boolean grantPermissions = (args.installFlags
1667                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1668                        final boolean killApp = (args.installFlags
1669                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1670                        final String[] grantedPermissions = args.installGrantPermissions;
1671
1672                        // Handle the parent package
1673                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1674                                grantedPermissions, didRestore, args.installerPackageName,
1675                                args.observer);
1676
1677                        // Handle the child packages
1678                        final int childCount = (parentRes.addedChildPackages != null)
1679                                ? parentRes.addedChildPackages.size() : 0;
1680                        for (int i = 0; i < childCount; i++) {
1681                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1682                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1683                                    grantedPermissions, false, args.installerPackageName,
1684                                    args.observer);
1685                        }
1686
1687                        // Log tracing if needed
1688                        if (args.traceMethod != null) {
1689                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1690                                    args.traceCookie);
1691                        }
1692                    } else {
1693                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1694                    }
1695
1696                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1697                } break;
1698                case UPDATED_MEDIA_STATUS: {
1699                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1700                    boolean reportStatus = msg.arg1 == 1;
1701                    boolean doGc = msg.arg2 == 1;
1702                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1703                    if (doGc) {
1704                        // Force a gc to clear up stale containers.
1705                        Runtime.getRuntime().gc();
1706                    }
1707                    if (msg.obj != null) {
1708                        @SuppressWarnings("unchecked")
1709                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1710                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1711                        // Unload containers
1712                        unloadAllContainers(args);
1713                    }
1714                    if (reportStatus) {
1715                        try {
1716                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1717                                    "Invoking StorageManagerService call back");
1718                            PackageHelper.getStorageManager().finishMediaUpdate();
1719                        } catch (RemoteException e) {
1720                            Log.e(TAG, "StorageManagerService not running?");
1721                        }
1722                    }
1723                } break;
1724                case WRITE_SETTINGS: {
1725                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1726                    synchronized (mPackages) {
1727                        removeMessages(WRITE_SETTINGS);
1728                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1729                        mSettings.writeLPr();
1730                        mDirtyUsers.clear();
1731                    }
1732                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1733                } break;
1734                case WRITE_PACKAGE_RESTRICTIONS: {
1735                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1736                    synchronized (mPackages) {
1737                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1738                        for (int userId : mDirtyUsers) {
1739                            mSettings.writePackageRestrictionsLPr(userId);
1740                        }
1741                        mDirtyUsers.clear();
1742                    }
1743                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1744                } break;
1745                case WRITE_PACKAGE_LIST: {
1746                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1747                    synchronized (mPackages) {
1748                        removeMessages(WRITE_PACKAGE_LIST);
1749                        mSettings.writePackageListLPr(msg.arg1);
1750                    }
1751                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1752                } break;
1753                case CHECK_PENDING_VERIFICATION: {
1754                    final int verificationId = msg.arg1;
1755                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1756
1757                    if ((state != null) && !state.timeoutExtended()) {
1758                        final InstallArgs args = state.getInstallArgs();
1759                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1760
1761                        Slog.i(TAG, "Verification timed out for " + originUri);
1762                        mPendingVerification.remove(verificationId);
1763
1764                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1765
1766                        final UserHandle user = args.getUser();
1767                        if (getDefaultVerificationResponse(user)
1768                                == PackageManager.VERIFICATION_ALLOW) {
1769                            Slog.i(TAG, "Continuing with installation of " + originUri);
1770                            state.setVerifierResponse(Binder.getCallingUid(),
1771                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1772                            broadcastPackageVerified(verificationId, originUri,
1773                                    PackageManager.VERIFICATION_ALLOW, user);
1774                            try {
1775                                ret = args.copyApk(mContainerService, true);
1776                            } catch (RemoteException e) {
1777                                Slog.e(TAG, "Could not contact the ContainerService");
1778                            }
1779                        } else {
1780                            broadcastPackageVerified(verificationId, originUri,
1781                                    PackageManager.VERIFICATION_REJECT, user);
1782                        }
1783
1784                        Trace.asyncTraceEnd(
1785                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1786
1787                        processPendingInstall(args, ret);
1788                        mHandler.sendEmptyMessage(MCS_UNBIND);
1789                    }
1790                    break;
1791                }
1792                case PACKAGE_VERIFIED: {
1793                    final int verificationId = msg.arg1;
1794
1795                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1796                    if (state == null) {
1797                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1798                        break;
1799                    }
1800
1801                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1802
1803                    state.setVerifierResponse(response.callerUid, response.code);
1804
1805                    if (state.isVerificationComplete()) {
1806                        mPendingVerification.remove(verificationId);
1807
1808                        final InstallArgs args = state.getInstallArgs();
1809                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1810
1811                        int ret;
1812                        if (state.isInstallAllowed()) {
1813                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1814                            broadcastPackageVerified(verificationId, originUri,
1815                                    response.code, state.getInstallArgs().getUser());
1816                            try {
1817                                ret = args.copyApk(mContainerService, true);
1818                            } catch (RemoteException e) {
1819                                Slog.e(TAG, "Could not contact the ContainerService");
1820                            }
1821                        } else {
1822                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1823                        }
1824
1825                        Trace.asyncTraceEnd(
1826                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1827
1828                        processPendingInstall(args, ret);
1829                        mHandler.sendEmptyMessage(MCS_UNBIND);
1830                    }
1831
1832                    break;
1833                }
1834                case START_INTENT_FILTER_VERIFICATIONS: {
1835                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1836                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1837                            params.replacing, params.pkg);
1838                    break;
1839                }
1840                case INTENT_FILTER_VERIFIED: {
1841                    final int verificationId = msg.arg1;
1842
1843                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1844                            verificationId);
1845                    if (state == null) {
1846                        Slog.w(TAG, "Invalid IntentFilter verification token "
1847                                + verificationId + " received");
1848                        break;
1849                    }
1850
1851                    final int userId = state.getUserId();
1852
1853                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1854                            "Processing IntentFilter verification with token:"
1855                            + verificationId + " and userId:" + userId);
1856
1857                    final IntentFilterVerificationResponse response =
1858                            (IntentFilterVerificationResponse) msg.obj;
1859
1860                    state.setVerifierResponse(response.callerUid, response.code);
1861
1862                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1863                            "IntentFilter verification with token:" + verificationId
1864                            + " and userId:" + userId
1865                            + " is settings verifier response with response code:"
1866                            + response.code);
1867
1868                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1869                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1870                                + response.getFailedDomainsString());
1871                    }
1872
1873                    if (state.isVerificationComplete()) {
1874                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1875                    } else {
1876                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1877                                "IntentFilter verification with token:" + verificationId
1878                                + " was not said to be complete");
1879                    }
1880
1881                    break;
1882                }
1883                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1884                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1885                            mInstantAppResolverConnection,
1886                            (InstantAppRequest) msg.obj,
1887                            mInstantAppInstallerActivity,
1888                            mHandler);
1889                }
1890            }
1891        }
1892    }
1893
1894    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1895            boolean killApp, String[] grantedPermissions,
1896            boolean launchedForRestore, String installerPackage,
1897            IPackageInstallObserver2 installObserver) {
1898        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1899            // Send the removed broadcasts
1900            if (res.removedInfo != null) {
1901                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1902            }
1903
1904            // Now that we successfully installed the package, grant runtime
1905            // permissions if requested before broadcasting the install. Also
1906            // for legacy apps in permission review mode we clear the permission
1907            // review flag which is used to emulate runtime permissions for
1908            // legacy apps.
1909            if (grantPermissions) {
1910                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1911            }
1912
1913            final boolean update = res.removedInfo != null
1914                    && res.removedInfo.removedPackage != null;
1915            final String origInstallerPackageName = res.removedInfo != null
1916                    ? res.removedInfo.installerPackageName : null;
1917
1918            // If this is the first time we have child packages for a disabled privileged
1919            // app that had no children, we grant requested runtime permissions to the new
1920            // children if the parent on the system image had them already granted.
1921            if (res.pkg.parentPackage != null) {
1922                synchronized (mPackages) {
1923                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1924                }
1925            }
1926
1927            synchronized (mPackages) {
1928                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1929            }
1930
1931            final String packageName = res.pkg.applicationInfo.packageName;
1932
1933            // Determine the set of users who are adding this package for
1934            // the first time vs. those who are seeing an update.
1935            int[] firstUsers = EMPTY_INT_ARRAY;
1936            int[] updateUsers = EMPTY_INT_ARRAY;
1937            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1938            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1939            for (int newUser : res.newUsers) {
1940                if (ps.getInstantApp(newUser)) {
1941                    continue;
1942                }
1943                if (allNewUsers) {
1944                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1945                    continue;
1946                }
1947                boolean isNew = true;
1948                for (int origUser : res.origUsers) {
1949                    if (origUser == newUser) {
1950                        isNew = false;
1951                        break;
1952                    }
1953                }
1954                if (isNew) {
1955                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1956                } else {
1957                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1958                }
1959            }
1960
1961            // Send installed broadcasts if the package is not a static shared lib.
1962            if (res.pkg.staticSharedLibName == null) {
1963                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1964
1965                // Send added for users that see the package for the first time
1966                // sendPackageAddedForNewUsers also deals with system apps
1967                int appId = UserHandle.getAppId(res.uid);
1968                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1969                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1970
1971                // Send added for users that don't see the package for the first time
1972                Bundle extras = new Bundle(1);
1973                extras.putInt(Intent.EXTRA_UID, res.uid);
1974                if (update) {
1975                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1976                }
1977                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1978                        extras, 0 /*flags*/,
1979                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1980                if (origInstallerPackageName != null) {
1981                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1982                            extras, 0 /*flags*/,
1983                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1984                }
1985
1986                // Send replaced for users that don't see the package for the first time
1987                if (update) {
1988                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1989                            packageName, extras, 0 /*flags*/,
1990                            null /*targetPackage*/, null /*finishedReceiver*/,
1991                            updateUsers);
1992                    if (origInstallerPackageName != null) {
1993                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1994                                extras, 0 /*flags*/,
1995                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1996                    }
1997                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1998                            null /*package*/, null /*extras*/, 0 /*flags*/,
1999                            packageName /*targetPackage*/,
2000                            null /*finishedReceiver*/, updateUsers);
2001                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2002                    // First-install and we did a restore, so we're responsible for the
2003                    // first-launch broadcast.
2004                    if (DEBUG_BACKUP) {
2005                        Slog.i(TAG, "Post-restore of " + packageName
2006                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2007                    }
2008                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2009                }
2010
2011                // Send broadcast package appeared if forward locked/external for all users
2012                // treat asec-hosted packages like removable media on upgrade
2013                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2014                    if (DEBUG_INSTALL) {
2015                        Slog.i(TAG, "upgrading pkg " + res.pkg
2016                                + " is ASEC-hosted -> AVAILABLE");
2017                    }
2018                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2019                    ArrayList<String> pkgList = new ArrayList<>(1);
2020                    pkgList.add(packageName);
2021                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2022                }
2023            }
2024
2025            // Work that needs to happen on first install within each user
2026            if (firstUsers != null && firstUsers.length > 0) {
2027                synchronized (mPackages) {
2028                    for (int userId : firstUsers) {
2029                        // If this app is a browser and it's newly-installed for some
2030                        // users, clear any default-browser state in those users. The
2031                        // app's nature doesn't depend on the user, so we can just check
2032                        // its browser nature in any user and generalize.
2033                        if (packageIsBrowser(packageName, userId)) {
2034                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2035                        }
2036
2037                        // We may also need to apply pending (restored) runtime
2038                        // permission grants within these users.
2039                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2040                    }
2041                }
2042            }
2043
2044            // Log current value of "unknown sources" setting
2045            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2046                    getUnknownSourcesSettings());
2047
2048            // Remove the replaced package's older resources safely now
2049            // We delete after a gc for applications  on sdcard.
2050            if (res.removedInfo != null && res.removedInfo.args != null) {
2051                Runtime.getRuntime().gc();
2052                synchronized (mInstallLock) {
2053                    res.removedInfo.args.doPostDeleteLI(true);
2054                }
2055            } else {
2056                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2057                // and not block here.
2058                VMRuntime.getRuntime().requestConcurrentGC();
2059            }
2060
2061            // Notify DexManager that the package was installed for new users.
2062            // The updated users should already be indexed and the package code paths
2063            // should not change.
2064            // Don't notify the manager for ephemeral apps as they are not expected to
2065            // survive long enough to benefit of background optimizations.
2066            for (int userId : firstUsers) {
2067                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2068                // There's a race currently where some install events may interleave with an uninstall.
2069                // This can lead to package info being null (b/36642664).
2070                if (info != null) {
2071                    mDexManager.notifyPackageInstalled(info, userId);
2072                }
2073            }
2074        }
2075
2076        // If someone is watching installs - notify them
2077        if (installObserver != null) {
2078            try {
2079                Bundle extras = extrasForInstallResult(res);
2080                installObserver.onPackageInstalled(res.name, res.returnCode,
2081                        res.returnMsg, extras);
2082            } catch (RemoteException e) {
2083                Slog.i(TAG, "Observer no longer exists.");
2084            }
2085        }
2086    }
2087
2088    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2089            PackageParser.Package pkg) {
2090        if (pkg.parentPackage == null) {
2091            return;
2092        }
2093        if (pkg.requestedPermissions == null) {
2094            return;
2095        }
2096        final PackageSetting disabledSysParentPs = mSettings
2097                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2098        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2099                || !disabledSysParentPs.isPrivileged()
2100                || (disabledSysParentPs.childPackageNames != null
2101                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2102            return;
2103        }
2104        final int[] allUserIds = sUserManager.getUserIds();
2105        final int permCount = pkg.requestedPermissions.size();
2106        for (int i = 0; i < permCount; i++) {
2107            String permission = pkg.requestedPermissions.get(i);
2108            BasePermission bp = mSettings.mPermissions.get(permission);
2109            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2110                continue;
2111            }
2112            for (int userId : allUserIds) {
2113                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2114                        permission, userId)) {
2115                    grantRuntimePermission(pkg.packageName, permission, userId);
2116                }
2117            }
2118        }
2119    }
2120
2121    private StorageEventListener mStorageListener = new StorageEventListener() {
2122        @Override
2123        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2124            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2125                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2126                    final String volumeUuid = vol.getFsUuid();
2127
2128                    // Clean up any users or apps that were removed or recreated
2129                    // while this volume was missing
2130                    sUserManager.reconcileUsers(volumeUuid);
2131                    reconcileApps(volumeUuid);
2132
2133                    // Clean up any install sessions that expired or were
2134                    // cancelled while this volume was missing
2135                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2136
2137                    loadPrivatePackages(vol);
2138
2139                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2140                    unloadPrivatePackages(vol);
2141                }
2142            }
2143
2144            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2145                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2146                    updateExternalMediaStatus(true, false);
2147                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2148                    updateExternalMediaStatus(false, false);
2149                }
2150            }
2151        }
2152
2153        @Override
2154        public void onVolumeForgotten(String fsUuid) {
2155            if (TextUtils.isEmpty(fsUuid)) {
2156                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2157                return;
2158            }
2159
2160            // Remove any apps installed on the forgotten volume
2161            synchronized (mPackages) {
2162                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2163                for (PackageSetting ps : packages) {
2164                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2165                    deletePackageVersioned(new VersionedPackage(ps.name,
2166                            PackageManager.VERSION_CODE_HIGHEST),
2167                            new LegacyPackageDeleteObserver(null).getBinder(),
2168                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2169                    // Try very hard to release any references to this package
2170                    // so we don't risk the system server being killed due to
2171                    // open FDs
2172                    AttributeCache.instance().removePackage(ps.name);
2173                }
2174
2175                mSettings.onVolumeForgotten(fsUuid);
2176                mSettings.writeLPr();
2177            }
2178        }
2179    };
2180
2181    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2182            String[] grantedPermissions) {
2183        for (int userId : userIds) {
2184            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2185        }
2186    }
2187
2188    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2189            String[] grantedPermissions) {
2190        PackageSetting ps = (PackageSetting) pkg.mExtras;
2191        if (ps == null) {
2192            return;
2193        }
2194
2195        PermissionsState permissionsState = ps.getPermissionsState();
2196
2197        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2198                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2199
2200        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2201                >= Build.VERSION_CODES.M;
2202
2203        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2204
2205        for (String permission : pkg.requestedPermissions) {
2206            final BasePermission bp;
2207            synchronized (mPackages) {
2208                bp = mSettings.mPermissions.get(permission);
2209            }
2210            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2211                    && (!instantApp || bp.isInstant())
2212                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2213                    && (grantedPermissions == null
2214                           || ArrayUtils.contains(grantedPermissions, permission))) {
2215                final int flags = permissionsState.getPermissionFlags(permission, userId);
2216                if (supportsRuntimePermissions) {
2217                    // Installer cannot change immutable permissions.
2218                    if ((flags & immutableFlags) == 0) {
2219                        grantRuntimePermission(pkg.packageName, permission, userId);
2220                    }
2221                } else if (mPermissionReviewRequired) {
2222                    // In permission review mode we clear the review flag when we
2223                    // are asked to install the app with all permissions granted.
2224                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2225                        updatePermissionFlags(permission, pkg.packageName,
2226                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2227                    }
2228                }
2229            }
2230        }
2231    }
2232
2233    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2234        Bundle extras = null;
2235        switch (res.returnCode) {
2236            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2237                extras = new Bundle();
2238                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2239                        res.origPermission);
2240                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2241                        res.origPackage);
2242                break;
2243            }
2244            case PackageManager.INSTALL_SUCCEEDED: {
2245                extras = new Bundle();
2246                extras.putBoolean(Intent.EXTRA_REPLACING,
2247                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2248                break;
2249            }
2250        }
2251        return extras;
2252    }
2253
2254    void scheduleWriteSettingsLocked() {
2255        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2256            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2257        }
2258    }
2259
2260    void scheduleWritePackageListLocked(int userId) {
2261        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2262            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2263            msg.arg1 = userId;
2264            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2265        }
2266    }
2267
2268    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2269        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2270        scheduleWritePackageRestrictionsLocked(userId);
2271    }
2272
2273    void scheduleWritePackageRestrictionsLocked(int userId) {
2274        final int[] userIds = (userId == UserHandle.USER_ALL)
2275                ? sUserManager.getUserIds() : new int[]{userId};
2276        for (int nextUserId : userIds) {
2277            if (!sUserManager.exists(nextUserId)) return;
2278            mDirtyUsers.add(nextUserId);
2279            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2280                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2281            }
2282        }
2283    }
2284
2285    public static PackageManagerService main(Context context, Installer installer,
2286            boolean factoryTest, boolean onlyCore) {
2287        // Self-check for initial settings.
2288        PackageManagerServiceCompilerMapping.checkProperties();
2289
2290        PackageManagerService m = new PackageManagerService(context, installer,
2291                factoryTest, onlyCore);
2292        m.enableSystemUserPackages();
2293        ServiceManager.addService("package", m);
2294        return m;
2295    }
2296
2297    private void enableSystemUserPackages() {
2298        if (!UserManager.isSplitSystemUser()) {
2299            return;
2300        }
2301        // For system user, enable apps based on the following conditions:
2302        // - app is whitelisted or belong to one of these groups:
2303        //   -- system app which has no launcher icons
2304        //   -- system app which has INTERACT_ACROSS_USERS permission
2305        //   -- system IME app
2306        // - app is not in the blacklist
2307        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2308        Set<String> enableApps = new ArraySet<>();
2309        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2310                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2311                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2312        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2313        enableApps.addAll(wlApps);
2314        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2315                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2316        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2317        enableApps.removeAll(blApps);
2318        Log.i(TAG, "Applications installed for system user: " + enableApps);
2319        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2320                UserHandle.SYSTEM);
2321        final int allAppsSize = allAps.size();
2322        synchronized (mPackages) {
2323            for (int i = 0; i < allAppsSize; i++) {
2324                String pName = allAps.get(i);
2325                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2326                // Should not happen, but we shouldn't be failing if it does
2327                if (pkgSetting == null) {
2328                    continue;
2329                }
2330                boolean install = enableApps.contains(pName);
2331                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2332                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2333                            + " for system user");
2334                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2335                }
2336            }
2337            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2338        }
2339    }
2340
2341    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2342        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2343                Context.DISPLAY_SERVICE);
2344        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2345    }
2346
2347    /**
2348     * Requests that files preopted on a secondary system partition be copied to the data partition
2349     * if possible.  Note that the actual copying of the files is accomplished by init for security
2350     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2351     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2352     */
2353    private static void requestCopyPreoptedFiles() {
2354        final int WAIT_TIME_MS = 100;
2355        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2356        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2357            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2358            // We will wait for up to 100 seconds.
2359            final long timeStart = SystemClock.uptimeMillis();
2360            final long timeEnd = timeStart + 100 * 1000;
2361            long timeNow = timeStart;
2362            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2363                try {
2364                    Thread.sleep(WAIT_TIME_MS);
2365                } catch (InterruptedException e) {
2366                    // Do nothing
2367                }
2368                timeNow = SystemClock.uptimeMillis();
2369                if (timeNow > timeEnd) {
2370                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2371                    Slog.wtf(TAG, "cppreopt did not finish!");
2372                    break;
2373                }
2374            }
2375
2376            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2377        }
2378    }
2379
2380    public PackageManagerService(Context context, Installer installer,
2381            boolean factoryTest, boolean onlyCore) {
2382        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2383        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2384        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2385                SystemClock.uptimeMillis());
2386
2387        if (mSdkVersion <= 0) {
2388            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2389        }
2390
2391        mContext = context;
2392
2393        mPermissionReviewRequired = context.getResources().getBoolean(
2394                R.bool.config_permissionReviewRequired);
2395
2396        mFactoryTest = factoryTest;
2397        mOnlyCore = onlyCore;
2398        mMetrics = new DisplayMetrics();
2399        mSettings = new Settings(mPackages);
2400        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2401                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2402        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2407                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2409                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2410        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2411                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2412
2413        String separateProcesses = SystemProperties.get("debug.separate_processes");
2414        if (separateProcesses != null && separateProcesses.length() > 0) {
2415            if ("*".equals(separateProcesses)) {
2416                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2417                mSeparateProcesses = null;
2418                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2419            } else {
2420                mDefParseFlags = 0;
2421                mSeparateProcesses = separateProcesses.split(",");
2422                Slog.w(TAG, "Running with debug.separate_processes: "
2423                        + separateProcesses);
2424            }
2425        } else {
2426            mDefParseFlags = 0;
2427            mSeparateProcesses = null;
2428        }
2429
2430        mInstaller = installer;
2431        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2432                "*dexopt*");
2433        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2434        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2435
2436        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2437                FgThread.get().getLooper());
2438
2439        getDefaultDisplayMetrics(context, mMetrics);
2440
2441        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2442        SystemConfig systemConfig = SystemConfig.getInstance();
2443        mGlobalGids = systemConfig.getGlobalGids();
2444        mSystemPermissions = systemConfig.getSystemPermissions();
2445        mAvailableFeatures = systemConfig.getAvailableFeatures();
2446        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2447
2448        mProtectedPackages = new ProtectedPackages(mContext);
2449
2450        synchronized (mInstallLock) {
2451        // writer
2452        synchronized (mPackages) {
2453            mHandlerThread = new ServiceThread(TAG,
2454                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2455            mHandlerThread.start();
2456            mHandler = new PackageHandler(mHandlerThread.getLooper());
2457            mProcessLoggingHandler = new ProcessLoggingHandler();
2458            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2459
2460            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2461            mInstantAppRegistry = new InstantAppRegistry(this);
2462
2463            File dataDir = Environment.getDataDirectory();
2464            mAppInstallDir = new File(dataDir, "app");
2465            mAppLib32InstallDir = new File(dataDir, "app-lib");
2466            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2467            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2468            sUserManager = new UserManagerService(context, this,
2469                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2470
2471            // Propagate permission configuration in to package manager.
2472            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2473                    = systemConfig.getPermissions();
2474            for (int i=0; i<permConfig.size(); i++) {
2475                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2476                BasePermission bp = mSettings.mPermissions.get(perm.name);
2477                if (bp == null) {
2478                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2479                    mSettings.mPermissions.put(perm.name, bp);
2480                }
2481                if (perm.gids != null) {
2482                    bp.setGids(perm.gids, perm.perUser);
2483                }
2484            }
2485
2486            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2487            final int builtInLibCount = libConfig.size();
2488            for (int i = 0; i < builtInLibCount; i++) {
2489                String name = libConfig.keyAt(i);
2490                String path = libConfig.valueAt(i);
2491                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2492                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2493            }
2494
2495            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2496
2497            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2498            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2499            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2500
2501            // Clean up orphaned packages for which the code path doesn't exist
2502            // and they are an update to a system app - caused by bug/32321269
2503            final int packageSettingCount = mSettings.mPackages.size();
2504            for (int i = packageSettingCount - 1; i >= 0; i--) {
2505                PackageSetting ps = mSettings.mPackages.valueAt(i);
2506                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2507                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2508                    mSettings.mPackages.removeAt(i);
2509                    mSettings.enableSystemPackageLPw(ps.name);
2510                }
2511            }
2512
2513            if (mFirstBoot) {
2514                requestCopyPreoptedFiles();
2515            }
2516
2517            String customResolverActivity = Resources.getSystem().getString(
2518                    R.string.config_customResolverActivity);
2519            if (TextUtils.isEmpty(customResolverActivity)) {
2520                customResolverActivity = null;
2521            } else {
2522                mCustomResolverComponentName = ComponentName.unflattenFromString(
2523                        customResolverActivity);
2524            }
2525
2526            long startTime = SystemClock.uptimeMillis();
2527
2528            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2529                    startTime);
2530
2531            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2532            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2533
2534            if (bootClassPath == null) {
2535                Slog.w(TAG, "No BOOTCLASSPATH found!");
2536            }
2537
2538            if (systemServerClassPath == null) {
2539                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2540            }
2541
2542            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2543
2544            final VersionInfo ver = mSettings.getInternalVersion();
2545            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2546            if (mIsUpgrade) {
2547                logCriticalInfo(Log.INFO,
2548                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2549            }
2550
2551            // when upgrading from pre-M, promote system app permissions from install to runtime
2552            mPromoteSystemApps =
2553                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2554
2555            // When upgrading from pre-N, we need to handle package extraction like first boot,
2556            // as there is no profiling data available.
2557            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2558
2559            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2560
2561            // save off the names of pre-existing system packages prior to scanning; we don't
2562            // want to automatically grant runtime permissions for new system apps
2563            if (mPromoteSystemApps) {
2564                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2565                while (pkgSettingIter.hasNext()) {
2566                    PackageSetting ps = pkgSettingIter.next();
2567                    if (isSystemApp(ps)) {
2568                        mExistingSystemPackages.add(ps.name);
2569                    }
2570                }
2571            }
2572
2573            mCacheDir = preparePackageParserCache(mIsUpgrade);
2574
2575            // Set flag to monitor and not change apk file paths when
2576            // scanning install directories.
2577            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2578
2579            if (mIsUpgrade || mFirstBoot) {
2580                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2581            }
2582
2583            // Collect vendor overlay packages. (Do this before scanning any apps.)
2584            // For security and version matching reason, only consider
2585            // overlay packages if they reside in the right directory.
2586            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2587                    | PackageParser.PARSE_IS_SYSTEM
2588                    | PackageParser.PARSE_IS_SYSTEM_DIR
2589                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2590
2591            mParallelPackageParserCallback.findStaticOverlayPackages();
2592
2593            // Find base frameworks (resource packages without code).
2594            scanDirTracedLI(frameworkDir, mDefParseFlags
2595                    | PackageParser.PARSE_IS_SYSTEM
2596                    | PackageParser.PARSE_IS_SYSTEM_DIR
2597                    | PackageParser.PARSE_IS_PRIVILEGED,
2598                    scanFlags | SCAN_NO_DEX, 0);
2599
2600            // Collected privileged system packages.
2601            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2602            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2603                    | PackageParser.PARSE_IS_SYSTEM
2604                    | PackageParser.PARSE_IS_SYSTEM_DIR
2605                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2606
2607            // Collect ordinary system packages.
2608            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2609            scanDirTracedLI(systemAppDir, mDefParseFlags
2610                    | PackageParser.PARSE_IS_SYSTEM
2611                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2612
2613            // Collect all vendor packages.
2614            File vendorAppDir = new File("/vendor/app");
2615            try {
2616                vendorAppDir = vendorAppDir.getCanonicalFile();
2617            } catch (IOException e) {
2618                // failed to look up canonical path, continue with original one
2619            }
2620            scanDirTracedLI(vendorAppDir, mDefParseFlags
2621                    | PackageParser.PARSE_IS_SYSTEM
2622                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2623
2624            // Collect all OEM packages.
2625            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2626            scanDirTracedLI(oemAppDir, mDefParseFlags
2627                    | PackageParser.PARSE_IS_SYSTEM
2628                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2629
2630            // Prune any system packages that no longer exist.
2631            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2632            if (!mOnlyCore) {
2633                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2634                while (psit.hasNext()) {
2635                    PackageSetting ps = psit.next();
2636
2637                    /*
2638                     * If this is not a system app, it can't be a
2639                     * disable system app.
2640                     */
2641                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2642                        continue;
2643                    }
2644
2645                    /*
2646                     * If the package is scanned, it's not erased.
2647                     */
2648                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2649                    if (scannedPkg != null) {
2650                        /*
2651                         * If the system app is both scanned and in the
2652                         * disabled packages list, then it must have been
2653                         * added via OTA. Remove it from the currently
2654                         * scanned package so the previously user-installed
2655                         * application can be scanned.
2656                         */
2657                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2658                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2659                                    + ps.name + "; removing system app.  Last known codePath="
2660                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2661                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2662                                    + scannedPkg.mVersionCode);
2663                            removePackageLI(scannedPkg, true);
2664                            mExpectingBetter.put(ps.name, ps.codePath);
2665                        }
2666
2667                        continue;
2668                    }
2669
2670                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2671                        psit.remove();
2672                        logCriticalInfo(Log.WARN, "System package " + ps.name
2673                                + " no longer exists; it's data will be wiped");
2674                        // Actual deletion of code and data will be handled by later
2675                        // reconciliation step
2676                    } else {
2677                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2678                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2679                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2680                        }
2681                    }
2682                }
2683            }
2684
2685            //look for any incomplete package installations
2686            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2687            for (int i = 0; i < deletePkgsList.size(); i++) {
2688                // Actual deletion of code and data will be handled by later
2689                // reconciliation step
2690                final String packageName = deletePkgsList.get(i).name;
2691                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2692                synchronized (mPackages) {
2693                    mSettings.removePackageLPw(packageName);
2694                }
2695            }
2696
2697            //delete tmp files
2698            deleteTempPackageFiles();
2699
2700            // Remove any shared userIDs that have no associated packages
2701            mSettings.pruneSharedUsersLPw();
2702
2703            if (!mOnlyCore) {
2704                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2705                        SystemClock.uptimeMillis());
2706                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2707
2708                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2709                        | PackageParser.PARSE_FORWARD_LOCK,
2710                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2711
2712                /**
2713                 * Remove disable package settings for any updated system
2714                 * apps that were removed via an OTA. If they're not a
2715                 * previously-updated app, remove them completely.
2716                 * Otherwise, just revoke their system-level permissions.
2717                 */
2718                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2719                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2720                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2721
2722                    String msg;
2723                    if (deletedPkg == null) {
2724                        msg = "Updated system package " + deletedAppName
2725                                + " no longer exists; it's data will be wiped";
2726                        // Actual deletion of code and data will be handled by later
2727                        // reconciliation step
2728                    } else {
2729                        msg = "Updated system app + " + deletedAppName
2730                                + " no longer present; removing system privileges for "
2731                                + deletedAppName;
2732
2733                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2734
2735                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2736                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2737                    }
2738                    logCriticalInfo(Log.WARN, msg);
2739                }
2740
2741                /**
2742                 * Make sure all system apps that we expected to appear on
2743                 * the userdata partition actually showed up. If they never
2744                 * appeared, crawl back and revive the system version.
2745                 */
2746                for (int i = 0; i < mExpectingBetter.size(); i++) {
2747                    final String packageName = mExpectingBetter.keyAt(i);
2748                    if (!mPackages.containsKey(packageName)) {
2749                        final File scanFile = mExpectingBetter.valueAt(i);
2750
2751                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2752                                + " but never showed up; reverting to system");
2753
2754                        int reparseFlags = mDefParseFlags;
2755                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2756                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2757                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2758                                    | PackageParser.PARSE_IS_PRIVILEGED;
2759                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2760                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2761                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2762                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2763                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2764                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2765                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2766                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2767                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2768                        } else {
2769                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2770                            continue;
2771                        }
2772
2773                        mSettings.enableSystemPackageLPw(packageName);
2774
2775                        try {
2776                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2777                        } catch (PackageManagerException e) {
2778                            Slog.e(TAG, "Failed to parse original system package: "
2779                                    + e.getMessage());
2780                        }
2781                    }
2782                }
2783            }
2784            mExpectingBetter.clear();
2785
2786            // Resolve the storage manager.
2787            mStorageManagerPackage = getStorageManagerPackageName();
2788
2789            // Resolve protected action filters. Only the setup wizard is allowed to
2790            // have a high priority filter for these actions.
2791            mSetupWizardPackage = getSetupWizardPackageName();
2792            if (mProtectedFilters.size() > 0) {
2793                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2794                    Slog.i(TAG, "No setup wizard;"
2795                        + " All protected intents capped to priority 0");
2796                }
2797                for (ActivityIntentInfo filter : mProtectedFilters) {
2798                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2799                        if (DEBUG_FILTERS) {
2800                            Slog.i(TAG, "Found setup wizard;"
2801                                + " allow priority " + filter.getPriority() + ";"
2802                                + " package: " + filter.activity.info.packageName
2803                                + " activity: " + filter.activity.className
2804                                + " priority: " + filter.getPriority());
2805                        }
2806                        // skip setup wizard; allow it to keep the high priority filter
2807                        continue;
2808                    }
2809                    if (DEBUG_FILTERS) {
2810                        Slog.i(TAG, "Protected action; cap priority to 0;"
2811                                + " package: " + filter.activity.info.packageName
2812                                + " activity: " + filter.activity.className
2813                                + " origPrio: " + filter.getPriority());
2814                    }
2815                    filter.setPriority(0);
2816                }
2817            }
2818            mDeferProtectedFilters = false;
2819            mProtectedFilters.clear();
2820
2821            // Now that we know all of the shared libraries, update all clients to have
2822            // the correct library paths.
2823            updateAllSharedLibrariesLPw(null);
2824
2825            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2826                // NOTE: We ignore potential failures here during a system scan (like
2827                // the rest of the commands above) because there's precious little we
2828                // can do about it. A settings error is reported, though.
2829                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2830            }
2831
2832            // Now that we know all the packages we are keeping,
2833            // read and update their last usage times.
2834            mPackageUsage.read(mPackages);
2835            mCompilerStats.read();
2836
2837            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2838                    SystemClock.uptimeMillis());
2839            Slog.i(TAG, "Time to scan packages: "
2840                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2841                    + " seconds");
2842
2843            // If the platform SDK has changed since the last time we booted,
2844            // we need to re-grant app permission to catch any new ones that
2845            // appear.  This is really a hack, and means that apps can in some
2846            // cases get permissions that the user didn't initially explicitly
2847            // allow...  it would be nice to have some better way to handle
2848            // this situation.
2849            int updateFlags = UPDATE_PERMISSIONS_ALL;
2850            if (ver.sdkVersion != mSdkVersion) {
2851                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2852                        + mSdkVersion + "; regranting permissions for internal storage");
2853                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2854            }
2855            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2856            ver.sdkVersion = mSdkVersion;
2857
2858            // If this is the first boot or an update from pre-M, and it is a normal
2859            // boot, then we need to initialize the default preferred apps across
2860            // all defined users.
2861            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2862                for (UserInfo user : sUserManager.getUsers(true)) {
2863                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2864                    applyFactoryDefaultBrowserLPw(user.id);
2865                    primeDomainVerificationsLPw(user.id);
2866                }
2867            }
2868
2869            // Prepare storage for system user really early during boot,
2870            // since core system apps like SettingsProvider and SystemUI
2871            // can't wait for user to start
2872            final int storageFlags;
2873            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2874                storageFlags = StorageManager.FLAG_STORAGE_DE;
2875            } else {
2876                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2877            }
2878            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2879                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2880                    true /* onlyCoreApps */);
2881            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2882                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2883                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2884                traceLog.traceBegin("AppDataFixup");
2885                try {
2886                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2887                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2888                } catch (InstallerException e) {
2889                    Slog.w(TAG, "Trouble fixing GIDs", e);
2890                }
2891                traceLog.traceEnd();
2892
2893                traceLog.traceBegin("AppDataPrepare");
2894                if (deferPackages == null || deferPackages.isEmpty()) {
2895                    return;
2896                }
2897                int count = 0;
2898                for (String pkgName : deferPackages) {
2899                    PackageParser.Package pkg = null;
2900                    synchronized (mPackages) {
2901                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2902                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2903                            pkg = ps.pkg;
2904                        }
2905                    }
2906                    if (pkg != null) {
2907                        synchronized (mInstallLock) {
2908                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2909                                    true /* maybeMigrateAppData */);
2910                        }
2911                        count++;
2912                    }
2913                }
2914                traceLog.traceEnd();
2915                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2916            }, "prepareAppData");
2917
2918            // If this is first boot after an OTA, and a normal boot, then
2919            // we need to clear code cache directories.
2920            // Note that we do *not* clear the application profiles. These remain valid
2921            // across OTAs and are used to drive profile verification (post OTA) and
2922            // profile compilation (without waiting to collect a fresh set of profiles).
2923            if (mIsUpgrade && !onlyCore) {
2924                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2925                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2926                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2927                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2928                        // No apps are running this early, so no need to freeze
2929                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2930                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2931                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2932                    }
2933                }
2934                ver.fingerprint = Build.FINGERPRINT;
2935            }
2936
2937            checkDefaultBrowser();
2938
2939            // clear only after permissions and other defaults have been updated
2940            mExistingSystemPackages.clear();
2941            mPromoteSystemApps = false;
2942
2943            // All the changes are done during package scanning.
2944            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2945
2946            // can downgrade to reader
2947            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2948            mSettings.writeLPr();
2949            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2950            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2951                    SystemClock.uptimeMillis());
2952
2953            if (!mOnlyCore) {
2954                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2955                mRequiredInstallerPackage = getRequiredInstallerLPr();
2956                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2957                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2958                if (mIntentFilterVerifierComponent != null) {
2959                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2960                            mIntentFilterVerifierComponent);
2961                } else {
2962                    mIntentFilterVerifier = null;
2963                }
2964                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2965                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2966                        SharedLibraryInfo.VERSION_UNDEFINED);
2967                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2968                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2969                        SharedLibraryInfo.VERSION_UNDEFINED);
2970            } else {
2971                mRequiredVerifierPackage = null;
2972                mRequiredInstallerPackage = null;
2973                mRequiredUninstallerPackage = null;
2974                mIntentFilterVerifierComponent = null;
2975                mIntentFilterVerifier = null;
2976                mServicesSystemSharedLibraryPackageName = null;
2977                mSharedSystemSharedLibraryPackageName = null;
2978            }
2979
2980            mInstallerService = new PackageInstallerService(context, this);
2981            final Pair<ComponentName, String> instantAppResolverComponent =
2982                    getInstantAppResolverLPr();
2983            if (instantAppResolverComponent != null) {
2984                if (DEBUG_EPHEMERAL) {
2985                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2986                }
2987                mInstantAppResolverConnection = new EphemeralResolverConnection(
2988                        mContext, instantAppResolverComponent.first,
2989                        instantAppResolverComponent.second);
2990                mInstantAppResolverSettingsComponent =
2991                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2992            } else {
2993                mInstantAppResolverConnection = null;
2994                mInstantAppResolverSettingsComponent = null;
2995            }
2996            updateInstantAppInstallerLocked(null);
2997
2998            // Read and update the usage of dex files.
2999            // Do this at the end of PM init so that all the packages have their
3000            // data directory reconciled.
3001            // At this point we know the code paths of the packages, so we can validate
3002            // the disk file and build the internal cache.
3003            // The usage file is expected to be small so loading and verifying it
3004            // should take a fairly small time compare to the other activities (e.g. package
3005            // scanning).
3006            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3007            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3008            for (int userId : currentUserIds) {
3009                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3010            }
3011            mDexManager.load(userPackages);
3012        } // synchronized (mPackages)
3013        } // synchronized (mInstallLock)
3014
3015        // Now after opening every single application zip, make sure they
3016        // are all flushed.  Not really needed, but keeps things nice and
3017        // tidy.
3018        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3019        Runtime.getRuntime().gc();
3020        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3021
3022        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3023        FallbackCategoryProvider.loadFallbacks();
3024        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3025
3026        // The initial scanning above does many calls into installd while
3027        // holding the mPackages lock, but we're mostly interested in yelling
3028        // once we have a booted system.
3029        mInstaller.setWarnIfHeld(mPackages);
3030
3031        // Expose private service for system components to use.
3032        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3033        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3034    }
3035
3036    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3037        // we're only interested in updating the installer appliction when 1) it's not
3038        // already set or 2) the modified package is the installer
3039        if (mInstantAppInstallerActivity != null
3040                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3041                        .equals(modifiedPackage)) {
3042            return;
3043        }
3044        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3045    }
3046
3047    private static File preparePackageParserCache(boolean isUpgrade) {
3048        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3049            return null;
3050        }
3051
3052        // Disable package parsing on eng builds to allow for faster incremental development.
3053        if ("eng".equals(Build.TYPE)) {
3054            return null;
3055        }
3056
3057        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3058            Slog.i(TAG, "Disabling package parser cache due to system property.");
3059            return null;
3060        }
3061
3062        // The base directory for the package parser cache lives under /data/system/.
3063        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3064                "package_cache");
3065        if (cacheBaseDir == null) {
3066            return null;
3067        }
3068
3069        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3070        // This also serves to "GC" unused entries when the package cache version changes (which
3071        // can only happen during upgrades).
3072        if (isUpgrade) {
3073            FileUtils.deleteContents(cacheBaseDir);
3074        }
3075
3076
3077        // Return the versioned package cache directory. This is something like
3078        // "/data/system/package_cache/1"
3079        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3080
3081        // The following is a workaround to aid development on non-numbered userdebug
3082        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3083        // the system partition is newer.
3084        //
3085        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3086        // that starts with "eng." to signify that this is an engineering build and not
3087        // destined for release.
3088        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3089            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3090
3091            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3092            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3093            // in general and should not be used for production changes. In this specific case,
3094            // we know that they will work.
3095            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3096            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3097                FileUtils.deleteContents(cacheBaseDir);
3098                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3099            }
3100        }
3101
3102        return cacheDir;
3103    }
3104
3105    @Override
3106    public boolean isFirstBoot() {
3107        // allow instant applications
3108        return mFirstBoot;
3109    }
3110
3111    @Override
3112    public boolean isOnlyCoreApps() {
3113        // allow instant applications
3114        return mOnlyCore;
3115    }
3116
3117    @Override
3118    public boolean isUpgrade() {
3119        // allow instant applications
3120        return mIsUpgrade;
3121    }
3122
3123    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3124        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3125
3126        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3127                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3128                UserHandle.USER_SYSTEM);
3129        if (matches.size() == 1) {
3130            return matches.get(0).getComponentInfo().packageName;
3131        } else if (matches.size() == 0) {
3132            Log.e(TAG, "There should probably be a verifier, but, none were found");
3133            return null;
3134        }
3135        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3136    }
3137
3138    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3139        synchronized (mPackages) {
3140            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3141            if (libraryEntry == null) {
3142                throw new IllegalStateException("Missing required shared library:" + name);
3143            }
3144            return libraryEntry.apk;
3145        }
3146    }
3147
3148    private @NonNull String getRequiredInstallerLPr() {
3149        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3150        intent.addCategory(Intent.CATEGORY_DEFAULT);
3151        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3152
3153        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3154                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3155                UserHandle.USER_SYSTEM);
3156        if (matches.size() == 1) {
3157            ResolveInfo resolveInfo = matches.get(0);
3158            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3159                throw new RuntimeException("The installer must be a privileged app");
3160            }
3161            return matches.get(0).getComponentInfo().packageName;
3162        } else {
3163            throw new RuntimeException("There must be exactly one installer; found " + matches);
3164        }
3165    }
3166
3167    private @NonNull String getRequiredUninstallerLPr() {
3168        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3169        intent.addCategory(Intent.CATEGORY_DEFAULT);
3170        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3171
3172        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3173                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3174                UserHandle.USER_SYSTEM);
3175        if (resolveInfo == null ||
3176                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3177            throw new RuntimeException("There must be exactly one uninstaller; found "
3178                    + resolveInfo);
3179        }
3180        return resolveInfo.getComponentInfo().packageName;
3181    }
3182
3183    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3184        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3185
3186        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3187                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3188                UserHandle.USER_SYSTEM);
3189        ResolveInfo best = null;
3190        final int N = matches.size();
3191        for (int i = 0; i < N; i++) {
3192            final ResolveInfo cur = matches.get(i);
3193            final String packageName = cur.getComponentInfo().packageName;
3194            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3195                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3196                continue;
3197            }
3198
3199            if (best == null || cur.priority > best.priority) {
3200                best = cur;
3201            }
3202        }
3203
3204        if (best != null) {
3205            return best.getComponentInfo().getComponentName();
3206        }
3207        Slog.w(TAG, "Intent filter verifier not found");
3208        return null;
3209    }
3210
3211    @Override
3212    public @Nullable ComponentName getInstantAppResolverComponent() {
3213        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3214            return null;
3215        }
3216        synchronized (mPackages) {
3217            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3218            if (instantAppResolver == null) {
3219                return null;
3220            }
3221            return instantAppResolver.first;
3222        }
3223    }
3224
3225    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3226        final String[] packageArray =
3227                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3228        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3229            if (DEBUG_EPHEMERAL) {
3230                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3231            }
3232            return null;
3233        }
3234
3235        final int callingUid = Binder.getCallingUid();
3236        final int resolveFlags =
3237                MATCH_DIRECT_BOOT_AWARE
3238                | MATCH_DIRECT_BOOT_UNAWARE
3239                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3240        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3241        final Intent resolverIntent = new Intent(actionName);
3242        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3243                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3244        // temporarily look for the old action
3245        if (resolvers.size() == 0) {
3246            if (DEBUG_EPHEMERAL) {
3247                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3248            }
3249            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3250            resolverIntent.setAction(actionName);
3251            resolvers = queryIntentServicesInternal(resolverIntent, null,
3252                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3253        }
3254        final int N = resolvers.size();
3255        if (N == 0) {
3256            if (DEBUG_EPHEMERAL) {
3257                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3258            }
3259            return null;
3260        }
3261
3262        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3263        for (int i = 0; i < N; i++) {
3264            final ResolveInfo info = resolvers.get(i);
3265
3266            if (info.serviceInfo == null) {
3267                continue;
3268            }
3269
3270            final String packageName = info.serviceInfo.packageName;
3271            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3272                if (DEBUG_EPHEMERAL) {
3273                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3274                            + " pkg: " + packageName + ", info:" + info);
3275                }
3276                continue;
3277            }
3278
3279            if (DEBUG_EPHEMERAL) {
3280                Slog.v(TAG, "Ephemeral resolver found;"
3281                        + " pkg: " + packageName + ", info:" + info);
3282            }
3283            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3284        }
3285        if (DEBUG_EPHEMERAL) {
3286            Slog.v(TAG, "Ephemeral resolver NOT found");
3287        }
3288        return null;
3289    }
3290
3291    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3292        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3293        intent.addCategory(Intent.CATEGORY_DEFAULT);
3294        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3295
3296        final int resolveFlags =
3297                MATCH_DIRECT_BOOT_AWARE
3298                | MATCH_DIRECT_BOOT_UNAWARE
3299                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3300        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3301                resolveFlags, UserHandle.USER_SYSTEM);
3302        // temporarily look for the old action
3303        if (matches.isEmpty()) {
3304            if (DEBUG_EPHEMERAL) {
3305                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3306            }
3307            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3308            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3309                    resolveFlags, UserHandle.USER_SYSTEM);
3310        }
3311        Iterator<ResolveInfo> iter = matches.iterator();
3312        while (iter.hasNext()) {
3313            final ResolveInfo rInfo = iter.next();
3314            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3315            if (ps != null) {
3316                final PermissionsState permissionsState = ps.getPermissionsState();
3317                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3318                    continue;
3319                }
3320            }
3321            iter.remove();
3322        }
3323        if (matches.size() == 0) {
3324            return null;
3325        } else if (matches.size() == 1) {
3326            return (ActivityInfo) matches.get(0).getComponentInfo();
3327        } else {
3328            throw new RuntimeException(
3329                    "There must be at most one ephemeral installer; found " + matches);
3330        }
3331    }
3332
3333    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3334            @NonNull ComponentName resolver) {
3335        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3336                .addCategory(Intent.CATEGORY_DEFAULT)
3337                .setPackage(resolver.getPackageName());
3338        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3339        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3340                UserHandle.USER_SYSTEM);
3341        // temporarily look for the old action
3342        if (matches.isEmpty()) {
3343            if (DEBUG_EPHEMERAL) {
3344                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3345            }
3346            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3347            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3348                    UserHandle.USER_SYSTEM);
3349        }
3350        if (matches.isEmpty()) {
3351            return null;
3352        }
3353        return matches.get(0).getComponentInfo().getComponentName();
3354    }
3355
3356    private void primeDomainVerificationsLPw(int userId) {
3357        if (DEBUG_DOMAIN_VERIFICATION) {
3358            Slog.d(TAG, "Priming domain verifications in user " + userId);
3359        }
3360
3361        SystemConfig systemConfig = SystemConfig.getInstance();
3362        ArraySet<String> packages = systemConfig.getLinkedApps();
3363
3364        for (String packageName : packages) {
3365            PackageParser.Package pkg = mPackages.get(packageName);
3366            if (pkg != null) {
3367                if (!pkg.isSystemApp()) {
3368                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3369                    continue;
3370                }
3371
3372                ArraySet<String> domains = null;
3373                for (PackageParser.Activity a : pkg.activities) {
3374                    for (ActivityIntentInfo filter : a.intents) {
3375                        if (hasValidDomains(filter)) {
3376                            if (domains == null) {
3377                                domains = new ArraySet<String>();
3378                            }
3379                            domains.addAll(filter.getHostsList());
3380                        }
3381                    }
3382                }
3383
3384                if (domains != null && domains.size() > 0) {
3385                    if (DEBUG_DOMAIN_VERIFICATION) {
3386                        Slog.v(TAG, "      + " + packageName);
3387                    }
3388                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3389                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3390                    // and then 'always' in the per-user state actually used for intent resolution.
3391                    final IntentFilterVerificationInfo ivi;
3392                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3393                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3394                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3395                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3396                } else {
3397                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3398                            + "' does not handle web links");
3399                }
3400            } else {
3401                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3402            }
3403        }
3404
3405        scheduleWritePackageRestrictionsLocked(userId);
3406        scheduleWriteSettingsLocked();
3407    }
3408
3409    private void applyFactoryDefaultBrowserLPw(int userId) {
3410        // The default browser app's package name is stored in a string resource,
3411        // with a product-specific overlay used for vendor customization.
3412        String browserPkg = mContext.getResources().getString(
3413                com.android.internal.R.string.default_browser);
3414        if (!TextUtils.isEmpty(browserPkg)) {
3415            // non-empty string => required to be a known package
3416            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3417            if (ps == null) {
3418                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3419                browserPkg = null;
3420            } else {
3421                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3422            }
3423        }
3424
3425        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3426        // default.  If there's more than one, just leave everything alone.
3427        if (browserPkg == null) {
3428            calculateDefaultBrowserLPw(userId);
3429        }
3430    }
3431
3432    private void calculateDefaultBrowserLPw(int userId) {
3433        List<String> allBrowsers = resolveAllBrowserApps(userId);
3434        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3435        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3436    }
3437
3438    private List<String> resolveAllBrowserApps(int userId) {
3439        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3440        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3441                PackageManager.MATCH_ALL, userId);
3442
3443        final int count = list.size();
3444        List<String> result = new ArrayList<String>(count);
3445        for (int i=0; i<count; i++) {
3446            ResolveInfo info = list.get(i);
3447            if (info.activityInfo == null
3448                    || !info.handleAllWebDataURI
3449                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3450                    || result.contains(info.activityInfo.packageName)) {
3451                continue;
3452            }
3453            result.add(info.activityInfo.packageName);
3454        }
3455
3456        return result;
3457    }
3458
3459    private boolean packageIsBrowser(String packageName, int userId) {
3460        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3461                PackageManager.MATCH_ALL, userId);
3462        final int N = list.size();
3463        for (int i = 0; i < N; i++) {
3464            ResolveInfo info = list.get(i);
3465            if (packageName.equals(info.activityInfo.packageName)) {
3466                return true;
3467            }
3468        }
3469        return false;
3470    }
3471
3472    private void checkDefaultBrowser() {
3473        final int myUserId = UserHandle.myUserId();
3474        final String packageName = getDefaultBrowserPackageName(myUserId);
3475        if (packageName != null) {
3476            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3477            if (info == null) {
3478                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3479                synchronized (mPackages) {
3480                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3481                }
3482            }
3483        }
3484    }
3485
3486    @Override
3487    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3488            throws RemoteException {
3489        try {
3490            return super.onTransact(code, data, reply, flags);
3491        } catch (RuntimeException e) {
3492            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3493                Slog.wtf(TAG, "Package Manager Crash", e);
3494            }
3495            throw e;
3496        }
3497    }
3498
3499    static int[] appendInts(int[] cur, int[] add) {
3500        if (add == null) return cur;
3501        if (cur == null) return add;
3502        final int N = add.length;
3503        for (int i=0; i<N; i++) {
3504            cur = appendInt(cur, add[i]);
3505        }
3506        return cur;
3507    }
3508
3509    /**
3510     * Returns whether or not a full application can see an instant application.
3511     * <p>
3512     * Currently, there are three cases in which this can occur:
3513     * <ol>
3514     * <li>The calling application is a "special" process. The special
3515     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3516     *     and {@code 0}</li>
3517     * <li>The calling application has the permission
3518     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3519     * <li>The calling application is the default launcher on the
3520     *     system partition.</li>
3521     * </ol>
3522     */
3523    private boolean canViewInstantApps(int callingUid, int userId) {
3524        if (callingUid == Process.SYSTEM_UID
3525                || callingUid == Process.SHELL_UID
3526                || callingUid == Process.ROOT_UID) {
3527            return true;
3528        }
3529        if (mContext.checkCallingOrSelfPermission(
3530                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3531            return true;
3532        }
3533        if (mContext.checkCallingOrSelfPermission(
3534                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3535            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3536            if (homeComponent != null
3537                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3538                return true;
3539            }
3540        }
3541        return false;
3542    }
3543
3544    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3545        if (!sUserManager.exists(userId)) return null;
3546        if (ps == null) {
3547            return null;
3548        }
3549        PackageParser.Package p = ps.pkg;
3550        if (p == null) {
3551            return null;
3552        }
3553        final int callingUid = Binder.getCallingUid();
3554        // Filter out ephemeral app metadata:
3555        //   * The system/shell/root can see metadata for any app
3556        //   * An installed app can see metadata for 1) other installed apps
3557        //     and 2) ephemeral apps that have explicitly interacted with it
3558        //   * Ephemeral apps can only see their own data and exposed installed apps
3559        //   * Holding a signature permission allows seeing instant apps
3560        if (filterAppAccessLPr(ps, callingUid, userId)) {
3561            return null;
3562        }
3563
3564        final PermissionsState permissionsState = ps.getPermissionsState();
3565
3566        // Compute GIDs only if requested
3567        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3568                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3569        // Compute granted permissions only if package has requested permissions
3570        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3571                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3572        final PackageUserState state = ps.readUserState(userId);
3573
3574        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3575                && ps.isSystem()) {
3576            flags |= MATCH_ANY_USER;
3577        }
3578
3579        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3580                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3581
3582        if (packageInfo == null) {
3583            return null;
3584        }
3585
3586        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3587                resolveExternalPackageNameLPr(p);
3588
3589        return packageInfo;
3590    }
3591
3592    @Override
3593    public void checkPackageStartable(String packageName, int userId) {
3594        final int callingUid = Binder.getCallingUid();
3595        if (getInstantAppPackageName(callingUid) != null) {
3596            throw new SecurityException("Instant applications don't have access to this method");
3597        }
3598        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3599        synchronized (mPackages) {
3600            final PackageSetting ps = mSettings.mPackages.get(packageName);
3601            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3602                throw new SecurityException("Package " + packageName + " was not found!");
3603            }
3604
3605            if (!ps.getInstalled(userId)) {
3606                throw new SecurityException(
3607                        "Package " + packageName + " was not installed for user " + userId + "!");
3608            }
3609
3610            if (mSafeMode && !ps.isSystem()) {
3611                throw new SecurityException("Package " + packageName + " not a system app!");
3612            }
3613
3614            if (mFrozenPackages.contains(packageName)) {
3615                throw new SecurityException("Package " + packageName + " is currently frozen!");
3616            }
3617
3618            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3619                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3620                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3621            }
3622        }
3623    }
3624
3625    @Override
3626    public boolean isPackageAvailable(String packageName, int userId) {
3627        if (!sUserManager.exists(userId)) return false;
3628        final int callingUid = Binder.getCallingUid();
3629        enforceCrossUserPermission(callingUid, userId,
3630                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3631        synchronized (mPackages) {
3632            PackageParser.Package p = mPackages.get(packageName);
3633            if (p != null) {
3634                final PackageSetting ps = (PackageSetting) p.mExtras;
3635                if (filterAppAccessLPr(ps, callingUid, userId)) {
3636                    return false;
3637                }
3638                if (ps != null) {
3639                    final PackageUserState state = ps.readUserState(userId);
3640                    if (state != null) {
3641                        return PackageParser.isAvailable(state);
3642                    }
3643                }
3644            }
3645        }
3646        return false;
3647    }
3648
3649    @Override
3650    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3651        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3652                flags, Binder.getCallingUid(), userId);
3653    }
3654
3655    @Override
3656    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3657            int flags, int userId) {
3658        return getPackageInfoInternal(versionedPackage.getPackageName(),
3659                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3660    }
3661
3662    /**
3663     * Important: The provided filterCallingUid is used exclusively to filter out packages
3664     * that can be seen based on user state. It's typically the original caller uid prior
3665     * to clearing. Because it can only be provided by trusted code, it's value can be
3666     * trusted and will be used as-is; unlike userId which will be validated by this method.
3667     */
3668    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3669            int flags, int filterCallingUid, int userId) {
3670        if (!sUserManager.exists(userId)) return null;
3671        flags = updateFlagsForPackage(flags, userId, packageName);
3672        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3673                false /* requireFullPermission */, false /* checkShell */, "get package info");
3674
3675        // reader
3676        synchronized (mPackages) {
3677            // Normalize package name to handle renamed packages and static libs
3678            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3679
3680            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3681            if (matchFactoryOnly) {
3682                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3683                if (ps != null) {
3684                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3685                        return null;
3686                    }
3687                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3688                        return null;
3689                    }
3690                    return generatePackageInfo(ps, flags, userId);
3691                }
3692            }
3693
3694            PackageParser.Package p = mPackages.get(packageName);
3695            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3696                return null;
3697            }
3698            if (DEBUG_PACKAGE_INFO)
3699                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3700            if (p != null) {
3701                final PackageSetting ps = (PackageSetting) p.mExtras;
3702                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3703                    return null;
3704                }
3705                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3706                    return null;
3707                }
3708                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3709            }
3710            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3711                final PackageSetting ps = mSettings.mPackages.get(packageName);
3712                if (ps == null) return null;
3713                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3714                    return null;
3715                }
3716                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3717                    return null;
3718                }
3719                return generatePackageInfo(ps, flags, userId);
3720            }
3721        }
3722        return null;
3723    }
3724
3725    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3726        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3727            return true;
3728        }
3729        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3730            return true;
3731        }
3732        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3733            return true;
3734        }
3735        return false;
3736    }
3737
3738    private boolean isComponentVisibleToInstantApp(
3739            @Nullable ComponentName component, @ComponentType int type) {
3740        if (type == TYPE_ACTIVITY) {
3741            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3742            return activity != null
3743                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3744                    : false;
3745        } else if (type == TYPE_RECEIVER) {
3746            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3747            return activity != null
3748                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3749                    : false;
3750        } else if (type == TYPE_SERVICE) {
3751            final PackageParser.Service service = mServices.mServices.get(component);
3752            return service != null
3753                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3754                    : false;
3755        } else if (type == TYPE_PROVIDER) {
3756            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3757            return provider != null
3758                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3759                    : false;
3760        } else if (type == TYPE_UNKNOWN) {
3761            return isComponentVisibleToInstantApp(component);
3762        }
3763        return false;
3764    }
3765
3766    /**
3767     * Returns whether or not access to the application should be filtered.
3768     * <p>
3769     * Access may be limited based upon whether the calling or target applications
3770     * are instant applications.
3771     *
3772     * @see #canAccessInstantApps(int)
3773     */
3774    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3775            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3776        // if we're in an isolated process, get the real calling UID
3777        if (Process.isIsolated(callingUid)) {
3778            callingUid = mIsolatedOwners.get(callingUid);
3779        }
3780        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3781        final boolean callerIsInstantApp = instantAppPkgName != null;
3782        if (ps == null) {
3783            if (callerIsInstantApp) {
3784                // pretend the application exists, but, needs to be filtered
3785                return true;
3786            }
3787            return false;
3788        }
3789        // if the target and caller are the same application, don't filter
3790        if (isCallerSameApp(ps.name, callingUid)) {
3791            return false;
3792        }
3793        if (callerIsInstantApp) {
3794            // request for a specific component; if it hasn't been explicitly exposed, filter
3795            if (component != null) {
3796                return !isComponentVisibleToInstantApp(component, componentType);
3797            }
3798            // request for application; if no components have been explicitly exposed, filter
3799            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3800        }
3801        if (ps.getInstantApp(userId)) {
3802            // caller can see all components of all instant applications, don't filter
3803            if (canViewInstantApps(callingUid, userId)) {
3804                return false;
3805            }
3806            // request for a specific instant application component, filter
3807            if (component != null) {
3808                return true;
3809            }
3810            // request for an instant application; if the caller hasn't been granted access, filter
3811            return !mInstantAppRegistry.isInstantAccessGranted(
3812                    userId, UserHandle.getAppId(callingUid), ps.appId);
3813        }
3814        return false;
3815    }
3816
3817    /**
3818     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3819     */
3820    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3821        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3822    }
3823
3824    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3825            int flags) {
3826        // Callers can access only the libs they depend on, otherwise they need to explicitly
3827        // ask for the shared libraries given the caller is allowed to access all static libs.
3828        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3829            // System/shell/root get to see all static libs
3830            final int appId = UserHandle.getAppId(uid);
3831            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3832                    || appId == Process.ROOT_UID) {
3833                return false;
3834            }
3835        }
3836
3837        // No package means no static lib as it is always on internal storage
3838        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3839            return false;
3840        }
3841
3842        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3843                ps.pkg.staticSharedLibVersion);
3844        if (libEntry == null) {
3845            return false;
3846        }
3847
3848        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3849        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3850        if (uidPackageNames == null) {
3851            return true;
3852        }
3853
3854        for (String uidPackageName : uidPackageNames) {
3855            if (ps.name.equals(uidPackageName)) {
3856                return false;
3857            }
3858            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3859            if (uidPs != null) {
3860                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3861                        libEntry.info.getName());
3862                if (index < 0) {
3863                    continue;
3864                }
3865                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3866                    return false;
3867                }
3868            }
3869        }
3870        return true;
3871    }
3872
3873    @Override
3874    public String[] currentToCanonicalPackageNames(String[] names) {
3875        final int callingUid = Binder.getCallingUid();
3876        if (getInstantAppPackageName(callingUid) != null) {
3877            return names;
3878        }
3879        final String[] out = new String[names.length];
3880        // reader
3881        synchronized (mPackages) {
3882            final int callingUserId = UserHandle.getUserId(callingUid);
3883            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3884            for (int i=names.length-1; i>=0; i--) {
3885                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3886                boolean translateName = false;
3887                if (ps != null && ps.realName != null) {
3888                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3889                    translateName = !targetIsInstantApp
3890                            || canViewInstantApps
3891                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3892                                    UserHandle.getAppId(callingUid), ps.appId);
3893                }
3894                out[i] = translateName ? ps.realName : names[i];
3895            }
3896        }
3897        return out;
3898    }
3899
3900    @Override
3901    public String[] canonicalToCurrentPackageNames(String[] names) {
3902        final int callingUid = Binder.getCallingUid();
3903        if (getInstantAppPackageName(callingUid) != null) {
3904            return names;
3905        }
3906        final String[] out = new String[names.length];
3907        // reader
3908        synchronized (mPackages) {
3909            final int callingUserId = UserHandle.getUserId(callingUid);
3910            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3911            for (int i=names.length-1; i>=0; i--) {
3912                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3913                boolean translateName = false;
3914                if (cur != null) {
3915                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3916                    final boolean targetIsInstantApp =
3917                            ps != null && ps.getInstantApp(callingUserId);
3918                    translateName = !targetIsInstantApp
3919                            || canViewInstantApps
3920                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3921                                    UserHandle.getAppId(callingUid), ps.appId);
3922                }
3923                out[i] = translateName ? cur : names[i];
3924            }
3925        }
3926        return out;
3927    }
3928
3929    @Override
3930    public int getPackageUid(String packageName, int flags, int userId) {
3931        if (!sUserManager.exists(userId)) return -1;
3932        final int callingUid = Binder.getCallingUid();
3933        flags = updateFlagsForPackage(flags, userId, packageName);
3934        enforceCrossUserPermission(callingUid, userId,
3935                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3936
3937        // reader
3938        synchronized (mPackages) {
3939            final PackageParser.Package p = mPackages.get(packageName);
3940            if (p != null && p.isMatch(flags)) {
3941                PackageSetting ps = (PackageSetting) p.mExtras;
3942                if (filterAppAccessLPr(ps, callingUid, userId)) {
3943                    return -1;
3944                }
3945                return UserHandle.getUid(userId, p.applicationInfo.uid);
3946            }
3947            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3948                final PackageSetting ps = mSettings.mPackages.get(packageName);
3949                if (ps != null && ps.isMatch(flags)
3950                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3951                    return UserHandle.getUid(userId, ps.appId);
3952                }
3953            }
3954        }
3955
3956        return -1;
3957    }
3958
3959    @Override
3960    public int[] getPackageGids(String packageName, int flags, int userId) {
3961        if (!sUserManager.exists(userId)) return null;
3962        final int callingUid = Binder.getCallingUid();
3963        flags = updateFlagsForPackage(flags, userId, packageName);
3964        enforceCrossUserPermission(callingUid, userId,
3965                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3966
3967        // reader
3968        synchronized (mPackages) {
3969            final PackageParser.Package p = mPackages.get(packageName);
3970            if (p != null && p.isMatch(flags)) {
3971                PackageSetting ps = (PackageSetting) p.mExtras;
3972                if (filterAppAccessLPr(ps, callingUid, userId)) {
3973                    return null;
3974                }
3975                // TODO: Shouldn't this be checking for package installed state for userId and
3976                // return null?
3977                return ps.getPermissionsState().computeGids(userId);
3978            }
3979            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3980                final PackageSetting ps = mSettings.mPackages.get(packageName);
3981                if (ps != null && ps.isMatch(flags)
3982                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3983                    return ps.getPermissionsState().computeGids(userId);
3984                }
3985            }
3986        }
3987
3988        return null;
3989    }
3990
3991    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3992        if (bp.perm != null) {
3993            return PackageParser.generatePermissionInfo(bp.perm, flags);
3994        }
3995        PermissionInfo pi = new PermissionInfo();
3996        pi.name = bp.name;
3997        pi.packageName = bp.sourcePackage;
3998        pi.nonLocalizedLabel = bp.name;
3999        pi.protectionLevel = bp.protectionLevel;
4000        return pi;
4001    }
4002
4003    @Override
4004    public PermissionInfo getPermissionInfo(String name, int flags) {
4005        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4006            return null;
4007        }
4008        // reader
4009        synchronized (mPackages) {
4010            final BasePermission p = mSettings.mPermissions.get(name);
4011            if (p != null) {
4012                return generatePermissionInfo(p, flags);
4013            }
4014            return null;
4015        }
4016    }
4017
4018    @Override
4019    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4020            int flags) {
4021        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4022            return null;
4023        }
4024        // reader
4025        synchronized (mPackages) {
4026            if (group != null && !mPermissionGroups.containsKey(group)) {
4027                // This is thrown as NameNotFoundException
4028                return null;
4029            }
4030
4031            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4032            for (BasePermission p : mSettings.mPermissions.values()) {
4033                if (group == null) {
4034                    if (p.perm == null || p.perm.info.group == null) {
4035                        out.add(generatePermissionInfo(p, flags));
4036                    }
4037                } else {
4038                    if (p.perm != null && group.equals(p.perm.info.group)) {
4039                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4040                    }
4041                }
4042            }
4043            return new ParceledListSlice<>(out);
4044        }
4045    }
4046
4047    @Override
4048    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4049        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4050            return null;
4051        }
4052        // reader
4053        synchronized (mPackages) {
4054            return PackageParser.generatePermissionGroupInfo(
4055                    mPermissionGroups.get(name), flags);
4056        }
4057    }
4058
4059    @Override
4060    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4061        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4062            return ParceledListSlice.emptyList();
4063        }
4064        // reader
4065        synchronized (mPackages) {
4066            final int N = mPermissionGroups.size();
4067            ArrayList<PermissionGroupInfo> out
4068                    = new ArrayList<PermissionGroupInfo>(N);
4069            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4070                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4071            }
4072            return new ParceledListSlice<>(out);
4073        }
4074    }
4075
4076    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4077            int filterCallingUid, int userId) {
4078        if (!sUserManager.exists(userId)) return null;
4079        PackageSetting ps = mSettings.mPackages.get(packageName);
4080        if (ps != null) {
4081            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4082                return null;
4083            }
4084            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4085                return null;
4086            }
4087            if (ps.pkg == null) {
4088                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4089                if (pInfo != null) {
4090                    return pInfo.applicationInfo;
4091                }
4092                return null;
4093            }
4094            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4095                    ps.readUserState(userId), userId);
4096            if (ai != null) {
4097                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4098            }
4099            return ai;
4100        }
4101        return null;
4102    }
4103
4104    @Override
4105    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4106        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4107    }
4108
4109    /**
4110     * Important: The provided filterCallingUid is used exclusively to filter out applications
4111     * that can be seen based on user state. It's typically the original caller uid prior
4112     * to clearing. Because it can only be provided by trusted code, it's value can be
4113     * trusted and will be used as-is; unlike userId which will be validated by this method.
4114     */
4115    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4116            int filterCallingUid, int userId) {
4117        if (!sUserManager.exists(userId)) return null;
4118        flags = updateFlagsForApplication(flags, userId, packageName);
4119        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4120                false /* requireFullPermission */, false /* checkShell */, "get application info");
4121
4122        // writer
4123        synchronized (mPackages) {
4124            // Normalize package name to handle renamed packages and static libs
4125            packageName = resolveInternalPackageNameLPr(packageName,
4126                    PackageManager.VERSION_CODE_HIGHEST);
4127
4128            PackageParser.Package p = mPackages.get(packageName);
4129            if (DEBUG_PACKAGE_INFO) Log.v(
4130                    TAG, "getApplicationInfo " + packageName
4131                    + ": " + p);
4132            if (p != null) {
4133                PackageSetting ps = mSettings.mPackages.get(packageName);
4134                if (ps == null) return null;
4135                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4136                    return null;
4137                }
4138                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4139                    return null;
4140                }
4141                // Note: isEnabledLP() does not apply here - always return info
4142                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4143                        p, flags, ps.readUserState(userId), userId);
4144                if (ai != null) {
4145                    ai.packageName = resolveExternalPackageNameLPr(p);
4146                }
4147                return ai;
4148            }
4149            if ("android".equals(packageName)||"system".equals(packageName)) {
4150                return mAndroidApplication;
4151            }
4152            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4153                // Already generates the external package name
4154                return generateApplicationInfoFromSettingsLPw(packageName,
4155                        flags, filterCallingUid, userId);
4156            }
4157        }
4158        return null;
4159    }
4160
4161    private String normalizePackageNameLPr(String packageName) {
4162        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4163        return normalizedPackageName != null ? normalizedPackageName : packageName;
4164    }
4165
4166    @Override
4167    public void deletePreloadsFileCache() {
4168        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4169            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4170        }
4171        File dir = Environment.getDataPreloadsFileCacheDirectory();
4172        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4173        FileUtils.deleteContents(dir);
4174    }
4175
4176    @Override
4177    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4178            final int storageFlags, final IPackageDataObserver observer) {
4179        mContext.enforceCallingOrSelfPermission(
4180                android.Manifest.permission.CLEAR_APP_CACHE, null);
4181        mHandler.post(() -> {
4182            boolean success = false;
4183            try {
4184                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4185                success = true;
4186            } catch (IOException e) {
4187                Slog.w(TAG, e);
4188            }
4189            if (observer != null) {
4190                try {
4191                    observer.onRemoveCompleted(null, success);
4192                } catch (RemoteException e) {
4193                    Slog.w(TAG, e);
4194                }
4195            }
4196        });
4197    }
4198
4199    @Override
4200    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4201            final int storageFlags, final IntentSender pi) {
4202        mContext.enforceCallingOrSelfPermission(
4203                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4204        mHandler.post(() -> {
4205            boolean success = false;
4206            try {
4207                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4208                success = true;
4209            } catch (IOException e) {
4210                Slog.w(TAG, e);
4211            }
4212            if (pi != null) {
4213                try {
4214                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4215                } catch (SendIntentException e) {
4216                    Slog.w(TAG, e);
4217                }
4218            }
4219        });
4220    }
4221
4222    /**
4223     * Blocking call to clear various types of cached data across the system
4224     * until the requested bytes are available.
4225     */
4226    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4227        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4228        final File file = storage.findPathForUuid(volumeUuid);
4229        if (file.getUsableSpace() >= bytes) return;
4230
4231        if (ENABLE_FREE_CACHE_V2) {
4232            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4233                    volumeUuid);
4234            final boolean aggressive = (storageFlags
4235                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4236            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4237
4238            // 1. Pre-flight to determine if we have any chance to succeed
4239            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4240            if (internalVolume && (aggressive || SystemProperties
4241                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4242                deletePreloadsFileCache();
4243                if (file.getUsableSpace() >= bytes) return;
4244            }
4245
4246            // 3. Consider parsed APK data (aggressive only)
4247            if (internalVolume && aggressive) {
4248                FileUtils.deleteContents(mCacheDir);
4249                if (file.getUsableSpace() >= bytes) return;
4250            }
4251
4252            // 4. Consider cached app data (above quotas)
4253            try {
4254                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4255                        Installer.FLAG_FREE_CACHE_V2);
4256            } catch (InstallerException ignored) {
4257            }
4258            if (file.getUsableSpace() >= bytes) return;
4259
4260            // 5. Consider shared libraries with refcount=0 and age>min cache period
4261            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4262                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4263                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4264                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4265                return;
4266            }
4267
4268            // 6. Consider dexopt output (aggressive only)
4269            // TODO: Implement
4270
4271            // 7. Consider installed instant apps unused longer than min cache period
4272            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4273                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4274                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4275                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4276                return;
4277            }
4278
4279            // 8. Consider cached app data (below quotas)
4280            try {
4281                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4282                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4283            } catch (InstallerException ignored) {
4284            }
4285            if (file.getUsableSpace() >= bytes) return;
4286
4287            // 9. Consider DropBox entries
4288            // TODO: Implement
4289
4290            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4291            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4292                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4293                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4294                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4295                return;
4296            }
4297        } else {
4298            try {
4299                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4300            } catch (InstallerException ignored) {
4301            }
4302            if (file.getUsableSpace() >= bytes) return;
4303        }
4304
4305        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4306    }
4307
4308    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4309            throws IOException {
4310        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4311        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4312
4313        List<VersionedPackage> packagesToDelete = null;
4314        final long now = System.currentTimeMillis();
4315
4316        synchronized (mPackages) {
4317            final int[] allUsers = sUserManager.getUserIds();
4318            final int libCount = mSharedLibraries.size();
4319            for (int i = 0; i < libCount; i++) {
4320                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4321                if (versionedLib == null) {
4322                    continue;
4323                }
4324                final int versionCount = versionedLib.size();
4325                for (int j = 0; j < versionCount; j++) {
4326                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4327                    // Skip packages that are not static shared libs.
4328                    if (!libInfo.isStatic()) {
4329                        break;
4330                    }
4331                    // Important: We skip static shared libs used for some user since
4332                    // in such a case we need to keep the APK on the device. The check for
4333                    // a lib being used for any user is performed by the uninstall call.
4334                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4335                    // Resolve the package name - we use synthetic package names internally
4336                    final String internalPackageName = resolveInternalPackageNameLPr(
4337                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4338                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4339                    // Skip unused static shared libs cached less than the min period
4340                    // to prevent pruning a lib needed by a subsequently installed package.
4341                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4342                        continue;
4343                    }
4344                    if (packagesToDelete == null) {
4345                        packagesToDelete = new ArrayList<>();
4346                    }
4347                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4348                            declaringPackage.getVersionCode()));
4349                }
4350            }
4351        }
4352
4353        if (packagesToDelete != null) {
4354            final int packageCount = packagesToDelete.size();
4355            for (int i = 0; i < packageCount; i++) {
4356                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4357                // Delete the package synchronously (will fail of the lib used for any user).
4358                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4359                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4360                                == PackageManager.DELETE_SUCCEEDED) {
4361                    if (volume.getUsableSpace() >= neededSpace) {
4362                        return true;
4363                    }
4364                }
4365            }
4366        }
4367
4368        return false;
4369    }
4370
4371    /**
4372     * Update given flags based on encryption status of current user.
4373     */
4374    private int updateFlags(int flags, int userId) {
4375        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4376                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4377            // Caller expressed an explicit opinion about what encryption
4378            // aware/unaware components they want to see, so fall through and
4379            // give them what they want
4380        } else {
4381            // Caller expressed no opinion, so match based on user state
4382            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4383                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4384            } else {
4385                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4386            }
4387        }
4388        return flags;
4389    }
4390
4391    private UserManagerInternal getUserManagerInternal() {
4392        if (mUserManagerInternal == null) {
4393            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4394        }
4395        return mUserManagerInternal;
4396    }
4397
4398    private DeviceIdleController.LocalService getDeviceIdleController() {
4399        if (mDeviceIdleController == null) {
4400            mDeviceIdleController =
4401                    LocalServices.getService(DeviceIdleController.LocalService.class);
4402        }
4403        return mDeviceIdleController;
4404    }
4405
4406    /**
4407     * Update given flags when being used to request {@link PackageInfo}.
4408     */
4409    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4410        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4411        boolean triaged = true;
4412        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4413                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4414            // Caller is asking for component details, so they'd better be
4415            // asking for specific encryption matching behavior, or be triaged
4416            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4417                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4418                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4419                triaged = false;
4420            }
4421        }
4422        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4423                | PackageManager.MATCH_SYSTEM_ONLY
4424                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4425            triaged = false;
4426        }
4427        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4428            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4429                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4430                    + Debug.getCallers(5));
4431        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4432                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4433            // If the caller wants all packages and has a restricted profile associated with it,
4434            // then match all users. This is to make sure that launchers that need to access work
4435            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4436            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4437            flags |= PackageManager.MATCH_ANY_USER;
4438        }
4439        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4440            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4441                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4442        }
4443        return updateFlags(flags, userId);
4444    }
4445
4446    /**
4447     * Update given flags when being used to request {@link ApplicationInfo}.
4448     */
4449    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4450        return updateFlagsForPackage(flags, userId, cookie);
4451    }
4452
4453    /**
4454     * Update given flags when being used to request {@link ComponentInfo}.
4455     */
4456    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4457        if (cookie instanceof Intent) {
4458            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4459                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4460            }
4461        }
4462
4463        boolean triaged = true;
4464        // Caller is asking for component details, so they'd better be
4465        // asking for specific encryption matching behavior, or be triaged
4466        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4467                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4468                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4469            triaged = false;
4470        }
4471        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4472            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4473                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4474        }
4475
4476        return updateFlags(flags, userId);
4477    }
4478
4479    /**
4480     * Update given intent when being used to request {@link ResolveInfo}.
4481     */
4482    private Intent updateIntentForResolve(Intent intent) {
4483        if (intent.getSelector() != null) {
4484            intent = intent.getSelector();
4485        }
4486        if (DEBUG_PREFERRED) {
4487            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4488        }
4489        return intent;
4490    }
4491
4492    /**
4493     * Update given flags when being used to request {@link ResolveInfo}.
4494     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4495     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4496     * flag set. However, this flag is only honoured in three circumstances:
4497     * <ul>
4498     * <li>when called from a system process</li>
4499     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4500     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4501     * action and a {@code android.intent.category.BROWSABLE} category</li>
4502     * </ul>
4503     */
4504    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4505        return updateFlagsForResolve(flags, userId, intent, callingUid,
4506                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4507    }
4508    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4509            boolean wantInstantApps) {
4510        return updateFlagsForResolve(flags, userId, intent, callingUid,
4511                wantInstantApps, false /*onlyExposedExplicitly*/);
4512    }
4513    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4514            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4515        // Safe mode means we shouldn't match any third-party components
4516        if (mSafeMode) {
4517            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4518        }
4519        if (getInstantAppPackageName(callingUid) != null) {
4520            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4521            if (onlyExposedExplicitly) {
4522                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4523            }
4524            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4525            flags |= PackageManager.MATCH_INSTANT;
4526        } else {
4527            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4528            final boolean allowMatchInstant =
4529                    (wantInstantApps
4530                            && Intent.ACTION_VIEW.equals(intent.getAction())
4531                            && hasWebURI(intent))
4532                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4533            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4534                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4535            if (!allowMatchInstant) {
4536                flags &= ~PackageManager.MATCH_INSTANT;
4537            }
4538        }
4539        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4540    }
4541
4542    @Override
4543    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4544        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4545    }
4546
4547    /**
4548     * Important: The provided filterCallingUid is used exclusively to filter out activities
4549     * that can be seen based on user state. It's typically the original caller uid prior
4550     * to clearing. Because it can only be provided by trusted code, it's value can be
4551     * trusted and will be used as-is; unlike userId which will be validated by this method.
4552     */
4553    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4554            int filterCallingUid, int userId) {
4555        if (!sUserManager.exists(userId)) return null;
4556        flags = updateFlagsForComponent(flags, userId, component);
4557        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4558                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4559        synchronized (mPackages) {
4560            PackageParser.Activity a = mActivities.mActivities.get(component);
4561
4562            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4563            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4564                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4565                if (ps == null) return null;
4566                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4567                    return null;
4568                }
4569                return PackageParser.generateActivityInfo(
4570                        a, flags, ps.readUserState(userId), userId);
4571            }
4572            if (mResolveComponentName.equals(component)) {
4573                return PackageParser.generateActivityInfo(
4574                        mResolveActivity, flags, new PackageUserState(), userId);
4575            }
4576        }
4577        return null;
4578    }
4579
4580    @Override
4581    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4582            String resolvedType) {
4583        synchronized (mPackages) {
4584            if (component.equals(mResolveComponentName)) {
4585                // The resolver supports EVERYTHING!
4586                return true;
4587            }
4588            final int callingUid = Binder.getCallingUid();
4589            final int callingUserId = UserHandle.getUserId(callingUid);
4590            PackageParser.Activity a = mActivities.mActivities.get(component);
4591            if (a == null) {
4592                return false;
4593            }
4594            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4595            if (ps == null) {
4596                return false;
4597            }
4598            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4599                return false;
4600            }
4601            for (int i=0; i<a.intents.size(); i++) {
4602                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4603                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4604                    return true;
4605                }
4606            }
4607            return false;
4608        }
4609    }
4610
4611    @Override
4612    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4613        if (!sUserManager.exists(userId)) return null;
4614        final int callingUid = Binder.getCallingUid();
4615        flags = updateFlagsForComponent(flags, userId, component);
4616        enforceCrossUserPermission(callingUid, userId,
4617                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4618        synchronized (mPackages) {
4619            PackageParser.Activity a = mReceivers.mActivities.get(component);
4620            if (DEBUG_PACKAGE_INFO) Log.v(
4621                TAG, "getReceiverInfo " + component + ": " + a);
4622            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4623                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4624                if (ps == null) return null;
4625                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4626                    return null;
4627                }
4628                return PackageParser.generateActivityInfo(
4629                        a, flags, ps.readUserState(userId), userId);
4630            }
4631        }
4632        return null;
4633    }
4634
4635    @Override
4636    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4637            int flags, int userId) {
4638        if (!sUserManager.exists(userId)) return null;
4639        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4640        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4641            return null;
4642        }
4643
4644        flags = updateFlagsForPackage(flags, userId, null);
4645
4646        final boolean canSeeStaticLibraries =
4647                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4648                        == PERMISSION_GRANTED
4649                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4650                        == PERMISSION_GRANTED
4651                || canRequestPackageInstallsInternal(packageName,
4652                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4653                        false  /* throwIfPermNotDeclared*/)
4654                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4655                        == PERMISSION_GRANTED;
4656
4657        synchronized (mPackages) {
4658            List<SharedLibraryInfo> result = null;
4659
4660            final int libCount = mSharedLibraries.size();
4661            for (int i = 0; i < libCount; i++) {
4662                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4663                if (versionedLib == null) {
4664                    continue;
4665                }
4666
4667                final int versionCount = versionedLib.size();
4668                for (int j = 0; j < versionCount; j++) {
4669                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4670                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4671                        break;
4672                    }
4673                    final long identity = Binder.clearCallingIdentity();
4674                    try {
4675                        PackageInfo packageInfo = getPackageInfoVersioned(
4676                                libInfo.getDeclaringPackage(), flags
4677                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4678                        if (packageInfo == null) {
4679                            continue;
4680                        }
4681                    } finally {
4682                        Binder.restoreCallingIdentity(identity);
4683                    }
4684
4685                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4686                            libInfo.getVersion(), libInfo.getType(),
4687                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4688                            flags, userId));
4689
4690                    if (result == null) {
4691                        result = new ArrayList<>();
4692                    }
4693                    result.add(resLibInfo);
4694                }
4695            }
4696
4697            return result != null ? new ParceledListSlice<>(result) : null;
4698        }
4699    }
4700
4701    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4702            SharedLibraryInfo libInfo, int flags, int userId) {
4703        List<VersionedPackage> versionedPackages = null;
4704        final int packageCount = mSettings.mPackages.size();
4705        for (int i = 0; i < packageCount; i++) {
4706            PackageSetting ps = mSettings.mPackages.valueAt(i);
4707
4708            if (ps == null) {
4709                continue;
4710            }
4711
4712            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4713                continue;
4714            }
4715
4716            final String libName = libInfo.getName();
4717            if (libInfo.isStatic()) {
4718                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4719                if (libIdx < 0) {
4720                    continue;
4721                }
4722                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4723                    continue;
4724                }
4725                if (versionedPackages == null) {
4726                    versionedPackages = new ArrayList<>();
4727                }
4728                // If the dependent is a static shared lib, use the public package name
4729                String dependentPackageName = ps.name;
4730                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4731                    dependentPackageName = ps.pkg.manifestPackageName;
4732                }
4733                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4734            } else if (ps.pkg != null) {
4735                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4736                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4737                    if (versionedPackages == null) {
4738                        versionedPackages = new ArrayList<>();
4739                    }
4740                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4741                }
4742            }
4743        }
4744
4745        return versionedPackages;
4746    }
4747
4748    @Override
4749    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4750        if (!sUserManager.exists(userId)) return null;
4751        final int callingUid = Binder.getCallingUid();
4752        flags = updateFlagsForComponent(flags, userId, component);
4753        enforceCrossUserPermission(callingUid, userId,
4754                false /* requireFullPermission */, false /* checkShell */, "get service info");
4755        synchronized (mPackages) {
4756            PackageParser.Service s = mServices.mServices.get(component);
4757            if (DEBUG_PACKAGE_INFO) Log.v(
4758                TAG, "getServiceInfo " + component + ": " + s);
4759            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4760                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4761                if (ps == null) return null;
4762                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4763                    return null;
4764                }
4765                return PackageParser.generateServiceInfo(
4766                        s, flags, ps.readUserState(userId), userId);
4767            }
4768        }
4769        return null;
4770    }
4771
4772    @Override
4773    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4774        if (!sUserManager.exists(userId)) return null;
4775        final int callingUid = Binder.getCallingUid();
4776        flags = updateFlagsForComponent(flags, userId, component);
4777        enforceCrossUserPermission(callingUid, userId,
4778                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4779        synchronized (mPackages) {
4780            PackageParser.Provider p = mProviders.mProviders.get(component);
4781            if (DEBUG_PACKAGE_INFO) Log.v(
4782                TAG, "getProviderInfo " + component + ": " + p);
4783            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4784                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4785                if (ps == null) return null;
4786                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4787                    return null;
4788                }
4789                return PackageParser.generateProviderInfo(
4790                        p, flags, ps.readUserState(userId), userId);
4791            }
4792        }
4793        return null;
4794    }
4795
4796    @Override
4797    public String[] getSystemSharedLibraryNames() {
4798        // allow instant applications
4799        synchronized (mPackages) {
4800            Set<String> libs = null;
4801            final int libCount = mSharedLibraries.size();
4802            for (int i = 0; i < libCount; i++) {
4803                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4804                if (versionedLib == null) {
4805                    continue;
4806                }
4807                final int versionCount = versionedLib.size();
4808                for (int j = 0; j < versionCount; j++) {
4809                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4810                    if (!libEntry.info.isStatic()) {
4811                        if (libs == null) {
4812                            libs = new ArraySet<>();
4813                        }
4814                        libs.add(libEntry.info.getName());
4815                        break;
4816                    }
4817                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4818                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4819                            UserHandle.getUserId(Binder.getCallingUid()),
4820                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4821                        if (libs == null) {
4822                            libs = new ArraySet<>();
4823                        }
4824                        libs.add(libEntry.info.getName());
4825                        break;
4826                    }
4827                }
4828            }
4829
4830            if (libs != null) {
4831                String[] libsArray = new String[libs.size()];
4832                libs.toArray(libsArray);
4833                return libsArray;
4834            }
4835
4836            return null;
4837        }
4838    }
4839
4840    @Override
4841    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4842        // allow instant applications
4843        synchronized (mPackages) {
4844            return mServicesSystemSharedLibraryPackageName;
4845        }
4846    }
4847
4848    @Override
4849    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4850        // allow instant applications
4851        synchronized (mPackages) {
4852            return mSharedSystemSharedLibraryPackageName;
4853        }
4854    }
4855
4856    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4857        for (int i = userList.length - 1; i >= 0; --i) {
4858            final int userId = userList[i];
4859            // don't add instant app to the list of updates
4860            if (pkgSetting.getInstantApp(userId)) {
4861                continue;
4862            }
4863            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4864            if (changedPackages == null) {
4865                changedPackages = new SparseArray<>();
4866                mChangedPackages.put(userId, changedPackages);
4867            }
4868            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4869            if (sequenceNumbers == null) {
4870                sequenceNumbers = new HashMap<>();
4871                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4872            }
4873            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4874            if (sequenceNumber != null) {
4875                changedPackages.remove(sequenceNumber);
4876            }
4877            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4878            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4879        }
4880        mChangedPackagesSequenceNumber++;
4881    }
4882
4883    @Override
4884    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4885        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4886            return null;
4887        }
4888        synchronized (mPackages) {
4889            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4890                return null;
4891            }
4892            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4893            if (changedPackages == null) {
4894                return null;
4895            }
4896            final List<String> packageNames =
4897                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4898            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4899                final String packageName = changedPackages.get(i);
4900                if (packageName != null) {
4901                    packageNames.add(packageName);
4902                }
4903            }
4904            return packageNames.isEmpty()
4905                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4906        }
4907    }
4908
4909    @Override
4910    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4911        // allow instant applications
4912        ArrayList<FeatureInfo> res;
4913        synchronized (mAvailableFeatures) {
4914            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4915            res.addAll(mAvailableFeatures.values());
4916        }
4917        final FeatureInfo fi = new FeatureInfo();
4918        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4919                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4920        res.add(fi);
4921
4922        return new ParceledListSlice<>(res);
4923    }
4924
4925    @Override
4926    public boolean hasSystemFeature(String name, int version) {
4927        // allow instant applications
4928        synchronized (mAvailableFeatures) {
4929            final FeatureInfo feat = mAvailableFeatures.get(name);
4930            if (feat == null) {
4931                return false;
4932            } else {
4933                return feat.version >= version;
4934            }
4935        }
4936    }
4937
4938    @Override
4939    public int checkPermission(String permName, String pkgName, int userId) {
4940        if (!sUserManager.exists(userId)) {
4941            return PackageManager.PERMISSION_DENIED;
4942        }
4943        final int callingUid = Binder.getCallingUid();
4944
4945        synchronized (mPackages) {
4946            final PackageParser.Package p = mPackages.get(pkgName);
4947            if (p != null && p.mExtras != null) {
4948                final PackageSetting ps = (PackageSetting) p.mExtras;
4949                if (filterAppAccessLPr(ps, callingUid, userId)) {
4950                    return PackageManager.PERMISSION_DENIED;
4951                }
4952                final boolean instantApp = ps.getInstantApp(userId);
4953                final PermissionsState permissionsState = ps.getPermissionsState();
4954                if (permissionsState.hasPermission(permName, userId)) {
4955                    if (instantApp) {
4956                        BasePermission bp = mSettings.mPermissions.get(permName);
4957                        if (bp != null && bp.isInstant()) {
4958                            return PackageManager.PERMISSION_GRANTED;
4959                        }
4960                    } else {
4961                        return PackageManager.PERMISSION_GRANTED;
4962                    }
4963                }
4964                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4965                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4966                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4967                    return PackageManager.PERMISSION_GRANTED;
4968                }
4969            }
4970        }
4971
4972        return PackageManager.PERMISSION_DENIED;
4973    }
4974
4975    @Override
4976    public int checkUidPermission(String permName, int uid) {
4977        final int callingUid = Binder.getCallingUid();
4978        final int callingUserId = UserHandle.getUserId(callingUid);
4979        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
4980        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
4981        final int userId = UserHandle.getUserId(uid);
4982        if (!sUserManager.exists(userId)) {
4983            return PackageManager.PERMISSION_DENIED;
4984        }
4985
4986        synchronized (mPackages) {
4987            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4988            if (obj != null) {
4989                if (obj instanceof SharedUserSetting) {
4990                    if (isCallerInstantApp) {
4991                        return PackageManager.PERMISSION_DENIED;
4992                    }
4993                } else if (obj instanceof PackageSetting) {
4994                    final PackageSetting ps = (PackageSetting) obj;
4995                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
4996                        return PackageManager.PERMISSION_DENIED;
4997                    }
4998                }
4999                final SettingBase settingBase = (SettingBase) obj;
5000                final PermissionsState permissionsState = settingBase.getPermissionsState();
5001                if (permissionsState.hasPermission(permName, userId)) {
5002                    if (isUidInstantApp) {
5003                        BasePermission bp = mSettings.mPermissions.get(permName);
5004                        if (bp != null && bp.isInstant()) {
5005                            return PackageManager.PERMISSION_GRANTED;
5006                        }
5007                    } else {
5008                        return PackageManager.PERMISSION_GRANTED;
5009                    }
5010                }
5011                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5012                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5013                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5014                    return PackageManager.PERMISSION_GRANTED;
5015                }
5016            } else {
5017                ArraySet<String> perms = mSystemPermissions.get(uid);
5018                if (perms != null) {
5019                    if (perms.contains(permName)) {
5020                        return PackageManager.PERMISSION_GRANTED;
5021                    }
5022                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5023                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5024                        return PackageManager.PERMISSION_GRANTED;
5025                    }
5026                }
5027            }
5028        }
5029
5030        return PackageManager.PERMISSION_DENIED;
5031    }
5032
5033    @Override
5034    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5035        if (UserHandle.getCallingUserId() != userId) {
5036            mContext.enforceCallingPermission(
5037                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5038                    "isPermissionRevokedByPolicy for user " + userId);
5039        }
5040
5041        if (checkPermission(permission, packageName, userId)
5042                == PackageManager.PERMISSION_GRANTED) {
5043            return false;
5044        }
5045
5046        final int callingUid = Binder.getCallingUid();
5047        if (getInstantAppPackageName(callingUid) != null) {
5048            if (!isCallerSameApp(packageName, callingUid)) {
5049                return false;
5050            }
5051        } else {
5052            if (isInstantApp(packageName, userId)) {
5053                return false;
5054            }
5055        }
5056
5057        final long identity = Binder.clearCallingIdentity();
5058        try {
5059            final int flags = getPermissionFlags(permission, packageName, userId);
5060            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5061        } finally {
5062            Binder.restoreCallingIdentity(identity);
5063        }
5064    }
5065
5066    @Override
5067    public String getPermissionControllerPackageName() {
5068        synchronized (mPackages) {
5069            return mRequiredInstallerPackage;
5070        }
5071    }
5072
5073    /**
5074     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5075     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5076     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5077     * @param message the message to log on security exception
5078     */
5079    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5080            boolean checkShell, String message) {
5081        if (userId < 0) {
5082            throw new IllegalArgumentException("Invalid userId " + userId);
5083        }
5084        if (checkShell) {
5085            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5086        }
5087        if (userId == UserHandle.getUserId(callingUid)) return;
5088        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5089            if (requireFullPermission) {
5090                mContext.enforceCallingOrSelfPermission(
5091                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5092            } else {
5093                try {
5094                    mContext.enforceCallingOrSelfPermission(
5095                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5096                } catch (SecurityException se) {
5097                    mContext.enforceCallingOrSelfPermission(
5098                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5099                }
5100            }
5101        }
5102    }
5103
5104    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5105        if (callingUid == Process.SHELL_UID) {
5106            if (userHandle >= 0
5107                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5108                throw new SecurityException("Shell does not have permission to access user "
5109                        + userHandle);
5110            } else if (userHandle < 0) {
5111                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5112                        + Debug.getCallers(3));
5113            }
5114        }
5115    }
5116
5117    private BasePermission findPermissionTreeLP(String permName) {
5118        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5119            if (permName.startsWith(bp.name) &&
5120                    permName.length() > bp.name.length() &&
5121                    permName.charAt(bp.name.length()) == '.') {
5122                return bp;
5123            }
5124        }
5125        return null;
5126    }
5127
5128    private BasePermission checkPermissionTreeLP(String permName) {
5129        if (permName != null) {
5130            BasePermission bp = findPermissionTreeLP(permName);
5131            if (bp != null) {
5132                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5133                    return bp;
5134                }
5135                throw new SecurityException("Calling uid "
5136                        + Binder.getCallingUid()
5137                        + " is not allowed to add to permission tree "
5138                        + bp.name + " owned by uid " + bp.uid);
5139            }
5140        }
5141        throw new SecurityException("No permission tree found for " + permName);
5142    }
5143
5144    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5145        if (s1 == null) {
5146            return s2 == null;
5147        }
5148        if (s2 == null) {
5149            return false;
5150        }
5151        if (s1.getClass() != s2.getClass()) {
5152            return false;
5153        }
5154        return s1.equals(s2);
5155    }
5156
5157    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5158        if (pi1.icon != pi2.icon) return false;
5159        if (pi1.logo != pi2.logo) return false;
5160        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5161        if (!compareStrings(pi1.name, pi2.name)) return false;
5162        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5163        // We'll take care of setting this one.
5164        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5165        // These are not currently stored in settings.
5166        //if (!compareStrings(pi1.group, pi2.group)) return false;
5167        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5168        //if (pi1.labelRes != pi2.labelRes) return false;
5169        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5170        return true;
5171    }
5172
5173    int permissionInfoFootprint(PermissionInfo info) {
5174        int size = info.name.length();
5175        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5176        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5177        return size;
5178    }
5179
5180    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5181        int size = 0;
5182        for (BasePermission perm : mSettings.mPermissions.values()) {
5183            if (perm.uid == tree.uid) {
5184                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5185            }
5186        }
5187        return size;
5188    }
5189
5190    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5191        // We calculate the max size of permissions defined by this uid and throw
5192        // if that plus the size of 'info' would exceed our stated maximum.
5193        if (tree.uid != Process.SYSTEM_UID) {
5194            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5195            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5196                throw new SecurityException("Permission tree size cap exceeded");
5197            }
5198        }
5199    }
5200
5201    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5202        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5203            throw new SecurityException("Instant apps can't add permissions");
5204        }
5205        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5206            throw new SecurityException("Label must be specified in permission");
5207        }
5208        BasePermission tree = checkPermissionTreeLP(info.name);
5209        BasePermission bp = mSettings.mPermissions.get(info.name);
5210        boolean added = bp == null;
5211        boolean changed = true;
5212        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5213        if (added) {
5214            enforcePermissionCapLocked(info, tree);
5215            bp = new BasePermission(info.name, tree.sourcePackage,
5216                    BasePermission.TYPE_DYNAMIC);
5217        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5218            throw new SecurityException(
5219                    "Not allowed to modify non-dynamic permission "
5220                    + info.name);
5221        } else {
5222            if (bp.protectionLevel == fixedLevel
5223                    && bp.perm.owner.equals(tree.perm.owner)
5224                    && bp.uid == tree.uid
5225                    && comparePermissionInfos(bp.perm.info, info)) {
5226                changed = false;
5227            }
5228        }
5229        bp.protectionLevel = fixedLevel;
5230        info = new PermissionInfo(info);
5231        info.protectionLevel = fixedLevel;
5232        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5233        bp.perm.info.packageName = tree.perm.info.packageName;
5234        bp.uid = tree.uid;
5235        if (added) {
5236            mSettings.mPermissions.put(info.name, bp);
5237        }
5238        if (changed) {
5239            if (!async) {
5240                mSettings.writeLPr();
5241            } else {
5242                scheduleWriteSettingsLocked();
5243            }
5244        }
5245        return added;
5246    }
5247
5248    @Override
5249    public boolean addPermission(PermissionInfo info) {
5250        synchronized (mPackages) {
5251            return addPermissionLocked(info, false);
5252        }
5253    }
5254
5255    @Override
5256    public boolean addPermissionAsync(PermissionInfo info) {
5257        synchronized (mPackages) {
5258            return addPermissionLocked(info, true);
5259        }
5260    }
5261
5262    @Override
5263    public void removePermission(String name) {
5264        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5265            throw new SecurityException("Instant applications don't have access to this method");
5266        }
5267        synchronized (mPackages) {
5268            checkPermissionTreeLP(name);
5269            BasePermission bp = mSettings.mPermissions.get(name);
5270            if (bp != null) {
5271                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5272                    throw new SecurityException(
5273                            "Not allowed to modify non-dynamic permission "
5274                            + name);
5275                }
5276                mSettings.mPermissions.remove(name);
5277                mSettings.writeLPr();
5278            }
5279        }
5280    }
5281
5282    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5283            PackageParser.Package pkg, BasePermission bp) {
5284        int index = pkg.requestedPermissions.indexOf(bp.name);
5285        if (index == -1) {
5286            throw new SecurityException("Package " + pkg.packageName
5287                    + " has not requested permission " + bp.name);
5288        }
5289        if (!bp.isRuntime() && !bp.isDevelopment()) {
5290            throw new SecurityException("Permission " + bp.name
5291                    + " is not a changeable permission type");
5292        }
5293    }
5294
5295    @Override
5296    public void grantRuntimePermission(String packageName, String name, final int userId) {
5297        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5298    }
5299
5300    private void grantRuntimePermission(String packageName, String name, final int userId,
5301            boolean overridePolicy) {
5302        if (!sUserManager.exists(userId)) {
5303            Log.e(TAG, "No such user:" + userId);
5304            return;
5305        }
5306        final int callingUid = Binder.getCallingUid();
5307
5308        mContext.enforceCallingOrSelfPermission(
5309                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5310                "grantRuntimePermission");
5311
5312        enforceCrossUserPermission(callingUid, userId,
5313                true /* requireFullPermission */, true /* checkShell */,
5314                "grantRuntimePermission");
5315
5316        final int uid;
5317        final PackageSetting ps;
5318
5319        synchronized (mPackages) {
5320            final PackageParser.Package pkg = mPackages.get(packageName);
5321            if (pkg == null) {
5322                throw new IllegalArgumentException("Unknown package: " + packageName);
5323            }
5324            final BasePermission bp = mSettings.mPermissions.get(name);
5325            if (bp == null) {
5326                throw new IllegalArgumentException("Unknown permission: " + name);
5327            }
5328            ps = (PackageSetting) pkg.mExtras;
5329            if (ps == null
5330                    || filterAppAccessLPr(ps, callingUid, userId)) {
5331                throw new IllegalArgumentException("Unknown package: " + packageName);
5332            }
5333
5334            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5335
5336            // If a permission review is required for legacy apps we represent
5337            // their permissions as always granted runtime ones since we need
5338            // to keep the review required permission flag per user while an
5339            // install permission's state is shared across all users.
5340            if (mPermissionReviewRequired
5341                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5342                    && bp.isRuntime()) {
5343                return;
5344            }
5345
5346            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5347
5348            final PermissionsState permissionsState = ps.getPermissionsState();
5349
5350            final int flags = permissionsState.getPermissionFlags(name, userId);
5351            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5352                throw new SecurityException("Cannot grant system fixed permission "
5353                        + name + " for package " + packageName);
5354            }
5355            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5356                throw new SecurityException("Cannot grant policy fixed permission "
5357                        + name + " for package " + packageName);
5358            }
5359
5360            if (bp.isDevelopment()) {
5361                // Development permissions must be handled specially, since they are not
5362                // normal runtime permissions.  For now they apply to all users.
5363                if (permissionsState.grantInstallPermission(bp) !=
5364                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5365                    scheduleWriteSettingsLocked();
5366                }
5367                return;
5368            }
5369
5370            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5371                throw new SecurityException("Cannot grant non-ephemeral permission"
5372                        + name + " for package " + packageName);
5373            }
5374
5375            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5376                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5377                return;
5378            }
5379
5380            final int result = permissionsState.grantRuntimePermission(bp, userId);
5381            switch (result) {
5382                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5383                    return;
5384                }
5385
5386                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5387                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5388                    mHandler.post(new Runnable() {
5389                        @Override
5390                        public void run() {
5391                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5392                        }
5393                    });
5394                }
5395                break;
5396            }
5397
5398            if (bp.isRuntime()) {
5399                logPermissionGranted(mContext, name, packageName);
5400            }
5401
5402            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5403
5404            // Not critical if that is lost - app has to request again.
5405            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5406        }
5407
5408        // Only need to do this if user is initialized. Otherwise it's a new user
5409        // and there are no processes running as the user yet and there's no need
5410        // to make an expensive call to remount processes for the changed permissions.
5411        if (READ_EXTERNAL_STORAGE.equals(name)
5412                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5413            final long token = Binder.clearCallingIdentity();
5414            try {
5415                if (sUserManager.isInitialized(userId)) {
5416                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5417                            StorageManagerInternal.class);
5418                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5419                }
5420            } finally {
5421                Binder.restoreCallingIdentity(token);
5422            }
5423        }
5424    }
5425
5426    @Override
5427    public void revokeRuntimePermission(String packageName, String name, int userId) {
5428        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5429    }
5430
5431    private void revokeRuntimePermission(String packageName, String name, int userId,
5432            boolean overridePolicy) {
5433        if (!sUserManager.exists(userId)) {
5434            Log.e(TAG, "No such user:" + userId);
5435            return;
5436        }
5437
5438        mContext.enforceCallingOrSelfPermission(
5439                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5440                "revokeRuntimePermission");
5441
5442        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5443                true /* requireFullPermission */, true /* checkShell */,
5444                "revokeRuntimePermission");
5445
5446        final int appId;
5447
5448        synchronized (mPackages) {
5449            final PackageParser.Package pkg = mPackages.get(packageName);
5450            if (pkg == null) {
5451                throw new IllegalArgumentException("Unknown package: " + packageName);
5452            }
5453            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5454            if (ps == null
5455                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5456                throw new IllegalArgumentException("Unknown package: " + packageName);
5457            }
5458            final BasePermission bp = mSettings.mPermissions.get(name);
5459            if (bp == null) {
5460                throw new IllegalArgumentException("Unknown permission: " + name);
5461            }
5462
5463            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5464
5465            // If a permission review is required for legacy apps we represent
5466            // their permissions as always granted runtime ones since we need
5467            // to keep the review required permission flag per user while an
5468            // install permission's state is shared across all users.
5469            if (mPermissionReviewRequired
5470                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5471                    && bp.isRuntime()) {
5472                return;
5473            }
5474
5475            final PermissionsState permissionsState = ps.getPermissionsState();
5476
5477            final int flags = permissionsState.getPermissionFlags(name, userId);
5478            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5479                throw new SecurityException("Cannot revoke system fixed permission "
5480                        + name + " for package " + packageName);
5481            }
5482            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5483                throw new SecurityException("Cannot revoke policy fixed permission "
5484                        + name + " for package " + packageName);
5485            }
5486
5487            if (bp.isDevelopment()) {
5488                // Development permissions must be handled specially, since they are not
5489                // normal runtime permissions.  For now they apply to all users.
5490                if (permissionsState.revokeInstallPermission(bp) !=
5491                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5492                    scheduleWriteSettingsLocked();
5493                }
5494                return;
5495            }
5496
5497            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5498                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5499                return;
5500            }
5501
5502            if (bp.isRuntime()) {
5503                logPermissionRevoked(mContext, name, packageName);
5504            }
5505
5506            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5507
5508            // Critical, after this call app should never have the permission.
5509            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5510
5511            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5512        }
5513
5514        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5515    }
5516
5517    /**
5518     * Get the first event id for the permission.
5519     *
5520     * <p>There are four events for each permission: <ul>
5521     *     <li>Request permission: first id + 0</li>
5522     *     <li>Grant permission: first id + 1</li>
5523     *     <li>Request for permission denied: first id + 2</li>
5524     *     <li>Revoke permission: first id + 3</li>
5525     * </ul></p>
5526     *
5527     * @param name name of the permission
5528     *
5529     * @return The first event id for the permission
5530     */
5531    private static int getBaseEventId(@NonNull String name) {
5532        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5533
5534        if (eventIdIndex == -1) {
5535            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5536                    || "user".equals(Build.TYPE)) {
5537                Log.i(TAG, "Unknown permission " + name);
5538
5539                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5540            } else {
5541                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5542                //
5543                // Also update
5544                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5545                // - metrics_constants.proto
5546                throw new IllegalStateException("Unknown permission " + name);
5547            }
5548        }
5549
5550        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5551    }
5552
5553    /**
5554     * Log that a permission was revoked.
5555     *
5556     * @param context Context of the caller
5557     * @param name name of the permission
5558     * @param packageName package permission if for
5559     */
5560    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5561            @NonNull String packageName) {
5562        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5563    }
5564
5565    /**
5566     * Log that a permission request was granted.
5567     *
5568     * @param context Context of the caller
5569     * @param name name of the permission
5570     * @param packageName package permission if for
5571     */
5572    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5573            @NonNull String packageName) {
5574        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5575    }
5576
5577    @Override
5578    public void resetRuntimePermissions() {
5579        mContext.enforceCallingOrSelfPermission(
5580                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5581                "revokeRuntimePermission");
5582
5583        int callingUid = Binder.getCallingUid();
5584        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5585            mContext.enforceCallingOrSelfPermission(
5586                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5587                    "resetRuntimePermissions");
5588        }
5589
5590        synchronized (mPackages) {
5591            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5592            for (int userId : UserManagerService.getInstance().getUserIds()) {
5593                final int packageCount = mPackages.size();
5594                for (int i = 0; i < packageCount; i++) {
5595                    PackageParser.Package pkg = mPackages.valueAt(i);
5596                    if (!(pkg.mExtras instanceof PackageSetting)) {
5597                        continue;
5598                    }
5599                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5600                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5601                }
5602            }
5603        }
5604    }
5605
5606    @Override
5607    public int getPermissionFlags(String name, String packageName, int userId) {
5608        if (!sUserManager.exists(userId)) {
5609            return 0;
5610        }
5611
5612        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5613
5614        final int callingUid = Binder.getCallingUid();
5615        enforceCrossUserPermission(callingUid, userId,
5616                true /* requireFullPermission */, false /* checkShell */,
5617                "getPermissionFlags");
5618
5619        synchronized (mPackages) {
5620            final PackageParser.Package pkg = mPackages.get(packageName);
5621            if (pkg == null) {
5622                return 0;
5623            }
5624            final BasePermission bp = mSettings.mPermissions.get(name);
5625            if (bp == null) {
5626                return 0;
5627            }
5628            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5629            if (ps == null
5630                    || filterAppAccessLPr(ps, callingUid, userId)) {
5631                return 0;
5632            }
5633            PermissionsState permissionsState = ps.getPermissionsState();
5634            return permissionsState.getPermissionFlags(name, userId);
5635        }
5636    }
5637
5638    @Override
5639    public void updatePermissionFlags(String name, String packageName, int flagMask,
5640            int flagValues, int userId) {
5641        if (!sUserManager.exists(userId)) {
5642            return;
5643        }
5644
5645        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5646
5647        final int callingUid = Binder.getCallingUid();
5648        enforceCrossUserPermission(callingUid, userId,
5649                true /* requireFullPermission */, true /* checkShell */,
5650                "updatePermissionFlags");
5651
5652        // Only the system can change these flags and nothing else.
5653        if (getCallingUid() != Process.SYSTEM_UID) {
5654            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5655            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5656            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5657            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5658            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5659        }
5660
5661        synchronized (mPackages) {
5662            final PackageParser.Package pkg = mPackages.get(packageName);
5663            if (pkg == null) {
5664                throw new IllegalArgumentException("Unknown package: " + packageName);
5665            }
5666            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5667            if (ps == null
5668                    || filterAppAccessLPr(ps, callingUid, userId)) {
5669                throw new IllegalArgumentException("Unknown package: " + packageName);
5670            }
5671
5672            final BasePermission bp = mSettings.mPermissions.get(name);
5673            if (bp == null) {
5674                throw new IllegalArgumentException("Unknown permission: " + name);
5675            }
5676
5677            PermissionsState permissionsState = ps.getPermissionsState();
5678
5679            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5680
5681            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5682                // Install and runtime permissions are stored in different places,
5683                // so figure out what permission changed and persist the change.
5684                if (permissionsState.getInstallPermissionState(name) != null) {
5685                    scheduleWriteSettingsLocked();
5686                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5687                        || hadState) {
5688                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5689                }
5690            }
5691        }
5692    }
5693
5694    /**
5695     * Update the permission flags for all packages and runtime permissions of a user in order
5696     * to allow device or profile owner to remove POLICY_FIXED.
5697     */
5698    @Override
5699    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5700        if (!sUserManager.exists(userId)) {
5701            return;
5702        }
5703
5704        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5705
5706        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5707                true /* requireFullPermission */, true /* checkShell */,
5708                "updatePermissionFlagsForAllApps");
5709
5710        // Only the system can change system fixed flags.
5711        if (getCallingUid() != Process.SYSTEM_UID) {
5712            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5713            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5714        }
5715
5716        synchronized (mPackages) {
5717            boolean changed = false;
5718            final int packageCount = mPackages.size();
5719            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5720                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5721                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5722                if (ps == null) {
5723                    continue;
5724                }
5725                PermissionsState permissionsState = ps.getPermissionsState();
5726                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5727                        userId, flagMask, flagValues);
5728            }
5729            if (changed) {
5730                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5731            }
5732        }
5733    }
5734
5735    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5736        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5737                != PackageManager.PERMISSION_GRANTED
5738            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5739                != PackageManager.PERMISSION_GRANTED) {
5740            throw new SecurityException(message + " requires "
5741                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5742                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5743        }
5744    }
5745
5746    @Override
5747    public boolean shouldShowRequestPermissionRationale(String permissionName,
5748            String packageName, int userId) {
5749        if (UserHandle.getCallingUserId() != userId) {
5750            mContext.enforceCallingPermission(
5751                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5752                    "canShowRequestPermissionRationale for user " + userId);
5753        }
5754
5755        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5756        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5757            return false;
5758        }
5759
5760        if (checkPermission(permissionName, packageName, userId)
5761                == PackageManager.PERMISSION_GRANTED) {
5762            return false;
5763        }
5764
5765        final int flags;
5766
5767        final long identity = Binder.clearCallingIdentity();
5768        try {
5769            flags = getPermissionFlags(permissionName,
5770                    packageName, userId);
5771        } finally {
5772            Binder.restoreCallingIdentity(identity);
5773        }
5774
5775        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5776                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5777                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5778
5779        if ((flags & fixedFlags) != 0) {
5780            return false;
5781        }
5782
5783        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5784    }
5785
5786    @Override
5787    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5788        mContext.enforceCallingOrSelfPermission(
5789                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5790                "addOnPermissionsChangeListener");
5791
5792        synchronized (mPackages) {
5793            mOnPermissionChangeListeners.addListenerLocked(listener);
5794        }
5795    }
5796
5797    @Override
5798    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5799        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5800            throw new SecurityException("Instant applications don't have access to this method");
5801        }
5802        synchronized (mPackages) {
5803            mOnPermissionChangeListeners.removeListenerLocked(listener);
5804        }
5805    }
5806
5807    @Override
5808    public boolean isProtectedBroadcast(String actionName) {
5809        // allow instant applications
5810        synchronized (mProtectedBroadcasts) {
5811            if (mProtectedBroadcasts.contains(actionName)) {
5812                return true;
5813            } else if (actionName != null) {
5814                // TODO: remove these terrible hacks
5815                if (actionName.startsWith("android.net.netmon.lingerExpired")
5816                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5817                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5818                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5819                    return true;
5820                }
5821            }
5822        }
5823        return false;
5824    }
5825
5826    @Override
5827    public int checkSignatures(String pkg1, String pkg2) {
5828        synchronized (mPackages) {
5829            final PackageParser.Package p1 = mPackages.get(pkg1);
5830            final PackageParser.Package p2 = mPackages.get(pkg2);
5831            if (p1 == null || p1.mExtras == null
5832                    || p2 == null || p2.mExtras == null) {
5833                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5834            }
5835            final int callingUid = Binder.getCallingUid();
5836            final int callingUserId = UserHandle.getUserId(callingUid);
5837            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5838            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5839            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5840                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5841                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5842            }
5843            return compareSignatures(p1.mSignatures, p2.mSignatures);
5844        }
5845    }
5846
5847    @Override
5848    public int checkUidSignatures(int uid1, int uid2) {
5849        final int callingUid = Binder.getCallingUid();
5850        final int callingUserId = UserHandle.getUserId(callingUid);
5851        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5852        // Map to base uids.
5853        uid1 = UserHandle.getAppId(uid1);
5854        uid2 = UserHandle.getAppId(uid2);
5855        // reader
5856        synchronized (mPackages) {
5857            Signature[] s1;
5858            Signature[] s2;
5859            Object obj = mSettings.getUserIdLPr(uid1);
5860            if (obj != null) {
5861                if (obj instanceof SharedUserSetting) {
5862                    if (isCallerInstantApp) {
5863                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5864                    }
5865                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5866                } else if (obj instanceof PackageSetting) {
5867                    final PackageSetting ps = (PackageSetting) obj;
5868                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5869                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5870                    }
5871                    s1 = ps.signatures.mSignatures;
5872                } else {
5873                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5874                }
5875            } else {
5876                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5877            }
5878            obj = mSettings.getUserIdLPr(uid2);
5879            if (obj != null) {
5880                if (obj instanceof SharedUserSetting) {
5881                    if (isCallerInstantApp) {
5882                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5883                    }
5884                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5885                } else if (obj instanceof PackageSetting) {
5886                    final PackageSetting ps = (PackageSetting) obj;
5887                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5888                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5889                    }
5890                    s2 = ps.signatures.mSignatures;
5891                } else {
5892                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5893                }
5894            } else {
5895                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5896            }
5897            return compareSignatures(s1, s2);
5898        }
5899    }
5900
5901    /**
5902     * This method should typically only be used when granting or revoking
5903     * permissions, since the app may immediately restart after this call.
5904     * <p>
5905     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5906     * guard your work against the app being relaunched.
5907     */
5908    private void killUid(int appId, int userId, String reason) {
5909        final long identity = Binder.clearCallingIdentity();
5910        try {
5911            IActivityManager am = ActivityManager.getService();
5912            if (am != null) {
5913                try {
5914                    am.killUid(appId, userId, reason);
5915                } catch (RemoteException e) {
5916                    /* ignore - same process */
5917                }
5918            }
5919        } finally {
5920            Binder.restoreCallingIdentity(identity);
5921        }
5922    }
5923
5924    /**
5925     * Compares two sets of signatures. Returns:
5926     * <br />
5927     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5928     * <br />
5929     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5930     * <br />
5931     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5932     * <br />
5933     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5934     * <br />
5935     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5936     */
5937    static int compareSignatures(Signature[] s1, Signature[] s2) {
5938        if (s1 == null) {
5939            return s2 == null
5940                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5941                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5942        }
5943
5944        if (s2 == null) {
5945            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5946        }
5947
5948        if (s1.length != s2.length) {
5949            return PackageManager.SIGNATURE_NO_MATCH;
5950        }
5951
5952        // Since both signature sets are of size 1, we can compare without HashSets.
5953        if (s1.length == 1) {
5954            return s1[0].equals(s2[0]) ?
5955                    PackageManager.SIGNATURE_MATCH :
5956                    PackageManager.SIGNATURE_NO_MATCH;
5957        }
5958
5959        ArraySet<Signature> set1 = new ArraySet<Signature>();
5960        for (Signature sig : s1) {
5961            set1.add(sig);
5962        }
5963        ArraySet<Signature> set2 = new ArraySet<Signature>();
5964        for (Signature sig : s2) {
5965            set2.add(sig);
5966        }
5967        // Make sure s2 contains all signatures in s1.
5968        if (set1.equals(set2)) {
5969            return PackageManager.SIGNATURE_MATCH;
5970        }
5971        return PackageManager.SIGNATURE_NO_MATCH;
5972    }
5973
5974    /**
5975     * If the database version for this type of package (internal storage or
5976     * external storage) is less than the version where package signatures
5977     * were updated, return true.
5978     */
5979    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5980        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5981        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5982    }
5983
5984    /**
5985     * Used for backward compatibility to make sure any packages with
5986     * certificate chains get upgraded to the new style. {@code existingSigs}
5987     * will be in the old format (since they were stored on disk from before the
5988     * system upgrade) and {@code scannedSigs} will be in the newer format.
5989     */
5990    private int compareSignaturesCompat(PackageSignatures existingSigs,
5991            PackageParser.Package scannedPkg) {
5992        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5993            return PackageManager.SIGNATURE_NO_MATCH;
5994        }
5995
5996        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5997        for (Signature sig : existingSigs.mSignatures) {
5998            existingSet.add(sig);
5999        }
6000        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6001        for (Signature sig : scannedPkg.mSignatures) {
6002            try {
6003                Signature[] chainSignatures = sig.getChainSignatures();
6004                for (Signature chainSig : chainSignatures) {
6005                    scannedCompatSet.add(chainSig);
6006                }
6007            } catch (CertificateEncodingException e) {
6008                scannedCompatSet.add(sig);
6009            }
6010        }
6011        /*
6012         * Make sure the expanded scanned set contains all signatures in the
6013         * existing one.
6014         */
6015        if (scannedCompatSet.equals(existingSet)) {
6016            // Migrate the old signatures to the new scheme.
6017            existingSigs.assignSignatures(scannedPkg.mSignatures);
6018            // The new KeySets will be re-added later in the scanning process.
6019            synchronized (mPackages) {
6020                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6021            }
6022            return PackageManager.SIGNATURE_MATCH;
6023        }
6024        return PackageManager.SIGNATURE_NO_MATCH;
6025    }
6026
6027    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6028        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6029        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6030    }
6031
6032    private int compareSignaturesRecover(PackageSignatures existingSigs,
6033            PackageParser.Package scannedPkg) {
6034        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6035            return PackageManager.SIGNATURE_NO_MATCH;
6036        }
6037
6038        String msg = null;
6039        try {
6040            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6041                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6042                        + scannedPkg.packageName);
6043                return PackageManager.SIGNATURE_MATCH;
6044            }
6045        } catch (CertificateException e) {
6046            msg = e.getMessage();
6047        }
6048
6049        logCriticalInfo(Log.INFO,
6050                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6051        return PackageManager.SIGNATURE_NO_MATCH;
6052    }
6053
6054    @Override
6055    public List<String> getAllPackages() {
6056        final int callingUid = Binder.getCallingUid();
6057        final int callingUserId = UserHandle.getUserId(callingUid);
6058        synchronized (mPackages) {
6059            if (canViewInstantApps(callingUid, callingUserId)) {
6060                return new ArrayList<String>(mPackages.keySet());
6061            }
6062            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6063            final List<String> result = new ArrayList<>();
6064            if (instantAppPkgName != null) {
6065                // caller is an instant application; filter unexposed applications
6066                for (PackageParser.Package pkg : mPackages.values()) {
6067                    if (!pkg.visibleToInstantApps) {
6068                        continue;
6069                    }
6070                    result.add(pkg.packageName);
6071                }
6072            } else {
6073                // caller is a normal application; filter instant applications
6074                for (PackageParser.Package pkg : mPackages.values()) {
6075                    final PackageSetting ps =
6076                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6077                    if (ps != null
6078                            && ps.getInstantApp(callingUserId)
6079                            && !mInstantAppRegistry.isInstantAccessGranted(
6080                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6081                        continue;
6082                    }
6083                    result.add(pkg.packageName);
6084                }
6085            }
6086            return result;
6087        }
6088    }
6089
6090    @Override
6091    public String[] getPackagesForUid(int uid) {
6092        final int callingUid = Binder.getCallingUid();
6093        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6094        final int userId = UserHandle.getUserId(uid);
6095        uid = UserHandle.getAppId(uid);
6096        // reader
6097        synchronized (mPackages) {
6098            Object obj = mSettings.getUserIdLPr(uid);
6099            if (obj instanceof SharedUserSetting) {
6100                if (isCallerInstantApp) {
6101                    return null;
6102                }
6103                final SharedUserSetting sus = (SharedUserSetting) obj;
6104                final int N = sus.packages.size();
6105                String[] res = new String[N];
6106                final Iterator<PackageSetting> it = sus.packages.iterator();
6107                int i = 0;
6108                while (it.hasNext()) {
6109                    PackageSetting ps = it.next();
6110                    if (ps.getInstalled(userId)) {
6111                        res[i++] = ps.name;
6112                    } else {
6113                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6114                    }
6115                }
6116                return res;
6117            } else if (obj instanceof PackageSetting) {
6118                final PackageSetting ps = (PackageSetting) obj;
6119                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6120                    return new String[]{ps.name};
6121                }
6122            }
6123        }
6124        return null;
6125    }
6126
6127    @Override
6128    public String getNameForUid(int uid) {
6129        final int callingUid = Binder.getCallingUid();
6130        if (getInstantAppPackageName(callingUid) != null) {
6131            return null;
6132        }
6133        synchronized (mPackages) {
6134            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6135            if (obj instanceof SharedUserSetting) {
6136                final SharedUserSetting sus = (SharedUserSetting) obj;
6137                return sus.name + ":" + sus.userId;
6138            } else if (obj instanceof PackageSetting) {
6139                final PackageSetting ps = (PackageSetting) obj;
6140                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6141                    return null;
6142                }
6143                return ps.name;
6144            }
6145        }
6146        return null;
6147    }
6148
6149    @Override
6150    public int getUidForSharedUser(String sharedUserName) {
6151        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6152            return -1;
6153        }
6154        if (sharedUserName == null) {
6155            return -1;
6156        }
6157        // reader
6158        synchronized (mPackages) {
6159            SharedUserSetting suid;
6160            try {
6161                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6162                if (suid != null) {
6163                    return suid.userId;
6164                }
6165            } catch (PackageManagerException ignore) {
6166                // can't happen, but, still need to catch it
6167            }
6168            return -1;
6169        }
6170    }
6171
6172    @Override
6173    public int getFlagsForUid(int uid) {
6174        final int callingUid = Binder.getCallingUid();
6175        if (getInstantAppPackageName(callingUid) != null) {
6176            return 0;
6177        }
6178        synchronized (mPackages) {
6179            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6180            if (obj instanceof SharedUserSetting) {
6181                final SharedUserSetting sus = (SharedUserSetting) obj;
6182                return sus.pkgFlags;
6183            } else if (obj instanceof PackageSetting) {
6184                final PackageSetting ps = (PackageSetting) obj;
6185                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6186                    return 0;
6187                }
6188                return ps.pkgFlags;
6189            }
6190        }
6191        return 0;
6192    }
6193
6194    @Override
6195    public int getPrivateFlagsForUid(int uid) {
6196        final int callingUid = Binder.getCallingUid();
6197        if (getInstantAppPackageName(callingUid) != null) {
6198            return 0;
6199        }
6200        synchronized (mPackages) {
6201            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6202            if (obj instanceof SharedUserSetting) {
6203                final SharedUserSetting sus = (SharedUserSetting) obj;
6204                return sus.pkgPrivateFlags;
6205            } else if (obj instanceof PackageSetting) {
6206                final PackageSetting ps = (PackageSetting) obj;
6207                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6208                    return 0;
6209                }
6210                return ps.pkgPrivateFlags;
6211            }
6212        }
6213        return 0;
6214    }
6215
6216    @Override
6217    public boolean isUidPrivileged(int uid) {
6218        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6219            return false;
6220        }
6221        uid = UserHandle.getAppId(uid);
6222        // reader
6223        synchronized (mPackages) {
6224            Object obj = mSettings.getUserIdLPr(uid);
6225            if (obj instanceof SharedUserSetting) {
6226                final SharedUserSetting sus = (SharedUserSetting) obj;
6227                final Iterator<PackageSetting> it = sus.packages.iterator();
6228                while (it.hasNext()) {
6229                    if (it.next().isPrivileged()) {
6230                        return true;
6231                    }
6232                }
6233            } else if (obj instanceof PackageSetting) {
6234                final PackageSetting ps = (PackageSetting) obj;
6235                return ps.isPrivileged();
6236            }
6237        }
6238        return false;
6239    }
6240
6241    @Override
6242    public String[] getAppOpPermissionPackages(String permissionName) {
6243        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6244            return null;
6245        }
6246        synchronized (mPackages) {
6247            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6248            if (pkgs == null) {
6249                return null;
6250            }
6251            return pkgs.toArray(new String[pkgs.size()]);
6252        }
6253    }
6254
6255    @Override
6256    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6257            int flags, int userId) {
6258        return resolveIntentInternal(
6259                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6260    }
6261
6262    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6263            int flags, int userId, boolean resolveForStart) {
6264        try {
6265            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6266
6267            if (!sUserManager.exists(userId)) return null;
6268            final int callingUid = Binder.getCallingUid();
6269            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6270            enforceCrossUserPermission(callingUid, userId,
6271                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6272
6273            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6274            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6275                    flags, callingUid, userId, resolveForStart);
6276            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6277
6278            final ResolveInfo bestChoice =
6279                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6280            return bestChoice;
6281        } finally {
6282            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6283        }
6284    }
6285
6286    @Override
6287    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6288        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6289            throw new SecurityException(
6290                    "findPersistentPreferredActivity can only be run by the system");
6291        }
6292        if (!sUserManager.exists(userId)) {
6293            return null;
6294        }
6295        final int callingUid = Binder.getCallingUid();
6296        intent = updateIntentForResolve(intent);
6297        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6298        final int flags = updateFlagsForResolve(
6299                0, userId, intent, callingUid, false /*includeInstantApps*/);
6300        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6301                userId);
6302        synchronized (mPackages) {
6303            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6304                    userId);
6305        }
6306    }
6307
6308    @Override
6309    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6310            IntentFilter filter, int match, ComponentName activity) {
6311        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6312            return;
6313        }
6314        final int userId = UserHandle.getCallingUserId();
6315        if (DEBUG_PREFERRED) {
6316            Log.v(TAG, "setLastChosenActivity intent=" + intent
6317                + " resolvedType=" + resolvedType
6318                + " flags=" + flags
6319                + " filter=" + filter
6320                + " match=" + match
6321                + " activity=" + activity);
6322            filter.dump(new PrintStreamPrinter(System.out), "    ");
6323        }
6324        intent.setComponent(null);
6325        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6326                userId);
6327        // Find any earlier preferred or last chosen entries and nuke them
6328        findPreferredActivity(intent, resolvedType,
6329                flags, query, 0, false, true, false, userId);
6330        // Add the new activity as the last chosen for this filter
6331        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6332                "Setting last chosen");
6333    }
6334
6335    @Override
6336    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6337        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6338            return null;
6339        }
6340        final int userId = UserHandle.getCallingUserId();
6341        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6342        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6343                userId);
6344        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6345                false, false, false, userId);
6346    }
6347
6348    /**
6349     * Returns whether or not instant apps have been disabled remotely.
6350     */
6351    private boolean isEphemeralDisabled() {
6352        return mEphemeralAppsDisabled;
6353    }
6354
6355    private boolean isInstantAppAllowed(
6356            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6357            boolean skipPackageCheck) {
6358        if (mInstantAppResolverConnection == null) {
6359            return false;
6360        }
6361        if (mInstantAppInstallerActivity == null) {
6362            return false;
6363        }
6364        if (intent.getComponent() != null) {
6365            return false;
6366        }
6367        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6368            return false;
6369        }
6370        if (!skipPackageCheck && intent.getPackage() != null) {
6371            return false;
6372        }
6373        final boolean isWebUri = hasWebURI(intent);
6374        if (!isWebUri || intent.getData().getHost() == null) {
6375            return false;
6376        }
6377        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6378        // Or if there's already an ephemeral app installed that handles the action
6379        synchronized (mPackages) {
6380            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6381            for (int n = 0; n < count; n++) {
6382                final ResolveInfo info = resolvedActivities.get(n);
6383                final String packageName = info.activityInfo.packageName;
6384                final PackageSetting ps = mSettings.mPackages.get(packageName);
6385                if (ps != null) {
6386                    // only check domain verification status if the app is not a browser
6387                    if (!info.handleAllWebDataURI) {
6388                        // Try to get the status from User settings first
6389                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6390                        final int status = (int) (packedStatus >> 32);
6391                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6392                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6393                            if (DEBUG_EPHEMERAL) {
6394                                Slog.v(TAG, "DENY instant app;"
6395                                    + " pkg: " + packageName + ", status: " + status);
6396                            }
6397                            return false;
6398                        }
6399                    }
6400                    if (ps.getInstantApp(userId)) {
6401                        if (DEBUG_EPHEMERAL) {
6402                            Slog.v(TAG, "DENY instant app installed;"
6403                                    + " pkg: " + packageName);
6404                        }
6405                        return false;
6406                    }
6407                }
6408            }
6409        }
6410        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6411        return true;
6412    }
6413
6414    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6415            Intent origIntent, String resolvedType, String callingPackage,
6416            Bundle verificationBundle, int userId) {
6417        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6418                new InstantAppRequest(responseObj, origIntent, resolvedType,
6419                        callingPackage, userId, verificationBundle));
6420        mHandler.sendMessage(msg);
6421    }
6422
6423    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6424            int flags, List<ResolveInfo> query, int userId) {
6425        if (query != null) {
6426            final int N = query.size();
6427            if (N == 1) {
6428                return query.get(0);
6429            } else if (N > 1) {
6430                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6431                // If there is more than one activity with the same priority,
6432                // then let the user decide between them.
6433                ResolveInfo r0 = query.get(0);
6434                ResolveInfo r1 = query.get(1);
6435                if (DEBUG_INTENT_MATCHING || debug) {
6436                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6437                            + r1.activityInfo.name + "=" + r1.priority);
6438                }
6439                // If the first activity has a higher priority, or a different
6440                // default, then it is always desirable to pick it.
6441                if (r0.priority != r1.priority
6442                        || r0.preferredOrder != r1.preferredOrder
6443                        || r0.isDefault != r1.isDefault) {
6444                    return query.get(0);
6445                }
6446                // If we have saved a preference for a preferred activity for
6447                // this Intent, use that.
6448                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6449                        flags, query, r0.priority, true, false, debug, userId);
6450                if (ri != null) {
6451                    return ri;
6452                }
6453                // If we have an ephemeral app, use it
6454                for (int i = 0; i < N; i++) {
6455                    ri = query.get(i);
6456                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6457                        final String packageName = ri.activityInfo.packageName;
6458                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6459                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6460                        final int status = (int)(packedStatus >> 32);
6461                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6462                            return ri;
6463                        }
6464                    }
6465                }
6466                ri = new ResolveInfo(mResolveInfo);
6467                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6468                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6469                // If all of the options come from the same package, show the application's
6470                // label and icon instead of the generic resolver's.
6471                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6472                // and then throw away the ResolveInfo itself, meaning that the caller loses
6473                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6474                // a fallback for this case; we only set the target package's resources on
6475                // the ResolveInfo, not the ActivityInfo.
6476                final String intentPackage = intent.getPackage();
6477                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6478                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6479                    ri.resolvePackageName = intentPackage;
6480                    if (userNeedsBadging(userId)) {
6481                        ri.noResourceId = true;
6482                    } else {
6483                        ri.icon = appi.icon;
6484                    }
6485                    ri.iconResourceId = appi.icon;
6486                    ri.labelRes = appi.labelRes;
6487                }
6488                ri.activityInfo.applicationInfo = new ApplicationInfo(
6489                        ri.activityInfo.applicationInfo);
6490                if (userId != 0) {
6491                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6492                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6493                }
6494                // Make sure that the resolver is displayable in car mode
6495                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6496                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6497                return ri;
6498            }
6499        }
6500        return null;
6501    }
6502
6503    /**
6504     * Return true if the given list is not empty and all of its contents have
6505     * an activityInfo with the given package name.
6506     */
6507    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6508        if (ArrayUtils.isEmpty(list)) {
6509            return false;
6510        }
6511        for (int i = 0, N = list.size(); i < N; i++) {
6512            final ResolveInfo ri = list.get(i);
6513            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6514            if (ai == null || !packageName.equals(ai.packageName)) {
6515                return false;
6516            }
6517        }
6518        return true;
6519    }
6520
6521    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6522            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6523        final int N = query.size();
6524        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6525                .get(userId);
6526        // Get the list of persistent preferred activities that handle the intent
6527        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6528        List<PersistentPreferredActivity> pprefs = ppir != null
6529                ? ppir.queryIntent(intent, resolvedType,
6530                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6531                        userId)
6532                : null;
6533        if (pprefs != null && pprefs.size() > 0) {
6534            final int M = pprefs.size();
6535            for (int i=0; i<M; i++) {
6536                final PersistentPreferredActivity ppa = pprefs.get(i);
6537                if (DEBUG_PREFERRED || debug) {
6538                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6539                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6540                            + "\n  component=" + ppa.mComponent);
6541                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6542                }
6543                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6544                        flags | MATCH_DISABLED_COMPONENTS, userId);
6545                if (DEBUG_PREFERRED || debug) {
6546                    Slog.v(TAG, "Found persistent preferred activity:");
6547                    if (ai != null) {
6548                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6549                    } else {
6550                        Slog.v(TAG, "  null");
6551                    }
6552                }
6553                if (ai == null) {
6554                    // This previously registered persistent preferred activity
6555                    // component is no longer known. Ignore it and do NOT remove it.
6556                    continue;
6557                }
6558                for (int j=0; j<N; j++) {
6559                    final ResolveInfo ri = query.get(j);
6560                    if (!ri.activityInfo.applicationInfo.packageName
6561                            .equals(ai.applicationInfo.packageName)) {
6562                        continue;
6563                    }
6564                    if (!ri.activityInfo.name.equals(ai.name)) {
6565                        continue;
6566                    }
6567                    //  Found a persistent preference that can handle the intent.
6568                    if (DEBUG_PREFERRED || debug) {
6569                        Slog.v(TAG, "Returning persistent preferred activity: " +
6570                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6571                    }
6572                    return ri;
6573                }
6574            }
6575        }
6576        return null;
6577    }
6578
6579    // TODO: handle preferred activities missing while user has amnesia
6580    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6581            List<ResolveInfo> query, int priority, boolean always,
6582            boolean removeMatches, boolean debug, int userId) {
6583        if (!sUserManager.exists(userId)) return null;
6584        final int callingUid = Binder.getCallingUid();
6585        flags = updateFlagsForResolve(
6586                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6587        intent = updateIntentForResolve(intent);
6588        // writer
6589        synchronized (mPackages) {
6590            // Try to find a matching persistent preferred activity.
6591            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6592                    debug, userId);
6593
6594            // If a persistent preferred activity matched, use it.
6595            if (pri != null) {
6596                return pri;
6597            }
6598
6599            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6600            // Get the list of preferred activities that handle the intent
6601            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6602            List<PreferredActivity> prefs = pir != null
6603                    ? pir.queryIntent(intent, resolvedType,
6604                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6605                            userId)
6606                    : null;
6607            if (prefs != null && prefs.size() > 0) {
6608                boolean changed = false;
6609                try {
6610                    // First figure out how good the original match set is.
6611                    // We will only allow preferred activities that came
6612                    // from the same match quality.
6613                    int match = 0;
6614
6615                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6616
6617                    final int N = query.size();
6618                    for (int j=0; j<N; j++) {
6619                        final ResolveInfo ri = query.get(j);
6620                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6621                                + ": 0x" + Integer.toHexString(match));
6622                        if (ri.match > match) {
6623                            match = ri.match;
6624                        }
6625                    }
6626
6627                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6628                            + Integer.toHexString(match));
6629
6630                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6631                    final int M = prefs.size();
6632                    for (int i=0; i<M; i++) {
6633                        final PreferredActivity pa = prefs.get(i);
6634                        if (DEBUG_PREFERRED || debug) {
6635                            Slog.v(TAG, "Checking PreferredActivity ds="
6636                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6637                                    + "\n  component=" + pa.mPref.mComponent);
6638                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6639                        }
6640                        if (pa.mPref.mMatch != match) {
6641                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6642                                    + Integer.toHexString(pa.mPref.mMatch));
6643                            continue;
6644                        }
6645                        // If it's not an "always" type preferred activity and that's what we're
6646                        // looking for, skip it.
6647                        if (always && !pa.mPref.mAlways) {
6648                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6649                            continue;
6650                        }
6651                        final ActivityInfo ai = getActivityInfo(
6652                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6653                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6654                                userId);
6655                        if (DEBUG_PREFERRED || debug) {
6656                            Slog.v(TAG, "Found preferred activity:");
6657                            if (ai != null) {
6658                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6659                            } else {
6660                                Slog.v(TAG, "  null");
6661                            }
6662                        }
6663                        if (ai == null) {
6664                            // This previously registered preferred activity
6665                            // component is no longer known.  Most likely an update
6666                            // to the app was installed and in the new version this
6667                            // component no longer exists.  Clean it up by removing
6668                            // it from the preferred activities list, and skip it.
6669                            Slog.w(TAG, "Removing dangling preferred activity: "
6670                                    + pa.mPref.mComponent);
6671                            pir.removeFilter(pa);
6672                            changed = true;
6673                            continue;
6674                        }
6675                        for (int j=0; j<N; j++) {
6676                            final ResolveInfo ri = query.get(j);
6677                            if (!ri.activityInfo.applicationInfo.packageName
6678                                    .equals(ai.applicationInfo.packageName)) {
6679                                continue;
6680                            }
6681                            if (!ri.activityInfo.name.equals(ai.name)) {
6682                                continue;
6683                            }
6684
6685                            if (removeMatches) {
6686                                pir.removeFilter(pa);
6687                                changed = true;
6688                                if (DEBUG_PREFERRED) {
6689                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6690                                }
6691                                break;
6692                            }
6693
6694                            // Okay we found a previously set preferred or last chosen app.
6695                            // If the result set is different from when this
6696                            // was created, we need to clear it and re-ask the
6697                            // user their preference, if we're looking for an "always" type entry.
6698                            if (always && !pa.mPref.sameSet(query)) {
6699                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6700                                        + intent + " type " + resolvedType);
6701                                if (DEBUG_PREFERRED) {
6702                                    Slog.v(TAG, "Removing preferred activity since set changed "
6703                                            + pa.mPref.mComponent);
6704                                }
6705                                pir.removeFilter(pa);
6706                                // Re-add the filter as a "last chosen" entry (!always)
6707                                PreferredActivity lastChosen = new PreferredActivity(
6708                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6709                                pir.addFilter(lastChosen);
6710                                changed = true;
6711                                return null;
6712                            }
6713
6714                            // Yay! Either the set matched or we're looking for the last chosen
6715                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6716                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6717                            return ri;
6718                        }
6719                    }
6720                } finally {
6721                    if (changed) {
6722                        if (DEBUG_PREFERRED) {
6723                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6724                        }
6725                        scheduleWritePackageRestrictionsLocked(userId);
6726                    }
6727                }
6728            }
6729        }
6730        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6731        return null;
6732    }
6733
6734    /*
6735     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6736     */
6737    @Override
6738    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6739            int targetUserId) {
6740        mContext.enforceCallingOrSelfPermission(
6741                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6742        List<CrossProfileIntentFilter> matches =
6743                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6744        if (matches != null) {
6745            int size = matches.size();
6746            for (int i = 0; i < size; i++) {
6747                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6748            }
6749        }
6750        if (hasWebURI(intent)) {
6751            // cross-profile app linking works only towards the parent.
6752            final int callingUid = Binder.getCallingUid();
6753            final UserInfo parent = getProfileParent(sourceUserId);
6754            synchronized(mPackages) {
6755                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6756                        false /*includeInstantApps*/);
6757                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6758                        intent, resolvedType, flags, sourceUserId, parent.id);
6759                return xpDomainInfo != null;
6760            }
6761        }
6762        return false;
6763    }
6764
6765    private UserInfo getProfileParent(int userId) {
6766        final long identity = Binder.clearCallingIdentity();
6767        try {
6768            return sUserManager.getProfileParent(userId);
6769        } finally {
6770            Binder.restoreCallingIdentity(identity);
6771        }
6772    }
6773
6774    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6775            String resolvedType, int userId) {
6776        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6777        if (resolver != null) {
6778            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6779        }
6780        return null;
6781    }
6782
6783    @Override
6784    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6785            String resolvedType, int flags, int userId) {
6786        try {
6787            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6788
6789            return new ParceledListSlice<>(
6790                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6791        } finally {
6792            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6793        }
6794    }
6795
6796    /**
6797     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6798     * instant, returns {@code null}.
6799     */
6800    private String getInstantAppPackageName(int callingUid) {
6801        synchronized (mPackages) {
6802            // If the caller is an isolated app use the owner's uid for the lookup.
6803            if (Process.isIsolated(callingUid)) {
6804                callingUid = mIsolatedOwners.get(callingUid);
6805            }
6806            final int appId = UserHandle.getAppId(callingUid);
6807            final Object obj = mSettings.getUserIdLPr(appId);
6808            if (obj instanceof PackageSetting) {
6809                final PackageSetting ps = (PackageSetting) obj;
6810                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6811                return isInstantApp ? ps.pkg.packageName : null;
6812            }
6813        }
6814        return null;
6815    }
6816
6817    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6818            String resolvedType, int flags, int userId) {
6819        return queryIntentActivitiesInternal(
6820                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6821    }
6822
6823    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6824            String resolvedType, int flags, int filterCallingUid, int userId,
6825            boolean resolveForStart) {
6826        if (!sUserManager.exists(userId)) return Collections.emptyList();
6827        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6828        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6829                false /* requireFullPermission */, false /* checkShell */,
6830                "query intent activities");
6831        final String pkgName = intent.getPackage();
6832        ComponentName comp = intent.getComponent();
6833        if (comp == null) {
6834            if (intent.getSelector() != null) {
6835                intent = intent.getSelector();
6836                comp = intent.getComponent();
6837            }
6838        }
6839
6840        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6841                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6842        if (comp != null) {
6843            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6844            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6845            if (ai != null) {
6846                // When specifying an explicit component, we prevent the activity from being
6847                // used when either 1) the calling package is normal and the activity is within
6848                // an ephemeral application or 2) the calling package is ephemeral and the
6849                // activity is not visible to ephemeral applications.
6850                final boolean matchInstantApp =
6851                        (flags & PackageManager.MATCH_INSTANT) != 0;
6852                final boolean matchVisibleToInstantAppOnly =
6853                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6854                final boolean matchExplicitlyVisibleOnly =
6855                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6856                final boolean isCallerInstantApp =
6857                        instantAppPkgName != null;
6858                final boolean isTargetSameInstantApp =
6859                        comp.getPackageName().equals(instantAppPkgName);
6860                final boolean isTargetInstantApp =
6861                        (ai.applicationInfo.privateFlags
6862                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6863                final boolean isTargetVisibleToInstantApp =
6864                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6865                final boolean isTargetExplicitlyVisibleToInstantApp =
6866                        isTargetVisibleToInstantApp
6867                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6868                final boolean isTargetHiddenFromInstantApp =
6869                        !isTargetVisibleToInstantApp
6870                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6871                final boolean blockResolution =
6872                        !isTargetSameInstantApp
6873                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6874                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6875                                        && isTargetHiddenFromInstantApp));
6876                if (!blockResolution) {
6877                    final ResolveInfo ri = new ResolveInfo();
6878                    ri.activityInfo = ai;
6879                    list.add(ri);
6880                }
6881            }
6882            return applyPostResolutionFilter(list, instantAppPkgName);
6883        }
6884
6885        // reader
6886        boolean sortResult = false;
6887        boolean addEphemeral = false;
6888        List<ResolveInfo> result;
6889        final boolean ephemeralDisabled = isEphemeralDisabled();
6890        synchronized (mPackages) {
6891            if (pkgName == null) {
6892                List<CrossProfileIntentFilter> matchingFilters =
6893                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6894                // Check for results that need to skip the current profile.
6895                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6896                        resolvedType, flags, userId);
6897                if (xpResolveInfo != null) {
6898                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6899                    xpResult.add(xpResolveInfo);
6900                    return applyPostResolutionFilter(
6901                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6902                }
6903
6904                // Check for results in the current profile.
6905                result = filterIfNotSystemUser(mActivities.queryIntent(
6906                        intent, resolvedType, flags, userId), userId);
6907                addEphemeral = !ephemeralDisabled
6908                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6909                // Check for cross profile results.
6910                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6911                xpResolveInfo = queryCrossProfileIntents(
6912                        matchingFilters, intent, resolvedType, flags, userId,
6913                        hasNonNegativePriorityResult);
6914                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6915                    boolean isVisibleToUser = filterIfNotSystemUser(
6916                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6917                    if (isVisibleToUser) {
6918                        result.add(xpResolveInfo);
6919                        sortResult = true;
6920                    }
6921                }
6922                if (hasWebURI(intent)) {
6923                    CrossProfileDomainInfo xpDomainInfo = null;
6924                    final UserInfo parent = getProfileParent(userId);
6925                    if (parent != null) {
6926                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6927                                flags, userId, parent.id);
6928                    }
6929                    if (xpDomainInfo != null) {
6930                        if (xpResolveInfo != null) {
6931                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6932                            // in the result.
6933                            result.remove(xpResolveInfo);
6934                        }
6935                        if (result.size() == 0 && !addEphemeral) {
6936                            // No result in current profile, but found candidate in parent user.
6937                            // And we are not going to add emphemeral app, so we can return the
6938                            // result straight away.
6939                            result.add(xpDomainInfo.resolveInfo);
6940                            return applyPostResolutionFilter(result, instantAppPkgName);
6941                        }
6942                    } else if (result.size() <= 1 && !addEphemeral) {
6943                        // No result in parent user and <= 1 result in current profile, and we
6944                        // are not going to add emphemeral app, so we can return the result without
6945                        // further processing.
6946                        return applyPostResolutionFilter(result, instantAppPkgName);
6947                    }
6948                    // We have more than one candidate (combining results from current and parent
6949                    // profile), so we need filtering and sorting.
6950                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6951                            intent, flags, result, xpDomainInfo, userId);
6952                    sortResult = true;
6953                }
6954            } else {
6955                final PackageParser.Package pkg = mPackages.get(pkgName);
6956                result = null;
6957                if (pkg != null) {
6958                    result = filterIfNotSystemUser(
6959                            mActivities.queryIntentForPackage(
6960                                    intent, resolvedType, flags, pkg.activities, userId),
6961                            userId);
6962                }
6963                if (result == null || result.size() == 0) {
6964                    // the caller wants to resolve for a particular package; however, there
6965                    // were no installed results, so, try to find an ephemeral result
6966                    addEphemeral = !ephemeralDisabled
6967                            && isInstantAppAllowed(
6968                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6969                    if (result == null) {
6970                        result = new ArrayList<>();
6971                    }
6972                }
6973            }
6974        }
6975        if (addEphemeral) {
6976            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
6977        }
6978        if (sortResult) {
6979            Collections.sort(result, mResolvePrioritySorter);
6980        }
6981        return applyPostResolutionFilter(result, instantAppPkgName);
6982    }
6983
6984    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6985            String resolvedType, int flags, int userId) {
6986        // first, check to see if we've got an instant app already installed
6987        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6988        ResolveInfo localInstantApp = null;
6989        boolean blockResolution = false;
6990        if (!alreadyResolvedLocally) {
6991            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6992                    flags
6993                        | PackageManager.GET_RESOLVED_FILTER
6994                        | PackageManager.MATCH_INSTANT
6995                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6996                    userId);
6997            for (int i = instantApps.size() - 1; i >= 0; --i) {
6998                final ResolveInfo info = instantApps.get(i);
6999                final String packageName = info.activityInfo.packageName;
7000                final PackageSetting ps = mSettings.mPackages.get(packageName);
7001                if (ps.getInstantApp(userId)) {
7002                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7003                    final int status = (int)(packedStatus >> 32);
7004                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7005                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7006                        // there's a local instant application installed, but, the user has
7007                        // chosen to never use it; skip resolution and don't acknowledge
7008                        // an instant application is even available
7009                        if (DEBUG_EPHEMERAL) {
7010                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7011                        }
7012                        blockResolution = true;
7013                        break;
7014                    } else {
7015                        // we have a locally installed instant application; skip resolution
7016                        // but acknowledge there's an instant application available
7017                        if (DEBUG_EPHEMERAL) {
7018                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7019                        }
7020                        localInstantApp = info;
7021                        break;
7022                    }
7023                }
7024            }
7025        }
7026        // no app installed, let's see if one's available
7027        AuxiliaryResolveInfo auxiliaryResponse = null;
7028        if (!blockResolution) {
7029            if (localInstantApp == null) {
7030                // we don't have an instant app locally, resolve externally
7031                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7032                final InstantAppRequest requestObject = new InstantAppRequest(
7033                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7034                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7035                auxiliaryResponse =
7036                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7037                                mContext, mInstantAppResolverConnection, requestObject);
7038                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7039            } else {
7040                // we have an instant application locally, but, we can't admit that since
7041                // callers shouldn't be able to determine prior browsing. create a dummy
7042                // auxiliary response so the downstream code behaves as if there's an
7043                // instant application available externally. when it comes time to start
7044                // the instant application, we'll do the right thing.
7045                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7046                auxiliaryResponse = new AuxiliaryResolveInfo(
7047                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7048            }
7049        }
7050        if (auxiliaryResponse != null) {
7051            if (DEBUG_EPHEMERAL) {
7052                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7053            }
7054            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7055            final PackageSetting ps =
7056                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7057            if (ps != null) {
7058                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7059                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7060                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7061                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7062                // make sure this resolver is the default
7063                ephemeralInstaller.isDefault = true;
7064                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7065                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7066                // add a non-generic filter
7067                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7068                ephemeralInstaller.filter.addDataPath(
7069                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7070                ephemeralInstaller.isInstantAppAvailable = true;
7071                result.add(ephemeralInstaller);
7072            }
7073        }
7074        return result;
7075    }
7076
7077    private static class CrossProfileDomainInfo {
7078        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7079        ResolveInfo resolveInfo;
7080        /* Best domain verification status of the activities found in the other profile */
7081        int bestDomainVerificationStatus;
7082    }
7083
7084    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7085            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7086        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7087                sourceUserId)) {
7088            return null;
7089        }
7090        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7091                resolvedType, flags, parentUserId);
7092
7093        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7094            return null;
7095        }
7096        CrossProfileDomainInfo result = null;
7097        int size = resultTargetUser.size();
7098        for (int i = 0; i < size; i++) {
7099            ResolveInfo riTargetUser = resultTargetUser.get(i);
7100            // Intent filter verification is only for filters that specify a host. So don't return
7101            // those that handle all web uris.
7102            if (riTargetUser.handleAllWebDataURI) {
7103                continue;
7104            }
7105            String packageName = riTargetUser.activityInfo.packageName;
7106            PackageSetting ps = mSettings.mPackages.get(packageName);
7107            if (ps == null) {
7108                continue;
7109            }
7110            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7111            int status = (int)(verificationState >> 32);
7112            if (result == null) {
7113                result = new CrossProfileDomainInfo();
7114                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7115                        sourceUserId, parentUserId);
7116                result.bestDomainVerificationStatus = status;
7117            } else {
7118                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7119                        result.bestDomainVerificationStatus);
7120            }
7121        }
7122        // Don't consider matches with status NEVER across profiles.
7123        if (result != null && result.bestDomainVerificationStatus
7124                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7125            return null;
7126        }
7127        return result;
7128    }
7129
7130    /**
7131     * Verification statuses are ordered from the worse to the best, except for
7132     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7133     */
7134    private int bestDomainVerificationStatus(int status1, int status2) {
7135        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7136            return status2;
7137        }
7138        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7139            return status1;
7140        }
7141        return (int) MathUtils.max(status1, status2);
7142    }
7143
7144    private boolean isUserEnabled(int userId) {
7145        long callingId = Binder.clearCallingIdentity();
7146        try {
7147            UserInfo userInfo = sUserManager.getUserInfo(userId);
7148            return userInfo != null && userInfo.isEnabled();
7149        } finally {
7150            Binder.restoreCallingIdentity(callingId);
7151        }
7152    }
7153
7154    /**
7155     * Filter out activities with systemUserOnly flag set, when current user is not System.
7156     *
7157     * @return filtered list
7158     */
7159    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7160        if (userId == UserHandle.USER_SYSTEM) {
7161            return resolveInfos;
7162        }
7163        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7164            ResolveInfo info = resolveInfos.get(i);
7165            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7166                resolveInfos.remove(i);
7167            }
7168        }
7169        return resolveInfos;
7170    }
7171
7172    /**
7173     * Filters out ephemeral activities.
7174     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7175     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7176     *
7177     * @param resolveInfos The pre-filtered list of resolved activities
7178     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7179     *          is performed.
7180     * @return A filtered list of resolved activities.
7181     */
7182    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7183            String ephemeralPkgName) {
7184        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7185            final ResolveInfo info = resolveInfos.get(i);
7186            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7187            // TODO: When adding on-demand split support for non-instant apps, remove this check
7188            // and always apply post filtering
7189            // allow activities that are defined in the provided package
7190            if (isEphemeralApp) {
7191                if (info.activityInfo.splitName != null
7192                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7193                                info.activityInfo.splitName)) {
7194                    // requested activity is defined in a split that hasn't been installed yet.
7195                    // add the installer to the resolve list
7196                    if (DEBUG_EPHEMERAL) {
7197                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7198                    }
7199                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7200                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7201                            info.activityInfo.packageName, info.activityInfo.splitName,
7202                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7203                    // make sure this resolver is the default
7204                    installerInfo.isDefault = true;
7205                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7206                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7207                    // add a non-generic filter
7208                    installerInfo.filter = new IntentFilter();
7209                    // load resources from the correct package
7210                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7211                    resolveInfos.set(i, installerInfo);
7212                    continue;
7213                }
7214            }
7215            // caller is a full app, don't need to apply any other filtering
7216            if (ephemeralPkgName == null) {
7217                continue;
7218            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7219                // caller is same app; don't need to apply any other filtering
7220                continue;
7221            }
7222            // allow activities that have been explicitly exposed to ephemeral apps
7223            if (!isEphemeralApp
7224                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7225                continue;
7226            }
7227            resolveInfos.remove(i);
7228        }
7229        return resolveInfos;
7230    }
7231
7232    /**
7233     * @param resolveInfos list of resolve infos in descending priority order
7234     * @return if the list contains a resolve info with non-negative priority
7235     */
7236    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7237        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7238    }
7239
7240    private static boolean hasWebURI(Intent intent) {
7241        if (intent.getData() == null) {
7242            return false;
7243        }
7244        final String scheme = intent.getScheme();
7245        if (TextUtils.isEmpty(scheme)) {
7246            return false;
7247        }
7248        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7249    }
7250
7251    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7252            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7253            int userId) {
7254        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7255
7256        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7257            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7258                    candidates.size());
7259        }
7260
7261        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7262        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7263        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7264        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7265        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7266        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7267
7268        synchronized (mPackages) {
7269            final int count = candidates.size();
7270            // First, try to use linked apps. Partition the candidates into four lists:
7271            // one for the final results, one for the "do not use ever", one for "undefined status"
7272            // and finally one for "browser app type".
7273            for (int n=0; n<count; n++) {
7274                ResolveInfo info = candidates.get(n);
7275                String packageName = info.activityInfo.packageName;
7276                PackageSetting ps = mSettings.mPackages.get(packageName);
7277                if (ps != null) {
7278                    // Add to the special match all list (Browser use case)
7279                    if (info.handleAllWebDataURI) {
7280                        matchAllList.add(info);
7281                        continue;
7282                    }
7283                    // Try to get the status from User settings first
7284                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7285                    int status = (int)(packedStatus >> 32);
7286                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7287                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7288                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7289                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7290                                    + " : linkgen=" + linkGeneration);
7291                        }
7292                        // Use link-enabled generation as preferredOrder, i.e.
7293                        // prefer newly-enabled over earlier-enabled.
7294                        info.preferredOrder = linkGeneration;
7295                        alwaysList.add(info);
7296                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7297                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7298                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7299                        }
7300                        neverList.add(info);
7301                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7302                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7303                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7304                        }
7305                        alwaysAskList.add(info);
7306                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7307                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7308                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7309                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7310                        }
7311                        undefinedList.add(info);
7312                    }
7313                }
7314            }
7315
7316            // We'll want to include browser possibilities in a few cases
7317            boolean includeBrowser = false;
7318
7319            // First try to add the "always" resolution(s) for the current user, if any
7320            if (alwaysList.size() > 0) {
7321                result.addAll(alwaysList);
7322            } else {
7323                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7324                result.addAll(undefinedList);
7325                // Maybe add one for the other profile.
7326                if (xpDomainInfo != null && (
7327                        xpDomainInfo.bestDomainVerificationStatus
7328                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7329                    result.add(xpDomainInfo.resolveInfo);
7330                }
7331                includeBrowser = true;
7332            }
7333
7334            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7335            // If there were 'always' entries their preferred order has been set, so we also
7336            // back that off to make the alternatives equivalent
7337            if (alwaysAskList.size() > 0) {
7338                for (ResolveInfo i : result) {
7339                    i.preferredOrder = 0;
7340                }
7341                result.addAll(alwaysAskList);
7342                includeBrowser = true;
7343            }
7344
7345            if (includeBrowser) {
7346                // Also add browsers (all of them or only the default one)
7347                if (DEBUG_DOMAIN_VERIFICATION) {
7348                    Slog.v(TAG, "   ...including browsers in candidate set");
7349                }
7350                if ((matchFlags & MATCH_ALL) != 0) {
7351                    result.addAll(matchAllList);
7352                } else {
7353                    // Browser/generic handling case.  If there's a default browser, go straight
7354                    // to that (but only if there is no other higher-priority match).
7355                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7356                    int maxMatchPrio = 0;
7357                    ResolveInfo defaultBrowserMatch = null;
7358                    final int numCandidates = matchAllList.size();
7359                    for (int n = 0; n < numCandidates; n++) {
7360                        ResolveInfo info = matchAllList.get(n);
7361                        // track the highest overall match priority...
7362                        if (info.priority > maxMatchPrio) {
7363                            maxMatchPrio = info.priority;
7364                        }
7365                        // ...and the highest-priority default browser match
7366                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7367                            if (defaultBrowserMatch == null
7368                                    || (defaultBrowserMatch.priority < info.priority)) {
7369                                if (debug) {
7370                                    Slog.v(TAG, "Considering default browser match " + info);
7371                                }
7372                                defaultBrowserMatch = info;
7373                            }
7374                        }
7375                    }
7376                    if (defaultBrowserMatch != null
7377                            && defaultBrowserMatch.priority >= maxMatchPrio
7378                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7379                    {
7380                        if (debug) {
7381                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7382                        }
7383                        result.add(defaultBrowserMatch);
7384                    } else {
7385                        result.addAll(matchAllList);
7386                    }
7387                }
7388
7389                // If there is nothing selected, add all candidates and remove the ones that the user
7390                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7391                if (result.size() == 0) {
7392                    result.addAll(candidates);
7393                    result.removeAll(neverList);
7394                }
7395            }
7396        }
7397        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7398            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7399                    result.size());
7400            for (ResolveInfo info : result) {
7401                Slog.v(TAG, "  + " + info.activityInfo);
7402            }
7403        }
7404        return result;
7405    }
7406
7407    // Returns a packed value as a long:
7408    //
7409    // high 'int'-sized word: link status: undefined/ask/never/always.
7410    // low 'int'-sized word: relative priority among 'always' results.
7411    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7412        long result = ps.getDomainVerificationStatusForUser(userId);
7413        // if none available, get the master status
7414        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7415            if (ps.getIntentFilterVerificationInfo() != null) {
7416                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7417            }
7418        }
7419        return result;
7420    }
7421
7422    private ResolveInfo querySkipCurrentProfileIntents(
7423            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7424            int flags, int sourceUserId) {
7425        if (matchingFilters != null) {
7426            int size = matchingFilters.size();
7427            for (int i = 0; i < size; i ++) {
7428                CrossProfileIntentFilter filter = matchingFilters.get(i);
7429                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7430                    // Checking if there are activities in the target user that can handle the
7431                    // intent.
7432                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7433                            resolvedType, flags, sourceUserId);
7434                    if (resolveInfo != null) {
7435                        return resolveInfo;
7436                    }
7437                }
7438            }
7439        }
7440        return null;
7441    }
7442
7443    // Return matching ResolveInfo in target user if any.
7444    private ResolveInfo queryCrossProfileIntents(
7445            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7446            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7447        if (matchingFilters != null) {
7448            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7449            // match the same intent. For performance reasons, it is better not to
7450            // run queryIntent twice for the same userId
7451            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7452            int size = matchingFilters.size();
7453            for (int i = 0; i < size; i++) {
7454                CrossProfileIntentFilter filter = matchingFilters.get(i);
7455                int targetUserId = filter.getTargetUserId();
7456                boolean skipCurrentProfile =
7457                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7458                boolean skipCurrentProfileIfNoMatchFound =
7459                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7460                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7461                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7462                    // Checking if there are activities in the target user that can handle the
7463                    // intent.
7464                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7465                            resolvedType, flags, sourceUserId);
7466                    if (resolveInfo != null) return resolveInfo;
7467                    alreadyTriedUserIds.put(targetUserId, true);
7468                }
7469            }
7470        }
7471        return null;
7472    }
7473
7474    /**
7475     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7476     * will forward the intent to the filter's target user.
7477     * Otherwise, returns null.
7478     */
7479    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7480            String resolvedType, int flags, int sourceUserId) {
7481        int targetUserId = filter.getTargetUserId();
7482        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7483                resolvedType, flags, targetUserId);
7484        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7485            // If all the matches in the target profile are suspended, return null.
7486            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7487                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7488                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7489                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7490                            targetUserId);
7491                }
7492            }
7493        }
7494        return null;
7495    }
7496
7497    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7498            int sourceUserId, int targetUserId) {
7499        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7500        long ident = Binder.clearCallingIdentity();
7501        boolean targetIsProfile;
7502        try {
7503            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7504        } finally {
7505            Binder.restoreCallingIdentity(ident);
7506        }
7507        String className;
7508        if (targetIsProfile) {
7509            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7510        } else {
7511            className = FORWARD_INTENT_TO_PARENT;
7512        }
7513        ComponentName forwardingActivityComponentName = new ComponentName(
7514                mAndroidApplication.packageName, className);
7515        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7516                sourceUserId);
7517        if (!targetIsProfile) {
7518            forwardingActivityInfo.showUserIcon = targetUserId;
7519            forwardingResolveInfo.noResourceId = true;
7520        }
7521        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7522        forwardingResolveInfo.priority = 0;
7523        forwardingResolveInfo.preferredOrder = 0;
7524        forwardingResolveInfo.match = 0;
7525        forwardingResolveInfo.isDefault = true;
7526        forwardingResolveInfo.filter = filter;
7527        forwardingResolveInfo.targetUserId = targetUserId;
7528        return forwardingResolveInfo;
7529    }
7530
7531    @Override
7532    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7533            Intent[] specifics, String[] specificTypes, Intent intent,
7534            String resolvedType, int flags, int userId) {
7535        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7536                specificTypes, intent, resolvedType, flags, userId));
7537    }
7538
7539    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7540            Intent[] specifics, String[] specificTypes, Intent intent,
7541            String resolvedType, int flags, int userId) {
7542        if (!sUserManager.exists(userId)) return Collections.emptyList();
7543        final int callingUid = Binder.getCallingUid();
7544        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7545                false /*includeInstantApps*/);
7546        enforceCrossUserPermission(callingUid, userId,
7547                false /*requireFullPermission*/, false /*checkShell*/,
7548                "query intent activity options");
7549        final String resultsAction = intent.getAction();
7550
7551        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7552                | PackageManager.GET_RESOLVED_FILTER, userId);
7553
7554        if (DEBUG_INTENT_MATCHING) {
7555            Log.v(TAG, "Query " + intent + ": " + results);
7556        }
7557
7558        int specificsPos = 0;
7559        int N;
7560
7561        // todo: note that the algorithm used here is O(N^2).  This
7562        // isn't a problem in our current environment, but if we start running
7563        // into situations where we have more than 5 or 10 matches then this
7564        // should probably be changed to something smarter...
7565
7566        // First we go through and resolve each of the specific items
7567        // that were supplied, taking care of removing any corresponding
7568        // duplicate items in the generic resolve list.
7569        if (specifics != null) {
7570            for (int i=0; i<specifics.length; i++) {
7571                final Intent sintent = specifics[i];
7572                if (sintent == null) {
7573                    continue;
7574                }
7575
7576                if (DEBUG_INTENT_MATCHING) {
7577                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7578                }
7579
7580                String action = sintent.getAction();
7581                if (resultsAction != null && resultsAction.equals(action)) {
7582                    // If this action was explicitly requested, then don't
7583                    // remove things that have it.
7584                    action = null;
7585                }
7586
7587                ResolveInfo ri = null;
7588                ActivityInfo ai = null;
7589
7590                ComponentName comp = sintent.getComponent();
7591                if (comp == null) {
7592                    ri = resolveIntent(
7593                        sintent,
7594                        specificTypes != null ? specificTypes[i] : null,
7595                            flags, userId);
7596                    if (ri == null) {
7597                        continue;
7598                    }
7599                    if (ri == mResolveInfo) {
7600                        // ACK!  Must do something better with this.
7601                    }
7602                    ai = ri.activityInfo;
7603                    comp = new ComponentName(ai.applicationInfo.packageName,
7604                            ai.name);
7605                } else {
7606                    ai = getActivityInfo(comp, flags, userId);
7607                    if (ai == null) {
7608                        continue;
7609                    }
7610                }
7611
7612                // Look for any generic query activities that are duplicates
7613                // of this specific one, and remove them from the results.
7614                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7615                N = results.size();
7616                int j;
7617                for (j=specificsPos; j<N; j++) {
7618                    ResolveInfo sri = results.get(j);
7619                    if ((sri.activityInfo.name.equals(comp.getClassName())
7620                            && sri.activityInfo.applicationInfo.packageName.equals(
7621                                    comp.getPackageName()))
7622                        || (action != null && sri.filter.matchAction(action))) {
7623                        results.remove(j);
7624                        if (DEBUG_INTENT_MATCHING) Log.v(
7625                            TAG, "Removing duplicate item from " + j
7626                            + " due to specific " + specificsPos);
7627                        if (ri == null) {
7628                            ri = sri;
7629                        }
7630                        j--;
7631                        N--;
7632                    }
7633                }
7634
7635                // Add this specific item to its proper place.
7636                if (ri == null) {
7637                    ri = new ResolveInfo();
7638                    ri.activityInfo = ai;
7639                }
7640                results.add(specificsPos, ri);
7641                ri.specificIndex = i;
7642                specificsPos++;
7643            }
7644        }
7645
7646        // Now we go through the remaining generic results and remove any
7647        // duplicate actions that are found here.
7648        N = results.size();
7649        for (int i=specificsPos; i<N-1; i++) {
7650            final ResolveInfo rii = results.get(i);
7651            if (rii.filter == null) {
7652                continue;
7653            }
7654
7655            // Iterate over all of the actions of this result's intent
7656            // filter...  typically this should be just one.
7657            final Iterator<String> it = rii.filter.actionsIterator();
7658            if (it == null) {
7659                continue;
7660            }
7661            while (it.hasNext()) {
7662                final String action = it.next();
7663                if (resultsAction != null && resultsAction.equals(action)) {
7664                    // If this action was explicitly requested, then don't
7665                    // remove things that have it.
7666                    continue;
7667                }
7668                for (int j=i+1; j<N; j++) {
7669                    final ResolveInfo rij = results.get(j);
7670                    if (rij.filter != null && rij.filter.hasAction(action)) {
7671                        results.remove(j);
7672                        if (DEBUG_INTENT_MATCHING) Log.v(
7673                            TAG, "Removing duplicate item from " + j
7674                            + " due to action " + action + " at " + i);
7675                        j--;
7676                        N--;
7677                    }
7678                }
7679            }
7680
7681            // If the caller didn't request filter information, drop it now
7682            // so we don't have to marshall/unmarshall it.
7683            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7684                rii.filter = null;
7685            }
7686        }
7687
7688        // Filter out the caller activity if so requested.
7689        if (caller != null) {
7690            N = results.size();
7691            for (int i=0; i<N; i++) {
7692                ActivityInfo ainfo = results.get(i).activityInfo;
7693                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7694                        && caller.getClassName().equals(ainfo.name)) {
7695                    results.remove(i);
7696                    break;
7697                }
7698            }
7699        }
7700
7701        // If the caller didn't request filter information,
7702        // drop them now so we don't have to
7703        // marshall/unmarshall it.
7704        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7705            N = results.size();
7706            for (int i=0; i<N; i++) {
7707                results.get(i).filter = null;
7708            }
7709        }
7710
7711        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7712        return results;
7713    }
7714
7715    @Override
7716    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7717            String resolvedType, int flags, int userId) {
7718        return new ParceledListSlice<>(
7719                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7720    }
7721
7722    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7723            String resolvedType, int flags, int userId) {
7724        if (!sUserManager.exists(userId)) return Collections.emptyList();
7725        final int callingUid = Binder.getCallingUid();
7726        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7727        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7728                false /*includeInstantApps*/);
7729        ComponentName comp = intent.getComponent();
7730        if (comp == null) {
7731            if (intent.getSelector() != null) {
7732                intent = intent.getSelector();
7733                comp = intent.getComponent();
7734            }
7735        }
7736        if (comp != null) {
7737            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7738            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7739            if (ai != null) {
7740                // When specifying an explicit component, we prevent the activity from being
7741                // used when either 1) the calling package is normal and the activity is within
7742                // an instant application or 2) the calling package is ephemeral and the
7743                // activity is not visible to instant applications.
7744                final boolean matchInstantApp =
7745                        (flags & PackageManager.MATCH_INSTANT) != 0;
7746                final boolean matchVisibleToInstantAppOnly =
7747                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7748                final boolean matchExplicitlyVisibleOnly =
7749                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7750                final boolean isCallerInstantApp =
7751                        instantAppPkgName != null;
7752                final boolean isTargetSameInstantApp =
7753                        comp.getPackageName().equals(instantAppPkgName);
7754                final boolean isTargetInstantApp =
7755                        (ai.applicationInfo.privateFlags
7756                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7757                final boolean isTargetVisibleToInstantApp =
7758                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7759                final boolean isTargetExplicitlyVisibleToInstantApp =
7760                        isTargetVisibleToInstantApp
7761                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7762                final boolean isTargetHiddenFromInstantApp =
7763                        !isTargetVisibleToInstantApp
7764                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7765                final boolean blockResolution =
7766                        !isTargetSameInstantApp
7767                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7768                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7769                                        && isTargetHiddenFromInstantApp));
7770                if (!blockResolution) {
7771                    ResolveInfo ri = new ResolveInfo();
7772                    ri.activityInfo = ai;
7773                    list.add(ri);
7774                }
7775            }
7776            return applyPostResolutionFilter(list, instantAppPkgName);
7777        }
7778
7779        // reader
7780        synchronized (mPackages) {
7781            String pkgName = intent.getPackage();
7782            if (pkgName == null) {
7783                final List<ResolveInfo> result =
7784                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7785                return applyPostResolutionFilter(result, instantAppPkgName);
7786            }
7787            final PackageParser.Package pkg = mPackages.get(pkgName);
7788            if (pkg != null) {
7789                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7790                        intent, resolvedType, flags, pkg.receivers, userId);
7791                return applyPostResolutionFilter(result, instantAppPkgName);
7792            }
7793            return Collections.emptyList();
7794        }
7795    }
7796
7797    @Override
7798    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7799        final int callingUid = Binder.getCallingUid();
7800        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7801    }
7802
7803    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7804            int userId, int callingUid) {
7805        if (!sUserManager.exists(userId)) return null;
7806        flags = updateFlagsForResolve(
7807                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7808        List<ResolveInfo> query = queryIntentServicesInternal(
7809                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7810        if (query != null) {
7811            if (query.size() >= 1) {
7812                // If there is more than one service with the same priority,
7813                // just arbitrarily pick the first one.
7814                return query.get(0);
7815            }
7816        }
7817        return null;
7818    }
7819
7820    @Override
7821    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7822            String resolvedType, int flags, int userId) {
7823        final int callingUid = Binder.getCallingUid();
7824        return new ParceledListSlice<>(queryIntentServicesInternal(
7825                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7826    }
7827
7828    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7829            String resolvedType, int flags, int userId, int callingUid,
7830            boolean includeInstantApps) {
7831        if (!sUserManager.exists(userId)) return Collections.emptyList();
7832        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7833        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7834        ComponentName comp = intent.getComponent();
7835        if (comp == null) {
7836            if (intent.getSelector() != null) {
7837                intent = intent.getSelector();
7838                comp = intent.getComponent();
7839            }
7840        }
7841        if (comp != null) {
7842            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7843            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7844            if (si != null) {
7845                // When specifying an explicit component, we prevent the service from being
7846                // used when either 1) the service is in an instant application and the
7847                // caller is not the same instant application or 2) the calling package is
7848                // ephemeral and the activity is not visible to ephemeral applications.
7849                final boolean matchInstantApp =
7850                        (flags & PackageManager.MATCH_INSTANT) != 0;
7851                final boolean matchVisibleToInstantAppOnly =
7852                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7853                final boolean isCallerInstantApp =
7854                        instantAppPkgName != null;
7855                final boolean isTargetSameInstantApp =
7856                        comp.getPackageName().equals(instantAppPkgName);
7857                final boolean isTargetInstantApp =
7858                        (si.applicationInfo.privateFlags
7859                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7860                final boolean isTargetHiddenFromInstantApp =
7861                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7862                final boolean blockResolution =
7863                        !isTargetSameInstantApp
7864                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7865                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7866                                        && isTargetHiddenFromInstantApp));
7867                if (!blockResolution) {
7868                    final ResolveInfo ri = new ResolveInfo();
7869                    ri.serviceInfo = si;
7870                    list.add(ri);
7871                }
7872            }
7873            return list;
7874        }
7875
7876        // reader
7877        synchronized (mPackages) {
7878            String pkgName = intent.getPackage();
7879            if (pkgName == null) {
7880                return applyPostServiceResolutionFilter(
7881                        mServices.queryIntent(intent, resolvedType, flags, userId),
7882                        instantAppPkgName);
7883            }
7884            final PackageParser.Package pkg = mPackages.get(pkgName);
7885            if (pkg != null) {
7886                return applyPostServiceResolutionFilter(
7887                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7888                                userId),
7889                        instantAppPkgName);
7890            }
7891            return Collections.emptyList();
7892        }
7893    }
7894
7895    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7896            String instantAppPkgName) {
7897        // TODO: When adding on-demand split support for non-instant apps, remove this check
7898        // and always apply post filtering
7899        if (instantAppPkgName == null) {
7900            return resolveInfos;
7901        }
7902        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7903            final ResolveInfo info = resolveInfos.get(i);
7904            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7905            // allow services that are defined in the provided package
7906            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7907                if (info.serviceInfo.splitName != null
7908                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7909                                info.serviceInfo.splitName)) {
7910                    // requested service is defined in a split that hasn't been installed yet.
7911                    // add the installer to the resolve list
7912                    if (DEBUG_EPHEMERAL) {
7913                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7914                    }
7915                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7916                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7917                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7918                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7919                    // make sure this resolver is the default
7920                    installerInfo.isDefault = true;
7921                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7922                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7923                    // add a non-generic filter
7924                    installerInfo.filter = new IntentFilter();
7925                    // load resources from the correct package
7926                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7927                    resolveInfos.set(i, installerInfo);
7928                }
7929                continue;
7930            }
7931            // allow services that have been explicitly exposed to ephemeral apps
7932            if (!isEphemeralApp
7933                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7934                continue;
7935            }
7936            resolveInfos.remove(i);
7937        }
7938        return resolveInfos;
7939    }
7940
7941    @Override
7942    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7943            String resolvedType, int flags, int userId) {
7944        return new ParceledListSlice<>(
7945                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7946    }
7947
7948    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7949            Intent intent, String resolvedType, int flags, int userId) {
7950        if (!sUserManager.exists(userId)) return Collections.emptyList();
7951        final int callingUid = Binder.getCallingUid();
7952        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7953        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7954                false /*includeInstantApps*/);
7955        ComponentName comp = intent.getComponent();
7956        if (comp == null) {
7957            if (intent.getSelector() != null) {
7958                intent = intent.getSelector();
7959                comp = intent.getComponent();
7960            }
7961        }
7962        if (comp != null) {
7963            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7964            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7965            if (pi != null) {
7966                // When specifying an explicit component, we prevent the provider from being
7967                // used when either 1) the provider is in an instant application and the
7968                // caller is not the same instant application or 2) the calling package is an
7969                // instant application and the provider is not visible to instant applications.
7970                final boolean matchInstantApp =
7971                        (flags & PackageManager.MATCH_INSTANT) != 0;
7972                final boolean matchVisibleToInstantAppOnly =
7973                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7974                final boolean isCallerInstantApp =
7975                        instantAppPkgName != null;
7976                final boolean isTargetSameInstantApp =
7977                        comp.getPackageName().equals(instantAppPkgName);
7978                final boolean isTargetInstantApp =
7979                        (pi.applicationInfo.privateFlags
7980                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7981                final boolean isTargetHiddenFromInstantApp =
7982                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7983                final boolean blockResolution =
7984                        !isTargetSameInstantApp
7985                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7986                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7987                                        && isTargetHiddenFromInstantApp));
7988                if (!blockResolution) {
7989                    final ResolveInfo ri = new ResolveInfo();
7990                    ri.providerInfo = pi;
7991                    list.add(ri);
7992                }
7993            }
7994            return list;
7995        }
7996
7997        // reader
7998        synchronized (mPackages) {
7999            String pkgName = intent.getPackage();
8000            if (pkgName == null) {
8001                return applyPostContentProviderResolutionFilter(
8002                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8003                        instantAppPkgName);
8004            }
8005            final PackageParser.Package pkg = mPackages.get(pkgName);
8006            if (pkg != null) {
8007                return applyPostContentProviderResolutionFilter(
8008                        mProviders.queryIntentForPackage(
8009                        intent, resolvedType, flags, pkg.providers, userId),
8010                        instantAppPkgName);
8011            }
8012            return Collections.emptyList();
8013        }
8014    }
8015
8016    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8017            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8018        // TODO: When adding on-demand split support for non-instant applications, remove
8019        // this check and always apply post filtering
8020        if (instantAppPkgName == null) {
8021            return resolveInfos;
8022        }
8023        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8024            final ResolveInfo info = resolveInfos.get(i);
8025            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8026            // allow providers that are defined in the provided package
8027            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8028                if (info.providerInfo.splitName != null
8029                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8030                                info.providerInfo.splitName)) {
8031                    // requested provider is defined in a split that hasn't been installed yet.
8032                    // add the installer to the resolve list
8033                    if (DEBUG_EPHEMERAL) {
8034                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8035                    }
8036                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8037                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8038                            info.providerInfo.packageName, info.providerInfo.splitName,
8039                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8040                    // make sure this resolver is the default
8041                    installerInfo.isDefault = true;
8042                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8043                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8044                    // add a non-generic filter
8045                    installerInfo.filter = new IntentFilter();
8046                    // load resources from the correct package
8047                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8048                    resolveInfos.set(i, installerInfo);
8049                }
8050                continue;
8051            }
8052            // allow providers that have been explicitly exposed to instant applications
8053            if (!isEphemeralApp
8054                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8055                continue;
8056            }
8057            resolveInfos.remove(i);
8058        }
8059        return resolveInfos;
8060    }
8061
8062    @Override
8063    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8064        final int callingUid = Binder.getCallingUid();
8065        if (getInstantAppPackageName(callingUid) != null) {
8066            return ParceledListSlice.emptyList();
8067        }
8068        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8069        flags = updateFlagsForPackage(flags, userId, null);
8070        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8071        enforceCrossUserPermission(callingUid, userId,
8072                true /* requireFullPermission */, false /* checkShell */,
8073                "get installed packages");
8074
8075        // writer
8076        synchronized (mPackages) {
8077            ArrayList<PackageInfo> list;
8078            if (listUninstalled) {
8079                list = new ArrayList<>(mSettings.mPackages.size());
8080                for (PackageSetting ps : mSettings.mPackages.values()) {
8081                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8082                        continue;
8083                    }
8084                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8085                        return null;
8086                    }
8087                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8088                    if (pi != null) {
8089                        list.add(pi);
8090                    }
8091                }
8092            } else {
8093                list = new ArrayList<>(mPackages.size());
8094                for (PackageParser.Package p : mPackages.values()) {
8095                    final PackageSetting ps = (PackageSetting) p.mExtras;
8096                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8097                        continue;
8098                    }
8099                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8100                        return null;
8101                    }
8102                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8103                            p.mExtras, flags, userId);
8104                    if (pi != null) {
8105                        list.add(pi);
8106                    }
8107                }
8108            }
8109
8110            return new ParceledListSlice<>(list);
8111        }
8112    }
8113
8114    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8115            String[] permissions, boolean[] tmp, int flags, int userId) {
8116        int numMatch = 0;
8117        final PermissionsState permissionsState = ps.getPermissionsState();
8118        for (int i=0; i<permissions.length; i++) {
8119            final String permission = permissions[i];
8120            if (permissionsState.hasPermission(permission, userId)) {
8121                tmp[i] = true;
8122                numMatch++;
8123            } else {
8124                tmp[i] = false;
8125            }
8126        }
8127        if (numMatch == 0) {
8128            return;
8129        }
8130        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8131
8132        // The above might return null in cases of uninstalled apps or install-state
8133        // skew across users/profiles.
8134        if (pi != null) {
8135            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8136                if (numMatch == permissions.length) {
8137                    pi.requestedPermissions = permissions;
8138                } else {
8139                    pi.requestedPermissions = new String[numMatch];
8140                    numMatch = 0;
8141                    for (int i=0; i<permissions.length; i++) {
8142                        if (tmp[i]) {
8143                            pi.requestedPermissions[numMatch] = permissions[i];
8144                            numMatch++;
8145                        }
8146                    }
8147                }
8148            }
8149            list.add(pi);
8150        }
8151    }
8152
8153    @Override
8154    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8155            String[] permissions, int flags, int userId) {
8156        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8157        flags = updateFlagsForPackage(flags, userId, permissions);
8158        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8159                true /* requireFullPermission */, false /* checkShell */,
8160                "get packages holding permissions");
8161        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8162
8163        // writer
8164        synchronized (mPackages) {
8165            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8166            boolean[] tmpBools = new boolean[permissions.length];
8167            if (listUninstalled) {
8168                for (PackageSetting ps : mSettings.mPackages.values()) {
8169                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8170                            userId);
8171                }
8172            } else {
8173                for (PackageParser.Package pkg : mPackages.values()) {
8174                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8175                    if (ps != null) {
8176                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8177                                userId);
8178                    }
8179                }
8180            }
8181
8182            return new ParceledListSlice<PackageInfo>(list);
8183        }
8184    }
8185
8186    @Override
8187    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8188        final int callingUid = Binder.getCallingUid();
8189        if (getInstantAppPackageName(callingUid) != null) {
8190            return ParceledListSlice.emptyList();
8191        }
8192        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8193        flags = updateFlagsForApplication(flags, userId, null);
8194        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8195
8196        // writer
8197        synchronized (mPackages) {
8198            ArrayList<ApplicationInfo> list;
8199            if (listUninstalled) {
8200                list = new ArrayList<>(mSettings.mPackages.size());
8201                for (PackageSetting ps : mSettings.mPackages.values()) {
8202                    ApplicationInfo ai;
8203                    int effectiveFlags = flags;
8204                    if (ps.isSystem()) {
8205                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8206                    }
8207                    if (ps.pkg != null) {
8208                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8209                            continue;
8210                        }
8211                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8212                            return null;
8213                        }
8214                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8215                                ps.readUserState(userId), userId);
8216                        if (ai != null) {
8217                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8218                        }
8219                    } else {
8220                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8221                        // and already converts to externally visible package name
8222                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8223                                callingUid, effectiveFlags, userId);
8224                    }
8225                    if (ai != null) {
8226                        list.add(ai);
8227                    }
8228                }
8229            } else {
8230                list = new ArrayList<>(mPackages.size());
8231                for (PackageParser.Package p : mPackages.values()) {
8232                    if (p.mExtras != null) {
8233                        PackageSetting ps = (PackageSetting) p.mExtras;
8234                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8235                            continue;
8236                        }
8237                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8238                            return null;
8239                        }
8240                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8241                                ps.readUserState(userId), userId);
8242                        if (ai != null) {
8243                            ai.packageName = resolveExternalPackageNameLPr(p);
8244                            list.add(ai);
8245                        }
8246                    }
8247                }
8248            }
8249
8250            return new ParceledListSlice<>(list);
8251        }
8252    }
8253
8254    @Override
8255    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8256        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8257            return null;
8258        }
8259        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8260                "getEphemeralApplications");
8261        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8262                true /* requireFullPermission */, false /* checkShell */,
8263                "getEphemeralApplications");
8264        synchronized (mPackages) {
8265            List<InstantAppInfo> instantApps = mInstantAppRegistry
8266                    .getInstantAppsLPr(userId);
8267            if (instantApps != null) {
8268                return new ParceledListSlice<>(instantApps);
8269            }
8270        }
8271        return null;
8272    }
8273
8274    @Override
8275    public boolean isInstantApp(String packageName, int userId) {
8276        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8277                true /* requireFullPermission */, false /* checkShell */,
8278                "isInstantApp");
8279        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8280            return false;
8281        }
8282
8283        synchronized (mPackages) {
8284            int callingUid = Binder.getCallingUid();
8285            if (Process.isIsolated(callingUid)) {
8286                callingUid = mIsolatedOwners.get(callingUid);
8287            }
8288            final PackageSetting ps = mSettings.mPackages.get(packageName);
8289            PackageParser.Package pkg = mPackages.get(packageName);
8290            final boolean returnAllowed =
8291                    ps != null
8292                    && (isCallerSameApp(packageName, callingUid)
8293                            || canViewInstantApps(callingUid, userId)
8294                            || mInstantAppRegistry.isInstantAccessGranted(
8295                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8296            if (returnAllowed) {
8297                return ps.getInstantApp(userId);
8298            }
8299        }
8300        return false;
8301    }
8302
8303    @Override
8304    public byte[] getInstantAppCookie(String packageName, int userId) {
8305        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8306            return null;
8307        }
8308
8309        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8310                true /* requireFullPermission */, false /* checkShell */,
8311                "getInstantAppCookie");
8312        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8313            return null;
8314        }
8315        synchronized (mPackages) {
8316            return mInstantAppRegistry.getInstantAppCookieLPw(
8317                    packageName, userId);
8318        }
8319    }
8320
8321    @Override
8322    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8323        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8324            return true;
8325        }
8326
8327        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8328                true /* requireFullPermission */, true /* checkShell */,
8329                "setInstantAppCookie");
8330        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8331            return false;
8332        }
8333        synchronized (mPackages) {
8334            return mInstantAppRegistry.setInstantAppCookieLPw(
8335                    packageName, cookie, userId);
8336        }
8337    }
8338
8339    @Override
8340    public Bitmap getInstantAppIcon(String packageName, int userId) {
8341        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8342            return null;
8343        }
8344
8345        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8346                "getInstantAppIcon");
8347
8348        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8349                true /* requireFullPermission */, false /* checkShell */,
8350                "getInstantAppIcon");
8351
8352        synchronized (mPackages) {
8353            return mInstantAppRegistry.getInstantAppIconLPw(
8354                    packageName, userId);
8355        }
8356    }
8357
8358    private boolean isCallerSameApp(String packageName, int uid) {
8359        PackageParser.Package pkg = mPackages.get(packageName);
8360        return pkg != null
8361                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8362    }
8363
8364    @Override
8365    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8366        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8367            return ParceledListSlice.emptyList();
8368        }
8369        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8370    }
8371
8372    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8373        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8374
8375        // reader
8376        synchronized (mPackages) {
8377            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8378            final int userId = UserHandle.getCallingUserId();
8379            while (i.hasNext()) {
8380                final PackageParser.Package p = i.next();
8381                if (p.applicationInfo == null) continue;
8382
8383                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8384                        && !p.applicationInfo.isDirectBootAware();
8385                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8386                        && p.applicationInfo.isDirectBootAware();
8387
8388                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8389                        && (!mSafeMode || isSystemApp(p))
8390                        && (matchesUnaware || matchesAware)) {
8391                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8392                    if (ps != null) {
8393                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8394                                ps.readUserState(userId), userId);
8395                        if (ai != null) {
8396                            finalList.add(ai);
8397                        }
8398                    }
8399                }
8400            }
8401        }
8402
8403        return finalList;
8404    }
8405
8406    @Override
8407    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8408        if (!sUserManager.exists(userId)) return null;
8409        flags = updateFlagsForComponent(flags, userId, name);
8410        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8411        // reader
8412        synchronized (mPackages) {
8413            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8414            PackageSetting ps = provider != null
8415                    ? mSettings.mPackages.get(provider.owner.packageName)
8416                    : null;
8417            if (ps != null) {
8418                final boolean isInstantApp = ps.getInstantApp(userId);
8419                // normal application; filter out instant application provider
8420                if (instantAppPkgName == null && isInstantApp) {
8421                    return null;
8422                }
8423                // instant application; filter out other instant applications
8424                if (instantAppPkgName != null
8425                        && isInstantApp
8426                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8427                    return null;
8428                }
8429                // instant application; filter out non-exposed provider
8430                if (instantAppPkgName != null
8431                        && !isInstantApp
8432                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8433                    return null;
8434                }
8435                // provider not enabled
8436                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8437                    return null;
8438                }
8439                return PackageParser.generateProviderInfo(
8440                        provider, flags, ps.readUserState(userId), userId);
8441            }
8442            return null;
8443        }
8444    }
8445
8446    /**
8447     * @deprecated
8448     */
8449    @Deprecated
8450    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8451        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8452            return;
8453        }
8454        // reader
8455        synchronized (mPackages) {
8456            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8457                    .entrySet().iterator();
8458            final int userId = UserHandle.getCallingUserId();
8459            while (i.hasNext()) {
8460                Map.Entry<String, PackageParser.Provider> entry = i.next();
8461                PackageParser.Provider p = entry.getValue();
8462                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8463
8464                if (ps != null && p.syncable
8465                        && (!mSafeMode || (p.info.applicationInfo.flags
8466                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8467                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8468                            ps.readUserState(userId), userId);
8469                    if (info != null) {
8470                        outNames.add(entry.getKey());
8471                        outInfo.add(info);
8472                    }
8473                }
8474            }
8475        }
8476    }
8477
8478    @Override
8479    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8480            int uid, int flags, String metaDataKey) {
8481        final int callingUid = Binder.getCallingUid();
8482        final int userId = processName != null ? UserHandle.getUserId(uid)
8483                : UserHandle.getCallingUserId();
8484        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8485        flags = updateFlagsForComponent(flags, userId, processName);
8486        ArrayList<ProviderInfo> finalList = null;
8487        // reader
8488        synchronized (mPackages) {
8489            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8490            while (i.hasNext()) {
8491                final PackageParser.Provider p = i.next();
8492                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8493                if (ps != null && p.info.authority != null
8494                        && (processName == null
8495                                || (p.info.processName.equals(processName)
8496                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8497                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8498
8499                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8500                    // parameter.
8501                    if (metaDataKey != null
8502                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8503                        continue;
8504                    }
8505                    final ComponentName component =
8506                            new ComponentName(p.info.packageName, p.info.name);
8507                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8508                        continue;
8509                    }
8510                    if (finalList == null) {
8511                        finalList = new ArrayList<ProviderInfo>(3);
8512                    }
8513                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8514                            ps.readUserState(userId), userId);
8515                    if (info != null) {
8516                        finalList.add(info);
8517                    }
8518                }
8519            }
8520        }
8521
8522        if (finalList != null) {
8523            Collections.sort(finalList, mProviderInitOrderSorter);
8524            return new ParceledListSlice<ProviderInfo>(finalList);
8525        }
8526
8527        return ParceledListSlice.emptyList();
8528    }
8529
8530    @Override
8531    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8532        // reader
8533        synchronized (mPackages) {
8534            final int callingUid = Binder.getCallingUid();
8535            final int callingUserId = UserHandle.getUserId(callingUid);
8536            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8537            if (ps == null) return null;
8538            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8539                return null;
8540            }
8541            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8542            return PackageParser.generateInstrumentationInfo(i, flags);
8543        }
8544    }
8545
8546    @Override
8547    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8548            String targetPackage, int flags) {
8549        final int callingUid = Binder.getCallingUid();
8550        final int callingUserId = UserHandle.getUserId(callingUid);
8551        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8552        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8553            return ParceledListSlice.emptyList();
8554        }
8555        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8556    }
8557
8558    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8559            int flags) {
8560        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8561
8562        // reader
8563        synchronized (mPackages) {
8564            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8565            while (i.hasNext()) {
8566                final PackageParser.Instrumentation p = i.next();
8567                if (targetPackage == null
8568                        || targetPackage.equals(p.info.targetPackage)) {
8569                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8570                            flags);
8571                    if (ii != null) {
8572                        finalList.add(ii);
8573                    }
8574                }
8575            }
8576        }
8577
8578        return finalList;
8579    }
8580
8581    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8582        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8583        try {
8584            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8585        } finally {
8586            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8587        }
8588    }
8589
8590    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8591        final File[] files = dir.listFiles();
8592        if (ArrayUtils.isEmpty(files)) {
8593            Log.d(TAG, "No files in app dir " + dir);
8594            return;
8595        }
8596
8597        if (DEBUG_PACKAGE_SCANNING) {
8598            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8599                    + " flags=0x" + Integer.toHexString(parseFlags));
8600        }
8601        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8602                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8603                mParallelPackageParserCallback);
8604
8605        // Submit files for parsing in parallel
8606        int fileCount = 0;
8607        for (File file : files) {
8608            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8609                    && !PackageInstallerService.isStageName(file.getName());
8610            if (!isPackage) {
8611                // Ignore entries which are not packages
8612                continue;
8613            }
8614            parallelPackageParser.submit(file, parseFlags);
8615            fileCount++;
8616        }
8617
8618        // Process results one by one
8619        for (; fileCount > 0; fileCount--) {
8620            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8621            Throwable throwable = parseResult.throwable;
8622            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8623
8624            if (throwable == null) {
8625                // Static shared libraries have synthetic package names
8626                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8627                    renameStaticSharedLibraryPackage(parseResult.pkg);
8628                }
8629                try {
8630                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8631                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8632                                currentTime, null);
8633                    }
8634                } catch (PackageManagerException e) {
8635                    errorCode = e.error;
8636                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8637                }
8638            } else if (throwable instanceof PackageParser.PackageParserException) {
8639                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8640                        throwable;
8641                errorCode = e.error;
8642                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8643            } else {
8644                throw new IllegalStateException("Unexpected exception occurred while parsing "
8645                        + parseResult.scanFile, throwable);
8646            }
8647
8648            // Delete invalid userdata apps
8649            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8650                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8651                logCriticalInfo(Log.WARN,
8652                        "Deleting invalid package at " + parseResult.scanFile);
8653                removeCodePathLI(parseResult.scanFile);
8654            }
8655        }
8656        parallelPackageParser.close();
8657    }
8658
8659    private static File getSettingsProblemFile() {
8660        File dataDir = Environment.getDataDirectory();
8661        File systemDir = new File(dataDir, "system");
8662        File fname = new File(systemDir, "uiderrors.txt");
8663        return fname;
8664    }
8665
8666    static void reportSettingsProblem(int priority, String msg) {
8667        logCriticalInfo(priority, msg);
8668    }
8669
8670    public static void logCriticalInfo(int priority, String msg) {
8671        Slog.println(priority, TAG, msg);
8672        EventLogTags.writePmCriticalInfo(msg);
8673        try {
8674            File fname = getSettingsProblemFile();
8675            FileOutputStream out = new FileOutputStream(fname, true);
8676            PrintWriter pw = new FastPrintWriter(out);
8677            SimpleDateFormat formatter = new SimpleDateFormat();
8678            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8679            pw.println(dateString + ": " + msg);
8680            pw.close();
8681            FileUtils.setPermissions(
8682                    fname.toString(),
8683                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8684                    -1, -1);
8685        } catch (java.io.IOException e) {
8686        }
8687    }
8688
8689    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8690        if (srcFile.isDirectory()) {
8691            final File baseFile = new File(pkg.baseCodePath);
8692            long maxModifiedTime = baseFile.lastModified();
8693            if (pkg.splitCodePaths != null) {
8694                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8695                    final File splitFile = new File(pkg.splitCodePaths[i]);
8696                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8697                }
8698            }
8699            return maxModifiedTime;
8700        }
8701        return srcFile.lastModified();
8702    }
8703
8704    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8705            final int policyFlags) throws PackageManagerException {
8706        // When upgrading from pre-N MR1, verify the package time stamp using the package
8707        // directory and not the APK file.
8708        final long lastModifiedTime = mIsPreNMR1Upgrade
8709                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8710        if (ps != null
8711                && ps.codePath.equals(srcFile)
8712                && ps.timeStamp == lastModifiedTime
8713                && !isCompatSignatureUpdateNeeded(pkg)
8714                && !isRecoverSignatureUpdateNeeded(pkg)) {
8715            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8716            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8717            ArraySet<PublicKey> signingKs;
8718            synchronized (mPackages) {
8719                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8720            }
8721            if (ps.signatures.mSignatures != null
8722                    && ps.signatures.mSignatures.length != 0
8723                    && signingKs != null) {
8724                // Optimization: reuse the existing cached certificates
8725                // if the package appears to be unchanged.
8726                pkg.mSignatures = ps.signatures.mSignatures;
8727                pkg.mSigningKeys = signingKs;
8728                return;
8729            }
8730
8731            Slog.w(TAG, "PackageSetting for " + ps.name
8732                    + " is missing signatures.  Collecting certs again to recover them.");
8733        } else {
8734            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8735        }
8736
8737        try {
8738            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8739            PackageParser.collectCertificates(pkg, policyFlags);
8740        } catch (PackageParserException e) {
8741            throw PackageManagerException.from(e);
8742        } finally {
8743            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8744        }
8745    }
8746
8747    /**
8748     *  Traces a package scan.
8749     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8750     */
8751    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8752            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8753        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8754        try {
8755            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8756        } finally {
8757            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8758        }
8759    }
8760
8761    /**
8762     *  Scans a package and returns the newly parsed package.
8763     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8764     */
8765    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8766            long currentTime, UserHandle user) throws PackageManagerException {
8767        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8768        PackageParser pp = new PackageParser();
8769        pp.setSeparateProcesses(mSeparateProcesses);
8770        pp.setOnlyCoreApps(mOnlyCore);
8771        pp.setDisplayMetrics(mMetrics);
8772        pp.setCallback(mPackageParserCallback);
8773
8774        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8775            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8776        }
8777
8778        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8779        final PackageParser.Package pkg;
8780        try {
8781            pkg = pp.parsePackage(scanFile, parseFlags);
8782        } catch (PackageParserException e) {
8783            throw PackageManagerException.from(e);
8784        } finally {
8785            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8786        }
8787
8788        // Static shared libraries have synthetic package names
8789        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8790            renameStaticSharedLibraryPackage(pkg);
8791        }
8792
8793        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8794    }
8795
8796    /**
8797     *  Scans a package and returns the newly parsed package.
8798     *  @throws PackageManagerException on a parse error.
8799     */
8800    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8801            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8802            throws PackageManagerException {
8803        // If the package has children and this is the first dive in the function
8804        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8805        // packages (parent and children) would be successfully scanned before the
8806        // actual scan since scanning mutates internal state and we want to atomically
8807        // install the package and its children.
8808        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8809            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8810                scanFlags |= SCAN_CHECK_ONLY;
8811            }
8812        } else {
8813            scanFlags &= ~SCAN_CHECK_ONLY;
8814        }
8815
8816        // Scan the parent
8817        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8818                scanFlags, currentTime, user);
8819
8820        // Scan the children
8821        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8822        for (int i = 0; i < childCount; i++) {
8823            PackageParser.Package childPackage = pkg.childPackages.get(i);
8824            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8825                    currentTime, user);
8826        }
8827
8828
8829        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8830            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8831        }
8832
8833        return scannedPkg;
8834    }
8835
8836    /**
8837     *  Scans a package and returns the newly parsed package.
8838     *  @throws PackageManagerException on a parse error.
8839     */
8840    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8841            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8842            throws PackageManagerException {
8843        PackageSetting ps = null;
8844        PackageSetting updatedPkg;
8845        // reader
8846        synchronized (mPackages) {
8847            // Look to see if we already know about this package.
8848            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8849            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8850                // This package has been renamed to its original name.  Let's
8851                // use that.
8852                ps = mSettings.getPackageLPr(oldName);
8853            }
8854            // If there was no original package, see one for the real package name.
8855            if (ps == null) {
8856                ps = mSettings.getPackageLPr(pkg.packageName);
8857            }
8858            // Check to see if this package could be hiding/updating a system
8859            // package.  Must look for it either under the original or real
8860            // package name depending on our state.
8861            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8862            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8863
8864            // If this is a package we don't know about on the system partition, we
8865            // may need to remove disabled child packages on the system partition
8866            // or may need to not add child packages if the parent apk is updated
8867            // on the data partition and no longer defines this child package.
8868            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8869                // If this is a parent package for an updated system app and this system
8870                // app got an OTA update which no longer defines some of the child packages
8871                // we have to prune them from the disabled system packages.
8872                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8873                if (disabledPs != null) {
8874                    final int scannedChildCount = (pkg.childPackages != null)
8875                            ? pkg.childPackages.size() : 0;
8876                    final int disabledChildCount = disabledPs.childPackageNames != null
8877                            ? disabledPs.childPackageNames.size() : 0;
8878                    for (int i = 0; i < disabledChildCount; i++) {
8879                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8880                        boolean disabledPackageAvailable = false;
8881                        for (int j = 0; j < scannedChildCount; j++) {
8882                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8883                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8884                                disabledPackageAvailable = true;
8885                                break;
8886                            }
8887                         }
8888                         if (!disabledPackageAvailable) {
8889                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8890                         }
8891                    }
8892                }
8893            }
8894        }
8895
8896        boolean updatedPkgBetter = false;
8897        // First check if this is a system package that may involve an update
8898        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8899            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8900            // it needs to drop FLAG_PRIVILEGED.
8901            if (locationIsPrivileged(scanFile)) {
8902                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8903            } else {
8904                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8905            }
8906
8907            if (ps != null && !ps.codePath.equals(scanFile)) {
8908                // The path has changed from what was last scanned...  check the
8909                // version of the new path against what we have stored to determine
8910                // what to do.
8911                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8912                if (pkg.mVersionCode <= ps.versionCode) {
8913                    // The system package has been updated and the code path does not match
8914                    // Ignore entry. Skip it.
8915                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8916                            + " ignored: updated version " + ps.versionCode
8917                            + " better than this " + pkg.mVersionCode);
8918                    if (!updatedPkg.codePath.equals(scanFile)) {
8919                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8920                                + ps.name + " changing from " + updatedPkg.codePathString
8921                                + " to " + scanFile);
8922                        updatedPkg.codePath = scanFile;
8923                        updatedPkg.codePathString = scanFile.toString();
8924                        updatedPkg.resourcePath = scanFile;
8925                        updatedPkg.resourcePathString = scanFile.toString();
8926                    }
8927                    updatedPkg.pkg = pkg;
8928                    updatedPkg.versionCode = pkg.mVersionCode;
8929
8930                    // Update the disabled system child packages to point to the package too.
8931                    final int childCount = updatedPkg.childPackageNames != null
8932                            ? updatedPkg.childPackageNames.size() : 0;
8933                    for (int i = 0; i < childCount; i++) {
8934                        String childPackageName = updatedPkg.childPackageNames.get(i);
8935                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8936                                childPackageName);
8937                        if (updatedChildPkg != null) {
8938                            updatedChildPkg.pkg = pkg;
8939                            updatedChildPkg.versionCode = pkg.mVersionCode;
8940                        }
8941                    }
8942
8943                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8944                            + scanFile + " ignored: updated version " + ps.versionCode
8945                            + " better than this " + pkg.mVersionCode);
8946                } else {
8947                    // The current app on the system partition is better than
8948                    // what we have updated to on the data partition; switch
8949                    // back to the system partition version.
8950                    // At this point, its safely assumed that package installation for
8951                    // apps in system partition will go through. If not there won't be a working
8952                    // version of the app
8953                    // writer
8954                    synchronized (mPackages) {
8955                        // Just remove the loaded entries from package lists.
8956                        mPackages.remove(ps.name);
8957                    }
8958
8959                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8960                            + " reverting from " + ps.codePathString
8961                            + ": new version " + pkg.mVersionCode
8962                            + " better than installed " + ps.versionCode);
8963
8964                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8965                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8966                    synchronized (mInstallLock) {
8967                        args.cleanUpResourcesLI();
8968                    }
8969                    synchronized (mPackages) {
8970                        mSettings.enableSystemPackageLPw(ps.name);
8971                    }
8972                    updatedPkgBetter = true;
8973                }
8974            }
8975        }
8976
8977        if (updatedPkg != null) {
8978            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8979            // initially
8980            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8981
8982            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8983            // flag set initially
8984            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8985                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8986            }
8987        }
8988
8989        // Verify certificates against what was last scanned
8990        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8991
8992        /*
8993         * A new system app appeared, but we already had a non-system one of the
8994         * same name installed earlier.
8995         */
8996        boolean shouldHideSystemApp = false;
8997        if (updatedPkg == null && ps != null
8998                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8999            /*
9000             * Check to make sure the signatures match first. If they don't,
9001             * wipe the installed application and its data.
9002             */
9003            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9004                    != PackageManager.SIGNATURE_MATCH) {
9005                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9006                        + " signatures don't match existing userdata copy; removing");
9007                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9008                        "scanPackageInternalLI")) {
9009                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9010                }
9011                ps = null;
9012            } else {
9013                /*
9014                 * If the newly-added system app is an older version than the
9015                 * already installed version, hide it. It will be scanned later
9016                 * and re-added like an update.
9017                 */
9018                if (pkg.mVersionCode <= ps.versionCode) {
9019                    shouldHideSystemApp = true;
9020                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9021                            + " but new version " + pkg.mVersionCode + " better than installed "
9022                            + ps.versionCode + "; hiding system");
9023                } else {
9024                    /*
9025                     * The newly found system app is a newer version that the
9026                     * one previously installed. Simply remove the
9027                     * already-installed application and replace it with our own
9028                     * while keeping the application data.
9029                     */
9030                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9031                            + " reverting from " + ps.codePathString + ": new version "
9032                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9033                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9034                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9035                    synchronized (mInstallLock) {
9036                        args.cleanUpResourcesLI();
9037                    }
9038                }
9039            }
9040        }
9041
9042        // The apk is forward locked (not public) if its code and resources
9043        // are kept in different files. (except for app in either system or
9044        // vendor path).
9045        // TODO grab this value from PackageSettings
9046        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9047            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9048                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9049            }
9050        }
9051
9052        // TODO: extend to support forward-locked splits
9053        String resourcePath = null;
9054        String baseResourcePath = null;
9055        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
9056            if (ps != null && ps.resourcePathString != null) {
9057                resourcePath = ps.resourcePathString;
9058                baseResourcePath = ps.resourcePathString;
9059            } else {
9060                // Should not happen at all. Just log an error.
9061                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9062            }
9063        } else {
9064            resourcePath = pkg.codePath;
9065            baseResourcePath = pkg.baseCodePath;
9066        }
9067
9068        // Set application objects path explicitly.
9069        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9070        pkg.setApplicationInfoCodePath(pkg.codePath);
9071        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9072        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9073        pkg.setApplicationInfoResourcePath(resourcePath);
9074        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9075        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9076
9077        final int userId = ((user == null) ? 0 : user.getIdentifier());
9078        if (ps != null && ps.getInstantApp(userId)) {
9079            scanFlags |= SCAN_AS_INSTANT_APP;
9080        }
9081
9082        // Note that we invoke the following method only if we are about to unpack an application
9083        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9084                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9085
9086        /*
9087         * If the system app should be overridden by a previously installed
9088         * data, hide the system app now and let the /data/app scan pick it up
9089         * again.
9090         */
9091        if (shouldHideSystemApp) {
9092            synchronized (mPackages) {
9093                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9094            }
9095        }
9096
9097        return scannedPkg;
9098    }
9099
9100    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9101        // Derive the new package synthetic package name
9102        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9103                + pkg.staticSharedLibVersion);
9104    }
9105
9106    private static String fixProcessName(String defProcessName,
9107            String processName) {
9108        if (processName == null) {
9109            return defProcessName;
9110        }
9111        return processName;
9112    }
9113
9114    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9115            throws PackageManagerException {
9116        if (pkgSetting.signatures.mSignatures != null) {
9117            // Already existing package. Make sure signatures match
9118            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9119                    == PackageManager.SIGNATURE_MATCH;
9120            if (!match) {
9121                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9122                        == PackageManager.SIGNATURE_MATCH;
9123            }
9124            if (!match) {
9125                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9126                        == PackageManager.SIGNATURE_MATCH;
9127            }
9128            if (!match) {
9129                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9130                        + pkg.packageName + " signatures do not match the "
9131                        + "previously installed version; ignoring!");
9132            }
9133        }
9134
9135        // Check for shared user signatures
9136        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9137            // Already existing package. Make sure signatures match
9138            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9139                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9140            if (!match) {
9141                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9142                        == PackageManager.SIGNATURE_MATCH;
9143            }
9144            if (!match) {
9145                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9146                        == PackageManager.SIGNATURE_MATCH;
9147            }
9148            if (!match) {
9149                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9150                        "Package " + pkg.packageName
9151                        + " has no signatures that match those in shared user "
9152                        + pkgSetting.sharedUser.name + "; ignoring!");
9153            }
9154        }
9155    }
9156
9157    /**
9158     * Enforces that only the system UID or root's UID can call a method exposed
9159     * via Binder.
9160     *
9161     * @param message used as message if SecurityException is thrown
9162     * @throws SecurityException if the caller is not system or root
9163     */
9164    private static final void enforceSystemOrRoot(String message) {
9165        final int uid = Binder.getCallingUid();
9166        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9167            throw new SecurityException(message);
9168        }
9169    }
9170
9171    @Override
9172    public void performFstrimIfNeeded() {
9173        enforceSystemOrRoot("Only the system can request fstrim");
9174
9175        // Before everything else, see whether we need to fstrim.
9176        try {
9177            IStorageManager sm = PackageHelper.getStorageManager();
9178            if (sm != null) {
9179                boolean doTrim = false;
9180                final long interval = android.provider.Settings.Global.getLong(
9181                        mContext.getContentResolver(),
9182                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9183                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9184                if (interval > 0) {
9185                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9186                    if (timeSinceLast > interval) {
9187                        doTrim = true;
9188                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9189                                + "; running immediately");
9190                    }
9191                }
9192                if (doTrim) {
9193                    final boolean dexOptDialogShown;
9194                    synchronized (mPackages) {
9195                        dexOptDialogShown = mDexOptDialogShown;
9196                    }
9197                    if (!isFirstBoot() && dexOptDialogShown) {
9198                        try {
9199                            ActivityManager.getService().showBootMessage(
9200                                    mContext.getResources().getString(
9201                                            R.string.android_upgrading_fstrim), true);
9202                        } catch (RemoteException e) {
9203                        }
9204                    }
9205                    sm.runMaintenance();
9206                }
9207            } else {
9208                Slog.e(TAG, "storageManager service unavailable!");
9209            }
9210        } catch (RemoteException e) {
9211            // Can't happen; StorageManagerService is local
9212        }
9213    }
9214
9215    @Override
9216    public void updatePackagesIfNeeded() {
9217        enforceSystemOrRoot("Only the system can request package update");
9218
9219        // We need to re-extract after an OTA.
9220        boolean causeUpgrade = isUpgrade();
9221
9222        // First boot or factory reset.
9223        // Note: we also handle devices that are upgrading to N right now as if it is their
9224        //       first boot, as they do not have profile data.
9225        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9226
9227        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9228        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9229
9230        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9231            return;
9232        }
9233
9234        List<PackageParser.Package> pkgs;
9235        synchronized (mPackages) {
9236            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9237        }
9238
9239        final long startTime = System.nanoTime();
9240        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9241                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9242                    false /* bootComplete */);
9243
9244        final int elapsedTimeSeconds =
9245                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9246
9247        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9248        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9249        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9250        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9251        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9252    }
9253
9254    /*
9255     * Return the prebuilt profile path given a package base code path.
9256     */
9257    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9258        return pkg.baseCodePath + ".prof";
9259    }
9260
9261    /**
9262     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9263     * containing statistics about the invocation. The array consists of three elements,
9264     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9265     * and {@code numberOfPackagesFailed}.
9266     */
9267    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9268            String compilerFilter, boolean bootComplete) {
9269
9270        int numberOfPackagesVisited = 0;
9271        int numberOfPackagesOptimized = 0;
9272        int numberOfPackagesSkipped = 0;
9273        int numberOfPackagesFailed = 0;
9274        final int numberOfPackagesToDexopt = pkgs.size();
9275
9276        for (PackageParser.Package pkg : pkgs) {
9277            numberOfPackagesVisited++;
9278
9279            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9280                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9281                // that are already compiled.
9282                File profileFile = new File(getPrebuildProfilePath(pkg));
9283                // Copy profile if it exists.
9284                if (profileFile.exists()) {
9285                    try {
9286                        // We could also do this lazily before calling dexopt in
9287                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9288                        // is that we don't have a good way to say "do this only once".
9289                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9290                                pkg.applicationInfo.uid, pkg.packageName)) {
9291                            Log.e(TAG, "Installer failed to copy system profile!");
9292                        }
9293                    } catch (Exception e) {
9294                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9295                                e);
9296                    }
9297                }
9298            }
9299
9300            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9301                if (DEBUG_DEXOPT) {
9302                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9303                }
9304                numberOfPackagesSkipped++;
9305                continue;
9306            }
9307
9308            if (DEBUG_DEXOPT) {
9309                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9310                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9311            }
9312
9313            if (showDialog) {
9314                try {
9315                    ActivityManager.getService().showBootMessage(
9316                            mContext.getResources().getString(R.string.android_upgrading_apk,
9317                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9318                } catch (RemoteException e) {
9319                }
9320                synchronized (mPackages) {
9321                    mDexOptDialogShown = true;
9322                }
9323            }
9324
9325            // If the OTA updates a system app which was previously preopted to a non-preopted state
9326            // the app might end up being verified at runtime. That's because by default the apps
9327            // are verify-profile but for preopted apps there's no profile.
9328            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9329            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9330            // filter (by default 'quicken').
9331            // Note that at this stage unused apps are already filtered.
9332            if (isSystemApp(pkg) &&
9333                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9334                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9335                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9336            }
9337
9338            // checkProfiles is false to avoid merging profiles during boot which
9339            // might interfere with background compilation (b/28612421).
9340            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9341            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9342            // trade-off worth doing to save boot time work.
9343            int dexOptStatus = performDexOptTraced(pkg.packageName,
9344                    false /* checkProfiles */,
9345                    compilerFilter,
9346                    false /* force */,
9347                    bootComplete);
9348            switch (dexOptStatus) {
9349                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9350                    numberOfPackagesOptimized++;
9351                    break;
9352                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9353                    numberOfPackagesSkipped++;
9354                    break;
9355                case PackageDexOptimizer.DEX_OPT_FAILED:
9356                    numberOfPackagesFailed++;
9357                    break;
9358                default:
9359                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9360                    break;
9361            }
9362        }
9363
9364        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9365                numberOfPackagesFailed };
9366    }
9367
9368    @Override
9369    public void notifyPackageUse(String packageName, int reason) {
9370        synchronized (mPackages) {
9371            final int callingUid = Binder.getCallingUid();
9372            final int callingUserId = UserHandle.getUserId(callingUid);
9373            if (getInstantAppPackageName(callingUid) != null) {
9374                if (!isCallerSameApp(packageName, callingUid)) {
9375                    return;
9376                }
9377            } else {
9378                if (isInstantApp(packageName, callingUserId)) {
9379                    return;
9380                }
9381            }
9382            final PackageParser.Package p = mPackages.get(packageName);
9383            if (p == null) {
9384                return;
9385            }
9386            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9387        }
9388    }
9389
9390    @Override
9391    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9392        int userId = UserHandle.getCallingUserId();
9393        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9394        if (ai == null) {
9395            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9396                + loadingPackageName + ", user=" + userId);
9397            return;
9398        }
9399        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9400    }
9401
9402    @Override
9403    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9404            IDexModuleRegisterCallback callback) {
9405        int userId = UserHandle.getCallingUserId();
9406        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9407        DexManager.RegisterDexModuleResult result;
9408        if (ai == null) {
9409            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9410                     " calling user. package=" + packageName + ", user=" + userId);
9411            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9412        } else {
9413            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9414        }
9415
9416        if (callback != null) {
9417            mHandler.post(() -> {
9418                try {
9419                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9420                } catch (RemoteException e) {
9421                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9422                }
9423            });
9424        }
9425    }
9426
9427    @Override
9428    public boolean performDexOpt(String packageName,
9429            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9430        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9431            return false;
9432        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9433            return false;
9434        }
9435        int dexoptStatus = performDexOptWithStatus(
9436              packageName, checkProfiles, compileReason, force, bootComplete);
9437        return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9438    }
9439
9440    /**
9441     * Perform dexopt on the given package and return one of following result:
9442     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9443     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9444     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9445     */
9446    /* package */ int performDexOptWithStatus(String packageName,
9447            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9448        return performDexOptTraced(packageName, checkProfiles,
9449                getCompilerFilterForReason(compileReason), force, bootComplete);
9450    }
9451
9452    @Override
9453    public boolean performDexOptMode(String packageName,
9454            boolean checkProfiles, String targetCompilerFilter, boolean force,
9455            boolean bootComplete) {
9456        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9457            return false;
9458        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9459            return false;
9460        }
9461        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9462                targetCompilerFilter, force, bootComplete);
9463        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9464    }
9465
9466    private int performDexOptTraced(String packageName,
9467                boolean checkProfiles, String targetCompilerFilter, boolean force,
9468                boolean bootComplete) {
9469        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9470        try {
9471            return performDexOptInternal(packageName, checkProfiles,
9472                    targetCompilerFilter, force, bootComplete);
9473        } finally {
9474            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9475        }
9476    }
9477
9478    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9479    // if the package can now be considered up to date for the given filter.
9480    private int performDexOptInternal(String packageName,
9481                boolean checkProfiles, String targetCompilerFilter, boolean force,
9482                boolean bootComplete) {
9483        PackageParser.Package p;
9484        synchronized (mPackages) {
9485            p = mPackages.get(packageName);
9486            if (p == null) {
9487                // Package could not be found. Report failure.
9488                return PackageDexOptimizer.DEX_OPT_FAILED;
9489            }
9490            mPackageUsage.maybeWriteAsync(mPackages);
9491            mCompilerStats.maybeWriteAsync();
9492        }
9493        long callingId = Binder.clearCallingIdentity();
9494        try {
9495            synchronized (mInstallLock) {
9496                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9497                        targetCompilerFilter, force, bootComplete);
9498            }
9499        } finally {
9500            Binder.restoreCallingIdentity(callingId);
9501        }
9502    }
9503
9504    public ArraySet<String> getOptimizablePackages() {
9505        ArraySet<String> pkgs = new ArraySet<String>();
9506        synchronized (mPackages) {
9507            for (PackageParser.Package p : mPackages.values()) {
9508                if (PackageDexOptimizer.canOptimizePackage(p)) {
9509                    pkgs.add(p.packageName);
9510                }
9511            }
9512        }
9513        return pkgs;
9514    }
9515
9516    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9517            boolean checkProfiles, String targetCompilerFilter,
9518            boolean force, boolean bootComplete) {
9519        // Select the dex optimizer based on the force parameter.
9520        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9521        //       allocate an object here.
9522        PackageDexOptimizer pdo = force
9523                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9524                : mPackageDexOptimizer;
9525
9526        // Dexopt all dependencies first. Note: we ignore the return value and march on
9527        // on errors.
9528        // Note that we are going to call performDexOpt on those libraries as many times as
9529        // they are referenced in packages. When we do a batch of performDexOpt (for example
9530        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9531        // and the first package that uses the library will dexopt it. The
9532        // others will see that the compiled code for the library is up to date.
9533        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9534        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9535        if (!deps.isEmpty()) {
9536            for (PackageParser.Package depPackage : deps) {
9537                // TODO: Analyze and investigate if we (should) profile libraries.
9538                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9539                        false /* checkProfiles */,
9540                        targetCompilerFilter,
9541                        getOrCreateCompilerPackageStats(depPackage),
9542                        true /* isUsedByOtherApps */,
9543                        bootComplete);
9544            }
9545        }
9546        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9547                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9548                mDexManager.isUsedByOtherApps(p.packageName), bootComplete);
9549    }
9550
9551    // Performs dexopt on the used secondary dex files belonging to the given package.
9552    // Returns true if all dex files were process successfully (which could mean either dexopt or
9553    // skip). Returns false if any of the files caused errors.
9554    @Override
9555    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9556            boolean force) {
9557        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9558            return false;
9559        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9560            return false;
9561        }
9562        mDexManager.reconcileSecondaryDexFiles(packageName);
9563        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9564    }
9565
9566    public boolean performDexOptSecondary(String packageName, int compileReason,
9567            boolean force) {
9568        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9569    }
9570
9571    /**
9572     * Reconcile the information we have about the secondary dex files belonging to
9573     * {@code packagName} and the actual dex files. For all dex files that were
9574     * deleted, update the internal records and delete the generated oat files.
9575     */
9576    @Override
9577    public void reconcileSecondaryDexFiles(String packageName) {
9578        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9579            return;
9580        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9581            return;
9582        }
9583        mDexManager.reconcileSecondaryDexFiles(packageName);
9584    }
9585
9586    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9587    // a reference there.
9588    /*package*/ DexManager getDexManager() {
9589        return mDexManager;
9590    }
9591
9592    /**
9593     * Execute the background dexopt job immediately.
9594     */
9595    @Override
9596    public boolean runBackgroundDexoptJob() {
9597        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9598            return false;
9599        }
9600        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9601    }
9602
9603    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9604        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9605                || p.usesStaticLibraries != null) {
9606            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9607            Set<String> collectedNames = new HashSet<>();
9608            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9609
9610            retValue.remove(p);
9611
9612            return retValue;
9613        } else {
9614            return Collections.emptyList();
9615        }
9616    }
9617
9618    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9619            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9620        if (!collectedNames.contains(p.packageName)) {
9621            collectedNames.add(p.packageName);
9622            collected.add(p);
9623
9624            if (p.usesLibraries != null) {
9625                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9626                        null, collected, collectedNames);
9627            }
9628            if (p.usesOptionalLibraries != null) {
9629                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9630                        null, collected, collectedNames);
9631            }
9632            if (p.usesStaticLibraries != null) {
9633                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9634                        p.usesStaticLibrariesVersions, collected, collectedNames);
9635            }
9636        }
9637    }
9638
9639    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9640            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9641        final int libNameCount = libs.size();
9642        for (int i = 0; i < libNameCount; i++) {
9643            String libName = libs.get(i);
9644            int version = (versions != null && versions.length == libNameCount)
9645                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9646            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9647            if (libPkg != null) {
9648                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9649            }
9650        }
9651    }
9652
9653    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9654        synchronized (mPackages) {
9655            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9656            if (libEntry != null) {
9657                return mPackages.get(libEntry.apk);
9658            }
9659            return null;
9660        }
9661    }
9662
9663    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9664        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9665        if (versionedLib == null) {
9666            return null;
9667        }
9668        return versionedLib.get(version);
9669    }
9670
9671    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9672        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9673                pkg.staticSharedLibName);
9674        if (versionedLib == null) {
9675            return null;
9676        }
9677        int previousLibVersion = -1;
9678        final int versionCount = versionedLib.size();
9679        for (int i = 0; i < versionCount; i++) {
9680            final int libVersion = versionedLib.keyAt(i);
9681            if (libVersion < pkg.staticSharedLibVersion) {
9682                previousLibVersion = Math.max(previousLibVersion, libVersion);
9683            }
9684        }
9685        if (previousLibVersion >= 0) {
9686            return versionedLib.get(previousLibVersion);
9687        }
9688        return null;
9689    }
9690
9691    public void shutdown() {
9692        mPackageUsage.writeNow(mPackages);
9693        mCompilerStats.writeNow();
9694    }
9695
9696    @Override
9697    public void dumpProfiles(String packageName) {
9698        PackageParser.Package pkg;
9699        synchronized (mPackages) {
9700            pkg = mPackages.get(packageName);
9701            if (pkg == null) {
9702                throw new IllegalArgumentException("Unknown package: " + packageName);
9703            }
9704        }
9705        /* Only the shell, root, or the app user should be able to dump profiles. */
9706        int callingUid = Binder.getCallingUid();
9707        if (callingUid != Process.SHELL_UID &&
9708            callingUid != Process.ROOT_UID &&
9709            callingUid != pkg.applicationInfo.uid) {
9710            throw new SecurityException("dumpProfiles");
9711        }
9712
9713        synchronized (mInstallLock) {
9714            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9715            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9716            try {
9717                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9718                String codePaths = TextUtils.join(";", allCodePaths);
9719                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9720            } catch (InstallerException e) {
9721                Slog.w(TAG, "Failed to dump profiles", e);
9722            }
9723            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9724        }
9725    }
9726
9727    @Override
9728    public void forceDexOpt(String packageName) {
9729        enforceSystemOrRoot("forceDexOpt");
9730
9731        PackageParser.Package pkg;
9732        synchronized (mPackages) {
9733            pkg = mPackages.get(packageName);
9734            if (pkg == null) {
9735                throw new IllegalArgumentException("Unknown package: " + packageName);
9736            }
9737        }
9738
9739        synchronized (mInstallLock) {
9740            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9741
9742            // Whoever is calling forceDexOpt wants a compiled package.
9743            // Don't use profiles since that may cause compilation to be skipped.
9744            final int res = performDexOptInternalWithDependenciesLI(pkg,
9745                    false /* checkProfiles */, getDefaultCompilerFilter(),
9746                    true /* force */,
9747                    true /* bootComplete */);
9748
9749            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9750            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9751                throw new IllegalStateException("Failed to dexopt: " + res);
9752            }
9753        }
9754    }
9755
9756    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9757        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9758            Slog.w(TAG, "Unable to update from " + oldPkg.name
9759                    + " to " + newPkg.packageName
9760                    + ": old package not in system partition");
9761            return false;
9762        } else if (mPackages.get(oldPkg.name) != null) {
9763            Slog.w(TAG, "Unable to update from " + oldPkg.name
9764                    + " to " + newPkg.packageName
9765                    + ": old package still exists");
9766            return false;
9767        }
9768        return true;
9769    }
9770
9771    void removeCodePathLI(File codePath) {
9772        if (codePath.isDirectory()) {
9773            try {
9774                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9775            } catch (InstallerException e) {
9776                Slog.w(TAG, "Failed to remove code path", e);
9777            }
9778        } else {
9779            codePath.delete();
9780        }
9781    }
9782
9783    private int[] resolveUserIds(int userId) {
9784        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9785    }
9786
9787    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9788        if (pkg == null) {
9789            Slog.wtf(TAG, "Package was null!", new Throwable());
9790            return;
9791        }
9792        clearAppDataLeafLIF(pkg, userId, flags);
9793        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9794        for (int i = 0; i < childCount; i++) {
9795            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9796        }
9797    }
9798
9799    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9800        final PackageSetting ps;
9801        synchronized (mPackages) {
9802            ps = mSettings.mPackages.get(pkg.packageName);
9803        }
9804        for (int realUserId : resolveUserIds(userId)) {
9805            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9806            try {
9807                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9808                        ceDataInode);
9809            } catch (InstallerException e) {
9810                Slog.w(TAG, String.valueOf(e));
9811            }
9812        }
9813    }
9814
9815    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9816        if (pkg == null) {
9817            Slog.wtf(TAG, "Package was null!", new Throwable());
9818            return;
9819        }
9820        destroyAppDataLeafLIF(pkg, userId, flags);
9821        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9822        for (int i = 0; i < childCount; i++) {
9823            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9824        }
9825    }
9826
9827    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9828        final PackageSetting ps;
9829        synchronized (mPackages) {
9830            ps = mSettings.mPackages.get(pkg.packageName);
9831        }
9832        for (int realUserId : resolveUserIds(userId)) {
9833            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9834            try {
9835                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9836                        ceDataInode);
9837            } catch (InstallerException e) {
9838                Slog.w(TAG, String.valueOf(e));
9839            }
9840            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9841        }
9842    }
9843
9844    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9845        if (pkg == null) {
9846            Slog.wtf(TAG, "Package was null!", new Throwable());
9847            return;
9848        }
9849        destroyAppProfilesLeafLIF(pkg);
9850        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9851        for (int i = 0; i < childCount; i++) {
9852            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9853        }
9854    }
9855
9856    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9857        try {
9858            mInstaller.destroyAppProfiles(pkg.packageName);
9859        } catch (InstallerException e) {
9860            Slog.w(TAG, String.valueOf(e));
9861        }
9862    }
9863
9864    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9865        if (pkg == null) {
9866            Slog.wtf(TAG, "Package was null!", new Throwable());
9867            return;
9868        }
9869        clearAppProfilesLeafLIF(pkg);
9870        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9871        for (int i = 0; i < childCount; i++) {
9872            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9873        }
9874    }
9875
9876    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9877        try {
9878            mInstaller.clearAppProfiles(pkg.packageName);
9879        } catch (InstallerException e) {
9880            Slog.w(TAG, String.valueOf(e));
9881        }
9882    }
9883
9884    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9885            long lastUpdateTime) {
9886        // Set parent install/update time
9887        PackageSetting ps = (PackageSetting) pkg.mExtras;
9888        if (ps != null) {
9889            ps.firstInstallTime = firstInstallTime;
9890            ps.lastUpdateTime = lastUpdateTime;
9891        }
9892        // Set children install/update time
9893        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9894        for (int i = 0; i < childCount; i++) {
9895            PackageParser.Package childPkg = pkg.childPackages.get(i);
9896            ps = (PackageSetting) childPkg.mExtras;
9897            if (ps != null) {
9898                ps.firstInstallTime = firstInstallTime;
9899                ps.lastUpdateTime = lastUpdateTime;
9900            }
9901        }
9902    }
9903
9904    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9905            PackageParser.Package changingLib) {
9906        if (file.path != null) {
9907            usesLibraryFiles.add(file.path);
9908            return;
9909        }
9910        PackageParser.Package p = mPackages.get(file.apk);
9911        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9912            // If we are doing this while in the middle of updating a library apk,
9913            // then we need to make sure to use that new apk for determining the
9914            // dependencies here.  (We haven't yet finished committing the new apk
9915            // to the package manager state.)
9916            if (p == null || p.packageName.equals(changingLib.packageName)) {
9917                p = changingLib;
9918            }
9919        }
9920        if (p != null) {
9921            usesLibraryFiles.addAll(p.getAllCodePaths());
9922            if (p.usesLibraryFiles != null) {
9923                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9924            }
9925        }
9926    }
9927
9928    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9929            PackageParser.Package changingLib) throws PackageManagerException {
9930        if (pkg == null) {
9931            return;
9932        }
9933        ArraySet<String> usesLibraryFiles = null;
9934        if (pkg.usesLibraries != null) {
9935            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9936                    null, null, pkg.packageName, changingLib, true, null);
9937        }
9938        if (pkg.usesStaticLibraries != null) {
9939            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9940                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9941                    pkg.packageName, changingLib, true, usesLibraryFiles);
9942        }
9943        if (pkg.usesOptionalLibraries != null) {
9944            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9945                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9946        }
9947        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9948            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9949        } else {
9950            pkg.usesLibraryFiles = null;
9951        }
9952    }
9953
9954    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9955            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9956            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9957            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9958            throws PackageManagerException {
9959        final int libCount = requestedLibraries.size();
9960        for (int i = 0; i < libCount; i++) {
9961            final String libName = requestedLibraries.get(i);
9962            final int libVersion = requiredVersions != null ? requiredVersions[i]
9963                    : SharedLibraryInfo.VERSION_UNDEFINED;
9964            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9965            if (libEntry == null) {
9966                if (required) {
9967                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9968                            "Package " + packageName + " requires unavailable shared library "
9969                                    + libName + "; failing!");
9970                } else if (DEBUG_SHARED_LIBRARIES) {
9971                    Slog.i(TAG, "Package " + packageName
9972                            + " desires unavailable shared library "
9973                            + libName + "; ignoring!");
9974                }
9975            } else {
9976                if (requiredVersions != null && requiredCertDigests != null) {
9977                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9978                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9979                            "Package " + packageName + " requires unavailable static shared"
9980                                    + " library " + libName + " version "
9981                                    + libEntry.info.getVersion() + "; failing!");
9982                    }
9983
9984                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9985                    if (libPkg == null) {
9986                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9987                                "Package " + packageName + " requires unavailable static shared"
9988                                        + " library; failing!");
9989                    }
9990
9991                    String expectedCertDigest = requiredCertDigests[i];
9992                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9993                                libPkg.mSignatures[0]);
9994                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9995                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9996                                "Package " + packageName + " requires differently signed" +
9997                                        " static shared library; failing!");
9998                    }
9999                }
10000
10001                if (outUsedLibraries == null) {
10002                    outUsedLibraries = new ArraySet<>();
10003                }
10004                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10005            }
10006        }
10007        return outUsedLibraries;
10008    }
10009
10010    private static boolean hasString(List<String> list, List<String> which) {
10011        if (list == null) {
10012            return false;
10013        }
10014        for (int i=list.size()-1; i>=0; i--) {
10015            for (int j=which.size()-1; j>=0; j--) {
10016                if (which.get(j).equals(list.get(i))) {
10017                    return true;
10018                }
10019            }
10020        }
10021        return false;
10022    }
10023
10024    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10025            PackageParser.Package changingPkg) {
10026        ArrayList<PackageParser.Package> res = null;
10027        for (PackageParser.Package pkg : mPackages.values()) {
10028            if (changingPkg != null
10029                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10030                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10031                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10032                            changingPkg.staticSharedLibName)) {
10033                return null;
10034            }
10035            if (res == null) {
10036                res = new ArrayList<>();
10037            }
10038            res.add(pkg);
10039            try {
10040                updateSharedLibrariesLPr(pkg, changingPkg);
10041            } catch (PackageManagerException e) {
10042                // If a system app update or an app and a required lib missing we
10043                // delete the package and for updated system apps keep the data as
10044                // it is better for the user to reinstall than to be in an limbo
10045                // state. Also libs disappearing under an app should never happen
10046                // - just in case.
10047                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10048                    final int flags = pkg.isUpdatedSystemApp()
10049                            ? PackageManager.DELETE_KEEP_DATA : 0;
10050                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10051                            flags , null, true, null);
10052                }
10053                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10054            }
10055        }
10056        return res;
10057    }
10058
10059    /**
10060     * Derive the value of the {@code cpuAbiOverride} based on the provided
10061     * value and an optional stored value from the package settings.
10062     */
10063    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10064        String cpuAbiOverride = null;
10065
10066        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10067            cpuAbiOverride = null;
10068        } else if (abiOverride != null) {
10069            cpuAbiOverride = abiOverride;
10070        } else if (settings != null) {
10071            cpuAbiOverride = settings.cpuAbiOverrideString;
10072        }
10073
10074        return cpuAbiOverride;
10075    }
10076
10077    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10078            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10079                    throws PackageManagerException {
10080        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10081        // If the package has children and this is the first dive in the function
10082        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10083        // whether all packages (parent and children) would be successfully scanned
10084        // before the actual scan since scanning mutates internal state and we want
10085        // to atomically install the package and its children.
10086        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10087            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10088                scanFlags |= SCAN_CHECK_ONLY;
10089            }
10090        } else {
10091            scanFlags &= ~SCAN_CHECK_ONLY;
10092        }
10093
10094        final PackageParser.Package scannedPkg;
10095        try {
10096            // Scan the parent
10097            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10098            // Scan the children
10099            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10100            for (int i = 0; i < childCount; i++) {
10101                PackageParser.Package childPkg = pkg.childPackages.get(i);
10102                scanPackageLI(childPkg, policyFlags,
10103                        scanFlags, currentTime, user);
10104            }
10105        } finally {
10106            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10107        }
10108
10109        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10110            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10111        }
10112
10113        return scannedPkg;
10114    }
10115
10116    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10117            int scanFlags, long currentTime, @Nullable UserHandle user)
10118                    throws PackageManagerException {
10119        boolean success = false;
10120        try {
10121            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10122                    currentTime, user);
10123            success = true;
10124            return res;
10125        } finally {
10126            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10127                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10128                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10129                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10130                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10131            }
10132        }
10133    }
10134
10135    /**
10136     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10137     */
10138    private static boolean apkHasCode(String fileName) {
10139        StrictJarFile jarFile = null;
10140        try {
10141            jarFile = new StrictJarFile(fileName,
10142                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10143            return jarFile.findEntry("classes.dex") != null;
10144        } catch (IOException ignore) {
10145        } finally {
10146            try {
10147                if (jarFile != null) {
10148                    jarFile.close();
10149                }
10150            } catch (IOException ignore) {}
10151        }
10152        return false;
10153    }
10154
10155    /**
10156     * Enforces code policy for the package. This ensures that if an APK has
10157     * declared hasCode="true" in its manifest that the APK actually contains
10158     * code.
10159     *
10160     * @throws PackageManagerException If bytecode could not be found when it should exist
10161     */
10162    private static void assertCodePolicy(PackageParser.Package pkg)
10163            throws PackageManagerException {
10164        final boolean shouldHaveCode =
10165                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10166        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10167            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10168                    "Package " + pkg.baseCodePath + " code is missing");
10169        }
10170
10171        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10172            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10173                final boolean splitShouldHaveCode =
10174                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10175                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10176                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10177                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10178                }
10179            }
10180        }
10181    }
10182
10183    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10184            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10185                    throws PackageManagerException {
10186        if (DEBUG_PACKAGE_SCANNING) {
10187            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10188                Log.d(TAG, "Scanning package " + pkg.packageName);
10189        }
10190
10191        applyPolicy(pkg, policyFlags);
10192
10193        assertPackageIsValid(pkg, policyFlags, scanFlags);
10194
10195        // Initialize package source and resource directories
10196        final File scanFile = new File(pkg.codePath);
10197        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10198        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10199
10200        SharedUserSetting suid = null;
10201        PackageSetting pkgSetting = null;
10202
10203        // Getting the package setting may have a side-effect, so if we
10204        // are only checking if scan would succeed, stash a copy of the
10205        // old setting to restore at the end.
10206        PackageSetting nonMutatedPs = null;
10207
10208        // We keep references to the derived CPU Abis from settings in oder to reuse
10209        // them in the case where we're not upgrading or booting for the first time.
10210        String primaryCpuAbiFromSettings = null;
10211        String secondaryCpuAbiFromSettings = null;
10212
10213        // writer
10214        synchronized (mPackages) {
10215            if (pkg.mSharedUserId != null) {
10216                // SIDE EFFECTS; may potentially allocate a new shared user
10217                suid = mSettings.getSharedUserLPw(
10218                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10219                if (DEBUG_PACKAGE_SCANNING) {
10220                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10221                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10222                                + "): packages=" + suid.packages);
10223                }
10224            }
10225
10226            // Check if we are renaming from an original package name.
10227            PackageSetting origPackage = null;
10228            String realName = null;
10229            if (pkg.mOriginalPackages != null) {
10230                // This package may need to be renamed to a previously
10231                // installed name.  Let's check on that...
10232                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10233                if (pkg.mOriginalPackages.contains(renamed)) {
10234                    // This package had originally been installed as the
10235                    // original name, and we have already taken care of
10236                    // transitioning to the new one.  Just update the new
10237                    // one to continue using the old name.
10238                    realName = pkg.mRealPackage;
10239                    if (!pkg.packageName.equals(renamed)) {
10240                        // Callers into this function may have already taken
10241                        // care of renaming the package; only do it here if
10242                        // it is not already done.
10243                        pkg.setPackageName(renamed);
10244                    }
10245                } else {
10246                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10247                        if ((origPackage = mSettings.getPackageLPr(
10248                                pkg.mOriginalPackages.get(i))) != null) {
10249                            // We do have the package already installed under its
10250                            // original name...  should we use it?
10251                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10252                                // New package is not compatible with original.
10253                                origPackage = null;
10254                                continue;
10255                            } else if (origPackage.sharedUser != null) {
10256                                // Make sure uid is compatible between packages.
10257                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10258                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10259                                            + " to " + pkg.packageName + ": old uid "
10260                                            + origPackage.sharedUser.name
10261                                            + " differs from " + pkg.mSharedUserId);
10262                                    origPackage = null;
10263                                    continue;
10264                                }
10265                                // TODO: Add case when shared user id is added [b/28144775]
10266                            } else {
10267                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10268                                        + pkg.packageName + " to old name " + origPackage.name);
10269                            }
10270                            break;
10271                        }
10272                    }
10273                }
10274            }
10275
10276            if (mTransferedPackages.contains(pkg.packageName)) {
10277                Slog.w(TAG, "Package " + pkg.packageName
10278                        + " was transferred to another, but its .apk remains");
10279            }
10280
10281            // See comments in nonMutatedPs declaration
10282            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10283                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10284                if (foundPs != null) {
10285                    nonMutatedPs = new PackageSetting(foundPs);
10286                }
10287            }
10288
10289            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10290                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10291                if (foundPs != null) {
10292                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10293                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10294                }
10295            }
10296
10297            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10298            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10299                PackageManagerService.reportSettingsProblem(Log.WARN,
10300                        "Package " + pkg.packageName + " shared user changed from "
10301                                + (pkgSetting.sharedUser != null
10302                                        ? pkgSetting.sharedUser.name : "<nothing>")
10303                                + " to "
10304                                + (suid != null ? suid.name : "<nothing>")
10305                                + "; replacing with new");
10306                pkgSetting = null;
10307            }
10308            final PackageSetting oldPkgSetting =
10309                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10310            final PackageSetting disabledPkgSetting =
10311                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10312
10313            String[] usesStaticLibraries = null;
10314            if (pkg.usesStaticLibraries != null) {
10315                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10316                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10317            }
10318
10319            if (pkgSetting == null) {
10320                final String parentPackageName = (pkg.parentPackage != null)
10321                        ? pkg.parentPackage.packageName : null;
10322                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10323                // REMOVE SharedUserSetting from method; update in a separate call
10324                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10325                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10326                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10327                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10328                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10329                        true /*allowInstall*/, instantApp, parentPackageName,
10330                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10331                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10332                // SIDE EFFECTS; updates system state; move elsewhere
10333                if (origPackage != null) {
10334                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10335                }
10336                mSettings.addUserToSettingLPw(pkgSetting);
10337            } else {
10338                // REMOVE SharedUserSetting from method; update in a separate call.
10339                //
10340                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10341                // secondaryCpuAbi are not known at this point so we always update them
10342                // to null here, only to reset them at a later point.
10343                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10344                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10345                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10346                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10347                        UserManagerService.getInstance(), usesStaticLibraries,
10348                        pkg.usesStaticLibrariesVersions);
10349            }
10350            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10351            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10352
10353            // SIDE EFFECTS; modifies system state; move elsewhere
10354            if (pkgSetting.origPackage != null) {
10355                // If we are first transitioning from an original package,
10356                // fix up the new package's name now.  We need to do this after
10357                // looking up the package under its new name, so getPackageLP
10358                // can take care of fiddling things correctly.
10359                pkg.setPackageName(origPackage.name);
10360
10361                // File a report about this.
10362                String msg = "New package " + pkgSetting.realName
10363                        + " renamed to replace old package " + pkgSetting.name;
10364                reportSettingsProblem(Log.WARN, msg);
10365
10366                // Make a note of it.
10367                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10368                    mTransferedPackages.add(origPackage.name);
10369                }
10370
10371                // No longer need to retain this.
10372                pkgSetting.origPackage = null;
10373            }
10374
10375            // SIDE EFFECTS; modifies system state; move elsewhere
10376            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10377                // Make a note of it.
10378                mTransferedPackages.add(pkg.packageName);
10379            }
10380
10381            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10382                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10383            }
10384
10385            if ((scanFlags & SCAN_BOOTING) == 0
10386                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10387                // Check all shared libraries and map to their actual file path.
10388                // We only do this here for apps not on a system dir, because those
10389                // are the only ones that can fail an install due to this.  We
10390                // will take care of the system apps by updating all of their
10391                // library paths after the scan is done. Also during the initial
10392                // scan don't update any libs as we do this wholesale after all
10393                // apps are scanned to avoid dependency based scanning.
10394                updateSharedLibrariesLPr(pkg, null);
10395            }
10396
10397            if (mFoundPolicyFile) {
10398                SELinuxMMAC.assignSeInfoValue(pkg);
10399            }
10400            pkg.applicationInfo.uid = pkgSetting.appId;
10401            pkg.mExtras = pkgSetting;
10402
10403
10404            // Static shared libs have same package with different versions where
10405            // we internally use a synthetic package name to allow multiple versions
10406            // of the same package, therefore we need to compare signatures against
10407            // the package setting for the latest library version.
10408            PackageSetting signatureCheckPs = pkgSetting;
10409            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10410                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10411                if (libraryEntry != null) {
10412                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10413                }
10414            }
10415
10416            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10417                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10418                    // We just determined the app is signed correctly, so bring
10419                    // over the latest parsed certs.
10420                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10421                } else {
10422                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10423                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10424                                "Package " + pkg.packageName + " upgrade keys do not match the "
10425                                + "previously installed version");
10426                    } else {
10427                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10428                        String msg = "System package " + pkg.packageName
10429                                + " signature changed; retaining data.";
10430                        reportSettingsProblem(Log.WARN, msg);
10431                    }
10432                }
10433            } else {
10434                try {
10435                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10436                    verifySignaturesLP(signatureCheckPs, pkg);
10437                    // We just determined the app is signed correctly, so bring
10438                    // over the latest parsed certs.
10439                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10440                } catch (PackageManagerException e) {
10441                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10442                        throw e;
10443                    }
10444                    // The signature has changed, but this package is in the system
10445                    // image...  let's recover!
10446                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10447                    // However...  if this package is part of a shared user, but it
10448                    // doesn't match the signature of the shared user, let's fail.
10449                    // What this means is that you can't change the signatures
10450                    // associated with an overall shared user, which doesn't seem all
10451                    // that unreasonable.
10452                    if (signatureCheckPs.sharedUser != null) {
10453                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10454                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10455                            throw new PackageManagerException(
10456                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10457                                    "Signature mismatch for shared user: "
10458                                            + pkgSetting.sharedUser);
10459                        }
10460                    }
10461                    // File a report about this.
10462                    String msg = "System package " + pkg.packageName
10463                            + " signature changed; retaining data.";
10464                    reportSettingsProblem(Log.WARN, msg);
10465                }
10466            }
10467
10468            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10469                // This package wants to adopt ownership of permissions from
10470                // another package.
10471                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10472                    final String origName = pkg.mAdoptPermissions.get(i);
10473                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10474                    if (orig != null) {
10475                        if (verifyPackageUpdateLPr(orig, pkg)) {
10476                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10477                                    + pkg.packageName);
10478                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10479                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10480                        }
10481                    }
10482                }
10483            }
10484        }
10485
10486        pkg.applicationInfo.processName = fixProcessName(
10487                pkg.applicationInfo.packageName,
10488                pkg.applicationInfo.processName);
10489
10490        if (pkg != mPlatformPackage) {
10491            // Get all of our default paths setup
10492            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10493        }
10494
10495        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10496
10497        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10498            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10499                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10500                final boolean extractNativeLibs = !pkg.isLibrary();
10501                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10502                        mAppLib32InstallDir);
10503                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10504
10505                // Some system apps still use directory structure for native libraries
10506                // in which case we might end up not detecting abi solely based on apk
10507                // structure. Try to detect abi based on directory structure.
10508                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10509                        pkg.applicationInfo.primaryCpuAbi == null) {
10510                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10511                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10512                }
10513            } else {
10514                // This is not a first boot or an upgrade, don't bother deriving the
10515                // ABI during the scan. Instead, trust the value that was stored in the
10516                // package setting.
10517                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10518                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10519
10520                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10521
10522                if (DEBUG_ABI_SELECTION) {
10523                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10524                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10525                        pkg.applicationInfo.secondaryCpuAbi);
10526                }
10527            }
10528        } else {
10529            if ((scanFlags & SCAN_MOVE) != 0) {
10530                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10531                // but we already have this packages package info in the PackageSetting. We just
10532                // use that and derive the native library path based on the new codepath.
10533                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10534                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10535            }
10536
10537            // Set native library paths again. For moves, the path will be updated based on the
10538            // ABIs we've determined above. For non-moves, the path will be updated based on the
10539            // ABIs we determined during compilation, but the path will depend on the final
10540            // package path (after the rename away from the stage path).
10541            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10542        }
10543
10544        // This is a special case for the "system" package, where the ABI is
10545        // dictated by the zygote configuration (and init.rc). We should keep track
10546        // of this ABI so that we can deal with "normal" applications that run under
10547        // the same UID correctly.
10548        if (mPlatformPackage == pkg) {
10549            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10550                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10551        }
10552
10553        // If there's a mismatch between the abi-override in the package setting
10554        // and the abiOverride specified for the install. Warn about this because we
10555        // would've already compiled the app without taking the package setting into
10556        // account.
10557        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10558            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10559                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10560                        " for package " + pkg.packageName);
10561            }
10562        }
10563
10564        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10565        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10566        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10567
10568        // Copy the derived override back to the parsed package, so that we can
10569        // update the package settings accordingly.
10570        pkg.cpuAbiOverride = cpuAbiOverride;
10571
10572        if (DEBUG_ABI_SELECTION) {
10573            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10574                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10575                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10576        }
10577
10578        // Push the derived path down into PackageSettings so we know what to
10579        // clean up at uninstall time.
10580        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10581
10582        if (DEBUG_ABI_SELECTION) {
10583            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10584                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10585                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10586        }
10587
10588        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10589        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10590            // We don't do this here during boot because we can do it all
10591            // at once after scanning all existing packages.
10592            //
10593            // We also do this *before* we perform dexopt on this package, so that
10594            // we can avoid redundant dexopts, and also to make sure we've got the
10595            // code and package path correct.
10596            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10597        }
10598
10599        if (mFactoryTest && pkg.requestedPermissions.contains(
10600                android.Manifest.permission.FACTORY_TEST)) {
10601            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10602        }
10603
10604        if (isSystemApp(pkg)) {
10605            pkgSetting.isOrphaned = true;
10606        }
10607
10608        // Take care of first install / last update times.
10609        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10610        if (currentTime != 0) {
10611            if (pkgSetting.firstInstallTime == 0) {
10612                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10613            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10614                pkgSetting.lastUpdateTime = currentTime;
10615            }
10616        } else if (pkgSetting.firstInstallTime == 0) {
10617            // We need *something*.  Take time time stamp of the file.
10618            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10619        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10620            if (scanFileTime != pkgSetting.timeStamp) {
10621                // A package on the system image has changed; consider this
10622                // to be an update.
10623                pkgSetting.lastUpdateTime = scanFileTime;
10624            }
10625        }
10626        pkgSetting.setTimeStamp(scanFileTime);
10627
10628        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10629            if (nonMutatedPs != null) {
10630                synchronized (mPackages) {
10631                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10632                }
10633            }
10634        } else {
10635            final int userId = user == null ? 0 : user.getIdentifier();
10636            // Modify state for the given package setting
10637            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10638                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10639            if (pkgSetting.getInstantApp(userId)) {
10640                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10641            }
10642        }
10643        return pkg;
10644    }
10645
10646    /**
10647     * Applies policy to the parsed package based upon the given policy flags.
10648     * Ensures the package is in a good state.
10649     * <p>
10650     * Implementation detail: This method must NOT have any side effect. It would
10651     * ideally be static, but, it requires locks to read system state.
10652     */
10653    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10654        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10655            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10656            if (pkg.applicationInfo.isDirectBootAware()) {
10657                // we're direct boot aware; set for all components
10658                for (PackageParser.Service s : pkg.services) {
10659                    s.info.encryptionAware = s.info.directBootAware = true;
10660                }
10661                for (PackageParser.Provider p : pkg.providers) {
10662                    p.info.encryptionAware = p.info.directBootAware = true;
10663                }
10664                for (PackageParser.Activity a : pkg.activities) {
10665                    a.info.encryptionAware = a.info.directBootAware = true;
10666                }
10667                for (PackageParser.Activity r : pkg.receivers) {
10668                    r.info.encryptionAware = r.info.directBootAware = true;
10669                }
10670            }
10671        } else {
10672            // Only allow system apps to be flagged as core apps.
10673            pkg.coreApp = false;
10674            // clear flags not applicable to regular apps
10675            pkg.applicationInfo.privateFlags &=
10676                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10677            pkg.applicationInfo.privateFlags &=
10678                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10679        }
10680        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10681
10682        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10683            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10684        }
10685
10686        if (!isSystemApp(pkg)) {
10687            // Only system apps can use these features.
10688            pkg.mOriginalPackages = null;
10689            pkg.mRealPackage = null;
10690            pkg.mAdoptPermissions = null;
10691        }
10692    }
10693
10694    /**
10695     * Asserts the parsed package is valid according to the given policy. If the
10696     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10697     * <p>
10698     * Implementation detail: This method must NOT have any side effects. It would
10699     * ideally be static, but, it requires locks to read system state.
10700     *
10701     * @throws PackageManagerException If the package fails any of the validation checks
10702     */
10703    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10704            throws PackageManagerException {
10705        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10706            assertCodePolicy(pkg);
10707        }
10708
10709        if (pkg.applicationInfo.getCodePath() == null ||
10710                pkg.applicationInfo.getResourcePath() == null) {
10711            // Bail out. The resource and code paths haven't been set.
10712            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10713                    "Code and resource paths haven't been set correctly");
10714        }
10715
10716        // Make sure we're not adding any bogus keyset info
10717        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10718        ksms.assertScannedPackageValid(pkg);
10719
10720        synchronized (mPackages) {
10721            // The special "android" package can only be defined once
10722            if (pkg.packageName.equals("android")) {
10723                if (mAndroidApplication != null) {
10724                    Slog.w(TAG, "*************************************************");
10725                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10726                    Slog.w(TAG, " codePath=" + pkg.codePath);
10727                    Slog.w(TAG, "*************************************************");
10728                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10729                            "Core android package being redefined.  Skipping.");
10730                }
10731            }
10732
10733            // A package name must be unique; don't allow duplicates
10734            if (mPackages.containsKey(pkg.packageName)) {
10735                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10736                        "Application package " + pkg.packageName
10737                        + " already installed.  Skipping duplicate.");
10738            }
10739
10740            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10741                // Static libs have a synthetic package name containing the version
10742                // but we still want the base name to be unique.
10743                if (mPackages.containsKey(pkg.manifestPackageName)) {
10744                    throw new PackageManagerException(
10745                            "Duplicate static shared lib provider package");
10746                }
10747
10748                // Static shared libraries should have at least O target SDK
10749                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10750                    throw new PackageManagerException(
10751                            "Packages declaring static-shared libs must target O SDK or higher");
10752                }
10753
10754                // Package declaring static a shared lib cannot be instant apps
10755                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10756                    throw new PackageManagerException(
10757                            "Packages declaring static-shared libs cannot be instant apps");
10758                }
10759
10760                // Package declaring static a shared lib cannot be renamed since the package
10761                // name is synthetic and apps can't code around package manager internals.
10762                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10763                    throw new PackageManagerException(
10764                            "Packages declaring static-shared libs cannot be renamed");
10765                }
10766
10767                // Package declaring static a shared lib cannot declare child packages
10768                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10769                    throw new PackageManagerException(
10770                            "Packages declaring static-shared libs cannot have child packages");
10771                }
10772
10773                // Package declaring static a shared lib cannot declare dynamic libs
10774                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10775                    throw new PackageManagerException(
10776                            "Packages declaring static-shared libs cannot declare dynamic libs");
10777                }
10778
10779                // Package declaring static a shared lib cannot declare shared users
10780                if (pkg.mSharedUserId != null) {
10781                    throw new PackageManagerException(
10782                            "Packages declaring static-shared libs cannot declare shared users");
10783                }
10784
10785                // Static shared libs cannot declare activities
10786                if (!pkg.activities.isEmpty()) {
10787                    throw new PackageManagerException(
10788                            "Static shared libs cannot declare activities");
10789                }
10790
10791                // Static shared libs cannot declare services
10792                if (!pkg.services.isEmpty()) {
10793                    throw new PackageManagerException(
10794                            "Static shared libs cannot declare services");
10795                }
10796
10797                // Static shared libs cannot declare providers
10798                if (!pkg.providers.isEmpty()) {
10799                    throw new PackageManagerException(
10800                            "Static shared libs cannot declare content providers");
10801                }
10802
10803                // Static shared libs cannot declare receivers
10804                if (!pkg.receivers.isEmpty()) {
10805                    throw new PackageManagerException(
10806                            "Static shared libs cannot declare broadcast receivers");
10807                }
10808
10809                // Static shared libs cannot declare permission groups
10810                if (!pkg.permissionGroups.isEmpty()) {
10811                    throw new PackageManagerException(
10812                            "Static shared libs cannot declare permission groups");
10813                }
10814
10815                // Static shared libs cannot declare permissions
10816                if (!pkg.permissions.isEmpty()) {
10817                    throw new PackageManagerException(
10818                            "Static shared libs cannot declare permissions");
10819                }
10820
10821                // Static shared libs cannot declare protected broadcasts
10822                if (pkg.protectedBroadcasts != null) {
10823                    throw new PackageManagerException(
10824                            "Static shared libs cannot declare protected broadcasts");
10825                }
10826
10827                // Static shared libs cannot be overlay targets
10828                if (pkg.mOverlayTarget != null) {
10829                    throw new PackageManagerException(
10830                            "Static shared libs cannot be overlay targets");
10831                }
10832
10833                // The version codes must be ordered as lib versions
10834                int minVersionCode = Integer.MIN_VALUE;
10835                int maxVersionCode = Integer.MAX_VALUE;
10836
10837                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10838                        pkg.staticSharedLibName);
10839                if (versionedLib != null) {
10840                    final int versionCount = versionedLib.size();
10841                    for (int i = 0; i < versionCount; i++) {
10842                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10843                        final int libVersionCode = libInfo.getDeclaringPackage()
10844                                .getVersionCode();
10845                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10846                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10847                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10848                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10849                        } else {
10850                            minVersionCode = maxVersionCode = libVersionCode;
10851                            break;
10852                        }
10853                    }
10854                }
10855                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10856                    throw new PackageManagerException("Static shared"
10857                            + " lib version codes must be ordered as lib versions");
10858                }
10859            }
10860
10861            // Only privileged apps and updated privileged apps can add child packages.
10862            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10863                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10864                    throw new PackageManagerException("Only privileged apps can add child "
10865                            + "packages. Ignoring package " + pkg.packageName);
10866                }
10867                final int childCount = pkg.childPackages.size();
10868                for (int i = 0; i < childCount; i++) {
10869                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10870                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10871                            childPkg.packageName)) {
10872                        throw new PackageManagerException("Can't override child of "
10873                                + "another disabled app. Ignoring package " + pkg.packageName);
10874                    }
10875                }
10876            }
10877
10878            // If we're only installing presumed-existing packages, require that the
10879            // scanned APK is both already known and at the path previously established
10880            // for it.  Previously unknown packages we pick up normally, but if we have an
10881            // a priori expectation about this package's install presence, enforce it.
10882            // With a singular exception for new system packages. When an OTA contains
10883            // a new system package, we allow the codepath to change from a system location
10884            // to the user-installed location. If we don't allow this change, any newer,
10885            // user-installed version of the application will be ignored.
10886            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10887                if (mExpectingBetter.containsKey(pkg.packageName)) {
10888                    logCriticalInfo(Log.WARN,
10889                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10890                } else {
10891                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10892                    if (known != null) {
10893                        if (DEBUG_PACKAGE_SCANNING) {
10894                            Log.d(TAG, "Examining " + pkg.codePath
10895                                    + " and requiring known paths " + known.codePathString
10896                                    + " & " + known.resourcePathString);
10897                        }
10898                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10899                                || !pkg.applicationInfo.getResourcePath().equals(
10900                                        known.resourcePathString)) {
10901                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10902                                    "Application package " + pkg.packageName
10903                                    + " found at " + pkg.applicationInfo.getCodePath()
10904                                    + " but expected at " + known.codePathString
10905                                    + "; ignoring.");
10906                        }
10907                    }
10908                }
10909            }
10910
10911            // Verify that this new package doesn't have any content providers
10912            // that conflict with existing packages.  Only do this if the
10913            // package isn't already installed, since we don't want to break
10914            // things that are installed.
10915            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10916                final int N = pkg.providers.size();
10917                int i;
10918                for (i=0; i<N; i++) {
10919                    PackageParser.Provider p = pkg.providers.get(i);
10920                    if (p.info.authority != null) {
10921                        String names[] = p.info.authority.split(";");
10922                        for (int j = 0; j < names.length; j++) {
10923                            if (mProvidersByAuthority.containsKey(names[j])) {
10924                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10925                                final String otherPackageName =
10926                                        ((other != null && other.getComponentName() != null) ?
10927                                                other.getComponentName().getPackageName() : "?");
10928                                throw new PackageManagerException(
10929                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10930                                        "Can't install because provider name " + names[j]
10931                                                + " (in package " + pkg.applicationInfo.packageName
10932                                                + ") is already used by " + otherPackageName);
10933                            }
10934                        }
10935                    }
10936                }
10937            }
10938        }
10939    }
10940
10941    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10942            int type, String declaringPackageName, int declaringVersionCode) {
10943        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10944        if (versionedLib == null) {
10945            versionedLib = new SparseArray<>();
10946            mSharedLibraries.put(name, versionedLib);
10947            if (type == SharedLibraryInfo.TYPE_STATIC) {
10948                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10949            }
10950        } else if (versionedLib.indexOfKey(version) >= 0) {
10951            return false;
10952        }
10953        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10954                version, type, declaringPackageName, declaringVersionCode);
10955        versionedLib.put(version, libEntry);
10956        return true;
10957    }
10958
10959    private boolean removeSharedLibraryLPw(String name, int version) {
10960        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10961        if (versionedLib == null) {
10962            return false;
10963        }
10964        final int libIdx = versionedLib.indexOfKey(version);
10965        if (libIdx < 0) {
10966            return false;
10967        }
10968        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10969        versionedLib.remove(version);
10970        if (versionedLib.size() <= 0) {
10971            mSharedLibraries.remove(name);
10972            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10973                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10974                        .getPackageName());
10975            }
10976        }
10977        return true;
10978    }
10979
10980    /**
10981     * Adds a scanned package to the system. When this method is finished, the package will
10982     * be available for query, resolution, etc...
10983     */
10984    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10985            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10986        final String pkgName = pkg.packageName;
10987        if (mCustomResolverComponentName != null &&
10988                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10989            setUpCustomResolverActivity(pkg);
10990        }
10991
10992        if (pkg.packageName.equals("android")) {
10993            synchronized (mPackages) {
10994                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10995                    // Set up information for our fall-back user intent resolution activity.
10996                    mPlatformPackage = pkg;
10997                    pkg.mVersionCode = mSdkVersion;
10998                    mAndroidApplication = pkg.applicationInfo;
10999                    if (!mResolverReplaced) {
11000                        mResolveActivity.applicationInfo = mAndroidApplication;
11001                        mResolveActivity.name = ResolverActivity.class.getName();
11002                        mResolveActivity.packageName = mAndroidApplication.packageName;
11003                        mResolveActivity.processName = "system:ui";
11004                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11005                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11006                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11007                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11008                        mResolveActivity.exported = true;
11009                        mResolveActivity.enabled = true;
11010                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11011                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11012                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11013                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11014                                | ActivityInfo.CONFIG_ORIENTATION
11015                                | ActivityInfo.CONFIG_KEYBOARD
11016                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11017                        mResolveInfo.activityInfo = mResolveActivity;
11018                        mResolveInfo.priority = 0;
11019                        mResolveInfo.preferredOrder = 0;
11020                        mResolveInfo.match = 0;
11021                        mResolveComponentName = new ComponentName(
11022                                mAndroidApplication.packageName, mResolveActivity.name);
11023                    }
11024                }
11025            }
11026        }
11027
11028        ArrayList<PackageParser.Package> clientLibPkgs = null;
11029        // writer
11030        synchronized (mPackages) {
11031            boolean hasStaticSharedLibs = false;
11032
11033            // Any app can add new static shared libraries
11034            if (pkg.staticSharedLibName != null) {
11035                // Static shared libs don't allow renaming as they have synthetic package
11036                // names to allow install of multiple versions, so use name from manifest.
11037                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11038                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11039                        pkg.manifestPackageName, pkg.mVersionCode)) {
11040                    hasStaticSharedLibs = true;
11041                } else {
11042                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11043                                + pkg.staticSharedLibName + " already exists; skipping");
11044                }
11045                // Static shared libs cannot be updated once installed since they
11046                // use synthetic package name which includes the version code, so
11047                // not need to update other packages's shared lib dependencies.
11048            }
11049
11050            if (!hasStaticSharedLibs
11051                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11052                // Only system apps can add new dynamic shared libraries.
11053                if (pkg.libraryNames != null) {
11054                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11055                        String name = pkg.libraryNames.get(i);
11056                        boolean allowed = false;
11057                        if (pkg.isUpdatedSystemApp()) {
11058                            // New library entries can only be added through the
11059                            // system image.  This is important to get rid of a lot
11060                            // of nasty edge cases: for example if we allowed a non-
11061                            // system update of the app to add a library, then uninstalling
11062                            // the update would make the library go away, and assumptions
11063                            // we made such as through app install filtering would now
11064                            // have allowed apps on the device which aren't compatible
11065                            // with it.  Better to just have the restriction here, be
11066                            // conservative, and create many fewer cases that can negatively
11067                            // impact the user experience.
11068                            final PackageSetting sysPs = mSettings
11069                                    .getDisabledSystemPkgLPr(pkg.packageName);
11070                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11071                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11072                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11073                                        allowed = true;
11074                                        break;
11075                                    }
11076                                }
11077                            }
11078                        } else {
11079                            allowed = true;
11080                        }
11081                        if (allowed) {
11082                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11083                                    SharedLibraryInfo.VERSION_UNDEFINED,
11084                                    SharedLibraryInfo.TYPE_DYNAMIC,
11085                                    pkg.packageName, pkg.mVersionCode)) {
11086                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11087                                        + name + " already exists; skipping");
11088                            }
11089                        } else {
11090                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11091                                    + name + " that is not declared on system image; skipping");
11092                        }
11093                    }
11094
11095                    if ((scanFlags & SCAN_BOOTING) == 0) {
11096                        // If we are not booting, we need to update any applications
11097                        // that are clients of our shared library.  If we are booting,
11098                        // this will all be done once the scan is complete.
11099                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11100                    }
11101                }
11102            }
11103        }
11104
11105        if ((scanFlags & SCAN_BOOTING) != 0) {
11106            // No apps can run during boot scan, so they don't need to be frozen
11107        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11108            // Caller asked to not kill app, so it's probably not frozen
11109        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11110            // Caller asked us to ignore frozen check for some reason; they
11111            // probably didn't know the package name
11112        } else {
11113            // We're doing major surgery on this package, so it better be frozen
11114            // right now to keep it from launching
11115            checkPackageFrozen(pkgName);
11116        }
11117
11118        // Also need to kill any apps that are dependent on the library.
11119        if (clientLibPkgs != null) {
11120            for (int i=0; i<clientLibPkgs.size(); i++) {
11121                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11122                killApplication(clientPkg.applicationInfo.packageName,
11123                        clientPkg.applicationInfo.uid, "update lib");
11124            }
11125        }
11126
11127        // writer
11128        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11129
11130        synchronized (mPackages) {
11131            // We don't expect installation to fail beyond this point
11132
11133            // Add the new setting to mSettings
11134            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11135            // Add the new setting to mPackages
11136            mPackages.put(pkg.applicationInfo.packageName, pkg);
11137            // Make sure we don't accidentally delete its data.
11138            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11139            while (iter.hasNext()) {
11140                PackageCleanItem item = iter.next();
11141                if (pkgName.equals(item.packageName)) {
11142                    iter.remove();
11143                }
11144            }
11145
11146            // Add the package's KeySets to the global KeySetManagerService
11147            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11148            ksms.addScannedPackageLPw(pkg);
11149
11150            int N = pkg.providers.size();
11151            StringBuilder r = null;
11152            int i;
11153            for (i=0; i<N; i++) {
11154                PackageParser.Provider p = pkg.providers.get(i);
11155                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11156                        p.info.processName);
11157                mProviders.addProvider(p);
11158                p.syncable = p.info.isSyncable;
11159                if (p.info.authority != null) {
11160                    String names[] = p.info.authority.split(";");
11161                    p.info.authority = null;
11162                    for (int j = 0; j < names.length; j++) {
11163                        if (j == 1 && p.syncable) {
11164                            // We only want the first authority for a provider to possibly be
11165                            // syncable, so if we already added this provider using a different
11166                            // authority clear the syncable flag. We copy the provider before
11167                            // changing it because the mProviders object contains a reference
11168                            // to a provider that we don't want to change.
11169                            // Only do this for the second authority since the resulting provider
11170                            // object can be the same for all future authorities for this provider.
11171                            p = new PackageParser.Provider(p);
11172                            p.syncable = false;
11173                        }
11174                        if (!mProvidersByAuthority.containsKey(names[j])) {
11175                            mProvidersByAuthority.put(names[j], p);
11176                            if (p.info.authority == null) {
11177                                p.info.authority = names[j];
11178                            } else {
11179                                p.info.authority = p.info.authority + ";" + names[j];
11180                            }
11181                            if (DEBUG_PACKAGE_SCANNING) {
11182                                if (chatty)
11183                                    Log.d(TAG, "Registered content provider: " + names[j]
11184                                            + ", className = " + p.info.name + ", isSyncable = "
11185                                            + p.info.isSyncable);
11186                            }
11187                        } else {
11188                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11189                            Slog.w(TAG, "Skipping provider name " + names[j] +
11190                                    " (in package " + pkg.applicationInfo.packageName +
11191                                    "): name already used by "
11192                                    + ((other != null && other.getComponentName() != null)
11193                                            ? other.getComponentName().getPackageName() : "?"));
11194                        }
11195                    }
11196                }
11197                if (chatty) {
11198                    if (r == null) {
11199                        r = new StringBuilder(256);
11200                    } else {
11201                        r.append(' ');
11202                    }
11203                    r.append(p.info.name);
11204                }
11205            }
11206            if (r != null) {
11207                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11208            }
11209
11210            N = pkg.services.size();
11211            r = null;
11212            for (i=0; i<N; i++) {
11213                PackageParser.Service s = pkg.services.get(i);
11214                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11215                        s.info.processName);
11216                mServices.addService(s);
11217                if (chatty) {
11218                    if (r == null) {
11219                        r = new StringBuilder(256);
11220                    } else {
11221                        r.append(' ');
11222                    }
11223                    r.append(s.info.name);
11224                }
11225            }
11226            if (r != null) {
11227                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11228            }
11229
11230            N = pkg.receivers.size();
11231            r = null;
11232            for (i=0; i<N; i++) {
11233                PackageParser.Activity a = pkg.receivers.get(i);
11234                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11235                        a.info.processName);
11236                mReceivers.addActivity(a, "receiver");
11237                if (chatty) {
11238                    if (r == null) {
11239                        r = new StringBuilder(256);
11240                    } else {
11241                        r.append(' ');
11242                    }
11243                    r.append(a.info.name);
11244                }
11245            }
11246            if (r != null) {
11247                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11248            }
11249
11250            N = pkg.activities.size();
11251            r = null;
11252            for (i=0; i<N; i++) {
11253                PackageParser.Activity a = pkg.activities.get(i);
11254                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11255                        a.info.processName);
11256                mActivities.addActivity(a, "activity");
11257                if (chatty) {
11258                    if (r == null) {
11259                        r = new StringBuilder(256);
11260                    } else {
11261                        r.append(' ');
11262                    }
11263                    r.append(a.info.name);
11264                }
11265            }
11266            if (r != null) {
11267                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11268            }
11269
11270            N = pkg.permissionGroups.size();
11271            r = null;
11272            for (i=0; i<N; i++) {
11273                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11274                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11275                final String curPackageName = cur == null ? null : cur.info.packageName;
11276                // Dont allow ephemeral apps to define new permission groups.
11277                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11278                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11279                            + pg.info.packageName
11280                            + " ignored: instant apps cannot define new permission groups.");
11281                    continue;
11282                }
11283                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11284                if (cur == null || isPackageUpdate) {
11285                    mPermissionGroups.put(pg.info.name, pg);
11286                    if (chatty) {
11287                        if (r == null) {
11288                            r = new StringBuilder(256);
11289                        } else {
11290                            r.append(' ');
11291                        }
11292                        if (isPackageUpdate) {
11293                            r.append("UPD:");
11294                        }
11295                        r.append(pg.info.name);
11296                    }
11297                } else {
11298                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11299                            + pg.info.packageName + " ignored: original from "
11300                            + cur.info.packageName);
11301                    if (chatty) {
11302                        if (r == null) {
11303                            r = new StringBuilder(256);
11304                        } else {
11305                            r.append(' ');
11306                        }
11307                        r.append("DUP:");
11308                        r.append(pg.info.name);
11309                    }
11310                }
11311            }
11312            if (r != null) {
11313                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11314            }
11315
11316            N = pkg.permissions.size();
11317            r = null;
11318            for (i=0; i<N; i++) {
11319                PackageParser.Permission p = pkg.permissions.get(i);
11320
11321                // Dont allow ephemeral apps to define new permissions.
11322                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11323                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11324                            + p.info.packageName
11325                            + " ignored: instant apps cannot define new permissions.");
11326                    continue;
11327                }
11328
11329                // Assume by default that we did not install this permission into the system.
11330                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11331
11332                // Now that permission groups have a special meaning, we ignore permission
11333                // groups for legacy apps to prevent unexpected behavior. In particular,
11334                // permissions for one app being granted to someone just because they happen
11335                // to be in a group defined by another app (before this had no implications).
11336                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11337                    p.group = mPermissionGroups.get(p.info.group);
11338                    // Warn for a permission in an unknown group.
11339                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11340                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11341                                + p.info.packageName + " in an unknown group " + p.info.group);
11342                    }
11343                }
11344
11345                ArrayMap<String, BasePermission> permissionMap =
11346                        p.tree ? mSettings.mPermissionTrees
11347                                : mSettings.mPermissions;
11348                BasePermission bp = permissionMap.get(p.info.name);
11349
11350                // Allow system apps to redefine non-system permissions
11351                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11352                    final boolean currentOwnerIsSystem = (bp.perm != null
11353                            && isSystemApp(bp.perm.owner));
11354                    if (isSystemApp(p.owner)) {
11355                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11356                            // It's a built-in permission and no owner, take ownership now
11357                            bp.packageSetting = pkgSetting;
11358                            bp.perm = p;
11359                            bp.uid = pkg.applicationInfo.uid;
11360                            bp.sourcePackage = p.info.packageName;
11361                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11362                        } else if (!currentOwnerIsSystem) {
11363                            String msg = "New decl " + p.owner + " of permission  "
11364                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11365                            reportSettingsProblem(Log.WARN, msg);
11366                            bp = null;
11367                        }
11368                    }
11369                }
11370
11371                if (bp == null) {
11372                    bp = new BasePermission(p.info.name, p.info.packageName,
11373                            BasePermission.TYPE_NORMAL);
11374                    permissionMap.put(p.info.name, bp);
11375                }
11376
11377                if (bp.perm == null) {
11378                    if (bp.sourcePackage == null
11379                            || bp.sourcePackage.equals(p.info.packageName)) {
11380                        BasePermission tree = findPermissionTreeLP(p.info.name);
11381                        if (tree == null
11382                                || tree.sourcePackage.equals(p.info.packageName)) {
11383                            bp.packageSetting = pkgSetting;
11384                            bp.perm = p;
11385                            bp.uid = pkg.applicationInfo.uid;
11386                            bp.sourcePackage = p.info.packageName;
11387                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11388                            if (chatty) {
11389                                if (r == null) {
11390                                    r = new StringBuilder(256);
11391                                } else {
11392                                    r.append(' ');
11393                                }
11394                                r.append(p.info.name);
11395                            }
11396                        } else {
11397                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11398                                    + p.info.packageName + " ignored: base tree "
11399                                    + tree.name + " is from package "
11400                                    + tree.sourcePackage);
11401                        }
11402                    } else {
11403                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11404                                + p.info.packageName + " ignored: original from "
11405                                + bp.sourcePackage);
11406                    }
11407                } else if (chatty) {
11408                    if (r == null) {
11409                        r = new StringBuilder(256);
11410                    } else {
11411                        r.append(' ');
11412                    }
11413                    r.append("DUP:");
11414                    r.append(p.info.name);
11415                }
11416                if (bp.perm == p) {
11417                    bp.protectionLevel = p.info.protectionLevel;
11418                }
11419            }
11420
11421            if (r != null) {
11422                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11423            }
11424
11425            N = pkg.instrumentation.size();
11426            r = null;
11427            for (i=0; i<N; i++) {
11428                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11429                a.info.packageName = pkg.applicationInfo.packageName;
11430                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11431                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11432                a.info.splitNames = pkg.splitNames;
11433                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11434                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11435                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11436                a.info.dataDir = pkg.applicationInfo.dataDir;
11437                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11438                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11439                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11440                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11441                mInstrumentation.put(a.getComponentName(), a);
11442                if (chatty) {
11443                    if (r == null) {
11444                        r = new StringBuilder(256);
11445                    } else {
11446                        r.append(' ');
11447                    }
11448                    r.append(a.info.name);
11449                }
11450            }
11451            if (r != null) {
11452                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11453            }
11454
11455            if (pkg.protectedBroadcasts != null) {
11456                N = pkg.protectedBroadcasts.size();
11457                synchronized (mProtectedBroadcasts) {
11458                    for (i = 0; i < N; i++) {
11459                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11460                    }
11461                }
11462            }
11463        }
11464
11465        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11466    }
11467
11468    /**
11469     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11470     * is derived purely on the basis of the contents of {@code scanFile} and
11471     * {@code cpuAbiOverride}.
11472     *
11473     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11474     */
11475    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11476                                 String cpuAbiOverride, boolean extractLibs,
11477                                 File appLib32InstallDir)
11478            throws PackageManagerException {
11479        // Give ourselves some initial paths; we'll come back for another
11480        // pass once we've determined ABI below.
11481        setNativeLibraryPaths(pkg, appLib32InstallDir);
11482
11483        // We would never need to extract libs for forward-locked and external packages,
11484        // since the container service will do it for us. We shouldn't attempt to
11485        // extract libs from system app when it was not updated.
11486        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11487                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11488            extractLibs = false;
11489        }
11490
11491        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11492        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11493
11494        NativeLibraryHelper.Handle handle = null;
11495        try {
11496            handle = NativeLibraryHelper.Handle.create(pkg);
11497            // TODO(multiArch): This can be null for apps that didn't go through the
11498            // usual installation process. We can calculate it again, like we
11499            // do during install time.
11500            //
11501            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11502            // unnecessary.
11503            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11504
11505            // Null out the abis so that they can be recalculated.
11506            pkg.applicationInfo.primaryCpuAbi = null;
11507            pkg.applicationInfo.secondaryCpuAbi = null;
11508            if (isMultiArch(pkg.applicationInfo)) {
11509                // Warn if we've set an abiOverride for multi-lib packages..
11510                // By definition, we need to copy both 32 and 64 bit libraries for
11511                // such packages.
11512                if (pkg.cpuAbiOverride != null
11513                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11514                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11515                }
11516
11517                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11518                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11519                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11520                    if (extractLibs) {
11521                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11522                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11523                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11524                                useIsaSpecificSubdirs);
11525                    } else {
11526                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11527                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11528                    }
11529                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11530                }
11531
11532                // Shared library native code should be in the APK zip aligned
11533                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11534                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11535                            "Shared library native lib extraction not supported");
11536                }
11537
11538                maybeThrowExceptionForMultiArchCopy(
11539                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11540
11541                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11542                    if (extractLibs) {
11543                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11544                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11545                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11546                                useIsaSpecificSubdirs);
11547                    } else {
11548                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11549                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11550                    }
11551                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11552                }
11553
11554                maybeThrowExceptionForMultiArchCopy(
11555                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11556
11557                if (abi64 >= 0) {
11558                    // Shared library native libs should be in the APK zip aligned
11559                    if (extractLibs && pkg.isLibrary()) {
11560                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11561                                "Shared library native lib extraction not supported");
11562                    }
11563                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11564                }
11565
11566                if (abi32 >= 0) {
11567                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11568                    if (abi64 >= 0) {
11569                        if (pkg.use32bitAbi) {
11570                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11571                            pkg.applicationInfo.primaryCpuAbi = abi;
11572                        } else {
11573                            pkg.applicationInfo.secondaryCpuAbi = abi;
11574                        }
11575                    } else {
11576                        pkg.applicationInfo.primaryCpuAbi = abi;
11577                    }
11578                }
11579            } else {
11580                String[] abiList = (cpuAbiOverride != null) ?
11581                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11582
11583                // Enable gross and lame hacks for apps that are built with old
11584                // SDK tools. We must scan their APKs for renderscript bitcode and
11585                // not launch them if it's present. Don't bother checking on devices
11586                // that don't have 64 bit support.
11587                boolean needsRenderScriptOverride = false;
11588                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11589                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11590                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11591                    needsRenderScriptOverride = true;
11592                }
11593
11594                final int copyRet;
11595                if (extractLibs) {
11596                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11597                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11598                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11599                } else {
11600                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11601                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11602                }
11603                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11604
11605                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11606                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11607                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11608                }
11609
11610                if (copyRet >= 0) {
11611                    // Shared libraries that have native libs must be multi-architecture
11612                    if (pkg.isLibrary()) {
11613                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11614                                "Shared library with native libs must be multiarch");
11615                    }
11616                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11617                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11618                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11619                } else if (needsRenderScriptOverride) {
11620                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11621                }
11622            }
11623        } catch (IOException ioe) {
11624            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11625        } finally {
11626            IoUtils.closeQuietly(handle);
11627        }
11628
11629        // Now that we've calculated the ABIs and determined if it's an internal app,
11630        // we will go ahead and populate the nativeLibraryPath.
11631        setNativeLibraryPaths(pkg, appLib32InstallDir);
11632    }
11633
11634    /**
11635     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11636     * i.e, so that all packages can be run inside a single process if required.
11637     *
11638     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11639     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11640     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11641     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11642     * updating a package that belongs to a shared user.
11643     *
11644     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11645     * adds unnecessary complexity.
11646     */
11647    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11648            PackageParser.Package scannedPackage) {
11649        String requiredInstructionSet = null;
11650        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11651            requiredInstructionSet = VMRuntime.getInstructionSet(
11652                     scannedPackage.applicationInfo.primaryCpuAbi);
11653        }
11654
11655        PackageSetting requirer = null;
11656        for (PackageSetting ps : packagesForUser) {
11657            // If packagesForUser contains scannedPackage, we skip it. This will happen
11658            // when scannedPackage is an update of an existing package. Without this check,
11659            // we will never be able to change the ABI of any package belonging to a shared
11660            // user, even if it's compatible with other packages.
11661            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11662                if (ps.primaryCpuAbiString == null) {
11663                    continue;
11664                }
11665
11666                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11667                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11668                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11669                    // this but there's not much we can do.
11670                    String errorMessage = "Instruction set mismatch, "
11671                            + ((requirer == null) ? "[caller]" : requirer)
11672                            + " requires " + requiredInstructionSet + " whereas " + ps
11673                            + " requires " + instructionSet;
11674                    Slog.w(TAG, errorMessage);
11675                }
11676
11677                if (requiredInstructionSet == null) {
11678                    requiredInstructionSet = instructionSet;
11679                    requirer = ps;
11680                }
11681            }
11682        }
11683
11684        if (requiredInstructionSet != null) {
11685            String adjustedAbi;
11686            if (requirer != null) {
11687                // requirer != null implies that either scannedPackage was null or that scannedPackage
11688                // did not require an ABI, in which case we have to adjust scannedPackage to match
11689                // the ABI of the set (which is the same as requirer's ABI)
11690                adjustedAbi = requirer.primaryCpuAbiString;
11691                if (scannedPackage != null) {
11692                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11693                }
11694            } else {
11695                // requirer == null implies that we're updating all ABIs in the set to
11696                // match scannedPackage.
11697                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11698            }
11699
11700            for (PackageSetting ps : packagesForUser) {
11701                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11702                    if (ps.primaryCpuAbiString != null) {
11703                        continue;
11704                    }
11705
11706                    ps.primaryCpuAbiString = adjustedAbi;
11707                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11708                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11709                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11710                        if (DEBUG_ABI_SELECTION) {
11711                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11712                                    + " (requirer="
11713                                    + (requirer != null ? requirer.pkg : "null")
11714                                    + ", scannedPackage="
11715                                    + (scannedPackage != null ? scannedPackage : "null")
11716                                    + ")");
11717                        }
11718                        try {
11719                            mInstaller.rmdex(ps.codePathString,
11720                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11721                        } catch (InstallerException ignored) {
11722                        }
11723                    }
11724                }
11725            }
11726        }
11727    }
11728
11729    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11730        synchronized (mPackages) {
11731            mResolverReplaced = true;
11732            // Set up information for custom user intent resolution activity.
11733            mResolveActivity.applicationInfo = pkg.applicationInfo;
11734            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11735            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11736            mResolveActivity.processName = pkg.applicationInfo.packageName;
11737            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11738            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11739                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11740            mResolveActivity.theme = 0;
11741            mResolveActivity.exported = true;
11742            mResolveActivity.enabled = true;
11743            mResolveInfo.activityInfo = mResolveActivity;
11744            mResolveInfo.priority = 0;
11745            mResolveInfo.preferredOrder = 0;
11746            mResolveInfo.match = 0;
11747            mResolveComponentName = mCustomResolverComponentName;
11748            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11749                    mResolveComponentName);
11750        }
11751    }
11752
11753    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11754        if (installerActivity == null) {
11755            if (DEBUG_EPHEMERAL) {
11756                Slog.d(TAG, "Clear ephemeral installer activity");
11757            }
11758            mInstantAppInstallerActivity = null;
11759            return;
11760        }
11761
11762        if (DEBUG_EPHEMERAL) {
11763            Slog.d(TAG, "Set ephemeral installer activity: "
11764                    + installerActivity.getComponentName());
11765        }
11766        // Set up information for ephemeral installer activity
11767        mInstantAppInstallerActivity = installerActivity;
11768        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11769                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11770        mInstantAppInstallerActivity.exported = true;
11771        mInstantAppInstallerActivity.enabled = true;
11772        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11773        mInstantAppInstallerInfo.priority = 0;
11774        mInstantAppInstallerInfo.preferredOrder = 1;
11775        mInstantAppInstallerInfo.isDefault = true;
11776        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11777                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11778    }
11779
11780    private static String calculateBundledApkRoot(final String codePathString) {
11781        final File codePath = new File(codePathString);
11782        final File codeRoot;
11783        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11784            codeRoot = Environment.getRootDirectory();
11785        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11786            codeRoot = Environment.getOemDirectory();
11787        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11788            codeRoot = Environment.getVendorDirectory();
11789        } else {
11790            // Unrecognized code path; take its top real segment as the apk root:
11791            // e.g. /something/app/blah.apk => /something
11792            try {
11793                File f = codePath.getCanonicalFile();
11794                File parent = f.getParentFile();    // non-null because codePath is a file
11795                File tmp;
11796                while ((tmp = parent.getParentFile()) != null) {
11797                    f = parent;
11798                    parent = tmp;
11799                }
11800                codeRoot = f;
11801                Slog.w(TAG, "Unrecognized code path "
11802                        + codePath + " - using " + codeRoot);
11803            } catch (IOException e) {
11804                // Can't canonicalize the code path -- shenanigans?
11805                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11806                return Environment.getRootDirectory().getPath();
11807            }
11808        }
11809        return codeRoot.getPath();
11810    }
11811
11812    /**
11813     * Derive and set the location of native libraries for the given package,
11814     * which varies depending on where and how the package was installed.
11815     */
11816    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11817        final ApplicationInfo info = pkg.applicationInfo;
11818        final String codePath = pkg.codePath;
11819        final File codeFile = new File(codePath);
11820        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11821        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11822
11823        info.nativeLibraryRootDir = null;
11824        info.nativeLibraryRootRequiresIsa = false;
11825        info.nativeLibraryDir = null;
11826        info.secondaryNativeLibraryDir = null;
11827
11828        if (isApkFile(codeFile)) {
11829            // Monolithic install
11830            if (bundledApp) {
11831                // If "/system/lib64/apkname" exists, assume that is the per-package
11832                // native library directory to use; otherwise use "/system/lib/apkname".
11833                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11834                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11835                        getPrimaryInstructionSet(info));
11836
11837                // This is a bundled system app so choose the path based on the ABI.
11838                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11839                // is just the default path.
11840                final String apkName = deriveCodePathName(codePath);
11841                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11842                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11843                        apkName).getAbsolutePath();
11844
11845                if (info.secondaryCpuAbi != null) {
11846                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11847                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11848                            secondaryLibDir, apkName).getAbsolutePath();
11849                }
11850            } else if (asecApp) {
11851                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11852                        .getAbsolutePath();
11853            } else {
11854                final String apkName = deriveCodePathName(codePath);
11855                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11856                        .getAbsolutePath();
11857            }
11858
11859            info.nativeLibraryRootRequiresIsa = false;
11860            info.nativeLibraryDir = info.nativeLibraryRootDir;
11861        } else {
11862            // Cluster install
11863            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11864            info.nativeLibraryRootRequiresIsa = true;
11865
11866            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11867                    getPrimaryInstructionSet(info)).getAbsolutePath();
11868
11869            if (info.secondaryCpuAbi != null) {
11870                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11871                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11872            }
11873        }
11874    }
11875
11876    /**
11877     * Calculate the abis and roots for a bundled app. These can uniquely
11878     * be determined from the contents of the system partition, i.e whether
11879     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11880     * of this information, and instead assume that the system was built
11881     * sensibly.
11882     */
11883    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11884                                           PackageSetting pkgSetting) {
11885        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11886
11887        // If "/system/lib64/apkname" exists, assume that is the per-package
11888        // native library directory to use; otherwise use "/system/lib/apkname".
11889        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11890        setBundledAppAbi(pkg, apkRoot, apkName);
11891        // pkgSetting might be null during rescan following uninstall of updates
11892        // to a bundled app, so accommodate that possibility.  The settings in
11893        // that case will be established later from the parsed package.
11894        //
11895        // If the settings aren't null, sync them up with what we've just derived.
11896        // note that apkRoot isn't stored in the package settings.
11897        if (pkgSetting != null) {
11898            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11899            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11900        }
11901    }
11902
11903    /**
11904     * Deduces the ABI of a bundled app and sets the relevant fields on the
11905     * parsed pkg object.
11906     *
11907     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11908     *        under which system libraries are installed.
11909     * @param apkName the name of the installed package.
11910     */
11911    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11912        final File codeFile = new File(pkg.codePath);
11913
11914        final boolean has64BitLibs;
11915        final boolean has32BitLibs;
11916        if (isApkFile(codeFile)) {
11917            // Monolithic install
11918            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11919            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11920        } else {
11921            // Cluster install
11922            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11923            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11924                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11925                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11926                has64BitLibs = (new File(rootDir, isa)).exists();
11927            } else {
11928                has64BitLibs = false;
11929            }
11930            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11931                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11932                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11933                has32BitLibs = (new File(rootDir, isa)).exists();
11934            } else {
11935                has32BitLibs = false;
11936            }
11937        }
11938
11939        if (has64BitLibs && !has32BitLibs) {
11940            // The package has 64 bit libs, but not 32 bit libs. Its primary
11941            // ABI should be 64 bit. We can safely assume here that the bundled
11942            // native libraries correspond to the most preferred ABI in the list.
11943
11944            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11945            pkg.applicationInfo.secondaryCpuAbi = null;
11946        } else if (has32BitLibs && !has64BitLibs) {
11947            // The package has 32 bit libs but not 64 bit libs. Its primary
11948            // ABI should be 32 bit.
11949
11950            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11951            pkg.applicationInfo.secondaryCpuAbi = null;
11952        } else if (has32BitLibs && has64BitLibs) {
11953            // The application has both 64 and 32 bit bundled libraries. We check
11954            // here that the app declares multiArch support, and warn if it doesn't.
11955            //
11956            // We will be lenient here and record both ABIs. The primary will be the
11957            // ABI that's higher on the list, i.e, a device that's configured to prefer
11958            // 64 bit apps will see a 64 bit primary ABI,
11959
11960            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11961                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11962            }
11963
11964            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11965                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11966                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11967            } else {
11968                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11969                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11970            }
11971        } else {
11972            pkg.applicationInfo.primaryCpuAbi = null;
11973            pkg.applicationInfo.secondaryCpuAbi = null;
11974        }
11975    }
11976
11977    private void killApplication(String pkgName, int appId, String reason) {
11978        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11979    }
11980
11981    private void killApplication(String pkgName, int appId, int userId, String reason) {
11982        // Request the ActivityManager to kill the process(only for existing packages)
11983        // so that we do not end up in a confused state while the user is still using the older
11984        // version of the application while the new one gets installed.
11985        final long token = Binder.clearCallingIdentity();
11986        try {
11987            IActivityManager am = ActivityManager.getService();
11988            if (am != null) {
11989                try {
11990                    am.killApplication(pkgName, appId, userId, reason);
11991                } catch (RemoteException e) {
11992                }
11993            }
11994        } finally {
11995            Binder.restoreCallingIdentity(token);
11996        }
11997    }
11998
11999    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12000        // Remove the parent package setting
12001        PackageSetting ps = (PackageSetting) pkg.mExtras;
12002        if (ps != null) {
12003            removePackageLI(ps, chatty);
12004        }
12005        // Remove the child package setting
12006        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12007        for (int i = 0; i < childCount; i++) {
12008            PackageParser.Package childPkg = pkg.childPackages.get(i);
12009            ps = (PackageSetting) childPkg.mExtras;
12010            if (ps != null) {
12011                removePackageLI(ps, chatty);
12012            }
12013        }
12014    }
12015
12016    void removePackageLI(PackageSetting ps, boolean chatty) {
12017        if (DEBUG_INSTALL) {
12018            if (chatty)
12019                Log.d(TAG, "Removing package " + ps.name);
12020        }
12021
12022        // writer
12023        synchronized (mPackages) {
12024            mPackages.remove(ps.name);
12025            final PackageParser.Package pkg = ps.pkg;
12026            if (pkg != null) {
12027                cleanPackageDataStructuresLILPw(pkg, chatty);
12028            }
12029        }
12030    }
12031
12032    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12033        if (DEBUG_INSTALL) {
12034            if (chatty)
12035                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12036        }
12037
12038        // writer
12039        synchronized (mPackages) {
12040            // Remove the parent package
12041            mPackages.remove(pkg.applicationInfo.packageName);
12042            cleanPackageDataStructuresLILPw(pkg, chatty);
12043
12044            // Remove the child packages
12045            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12046            for (int i = 0; i < childCount; i++) {
12047                PackageParser.Package childPkg = pkg.childPackages.get(i);
12048                mPackages.remove(childPkg.applicationInfo.packageName);
12049                cleanPackageDataStructuresLILPw(childPkg, chatty);
12050            }
12051        }
12052    }
12053
12054    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12055        int N = pkg.providers.size();
12056        StringBuilder r = null;
12057        int i;
12058        for (i=0; i<N; i++) {
12059            PackageParser.Provider p = pkg.providers.get(i);
12060            mProviders.removeProvider(p);
12061            if (p.info.authority == null) {
12062
12063                /* There was another ContentProvider with this authority when
12064                 * this app was installed so this authority is null,
12065                 * Ignore it as we don't have to unregister the provider.
12066                 */
12067                continue;
12068            }
12069            String names[] = p.info.authority.split(";");
12070            for (int j = 0; j < names.length; j++) {
12071                if (mProvidersByAuthority.get(names[j]) == p) {
12072                    mProvidersByAuthority.remove(names[j]);
12073                    if (DEBUG_REMOVE) {
12074                        if (chatty)
12075                            Log.d(TAG, "Unregistered content provider: " + names[j]
12076                                    + ", className = " + p.info.name + ", isSyncable = "
12077                                    + p.info.isSyncable);
12078                    }
12079                }
12080            }
12081            if (DEBUG_REMOVE && chatty) {
12082                if (r == null) {
12083                    r = new StringBuilder(256);
12084                } else {
12085                    r.append(' ');
12086                }
12087                r.append(p.info.name);
12088            }
12089        }
12090        if (r != null) {
12091            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12092        }
12093
12094        N = pkg.services.size();
12095        r = null;
12096        for (i=0; i<N; i++) {
12097            PackageParser.Service s = pkg.services.get(i);
12098            mServices.removeService(s);
12099            if (chatty) {
12100                if (r == null) {
12101                    r = new StringBuilder(256);
12102                } else {
12103                    r.append(' ');
12104                }
12105                r.append(s.info.name);
12106            }
12107        }
12108        if (r != null) {
12109            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12110        }
12111
12112        N = pkg.receivers.size();
12113        r = null;
12114        for (i=0; i<N; i++) {
12115            PackageParser.Activity a = pkg.receivers.get(i);
12116            mReceivers.removeActivity(a, "receiver");
12117            if (DEBUG_REMOVE && chatty) {
12118                if (r == null) {
12119                    r = new StringBuilder(256);
12120                } else {
12121                    r.append(' ');
12122                }
12123                r.append(a.info.name);
12124            }
12125        }
12126        if (r != null) {
12127            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12128        }
12129
12130        N = pkg.activities.size();
12131        r = null;
12132        for (i=0; i<N; i++) {
12133            PackageParser.Activity a = pkg.activities.get(i);
12134            mActivities.removeActivity(a, "activity");
12135            if (DEBUG_REMOVE && chatty) {
12136                if (r == null) {
12137                    r = new StringBuilder(256);
12138                } else {
12139                    r.append(' ');
12140                }
12141                r.append(a.info.name);
12142            }
12143        }
12144        if (r != null) {
12145            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12146        }
12147
12148        N = pkg.permissions.size();
12149        r = null;
12150        for (i=0; i<N; i++) {
12151            PackageParser.Permission p = pkg.permissions.get(i);
12152            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12153            if (bp == null) {
12154                bp = mSettings.mPermissionTrees.get(p.info.name);
12155            }
12156            if (bp != null && bp.perm == p) {
12157                bp.perm = null;
12158                if (DEBUG_REMOVE && chatty) {
12159                    if (r == null) {
12160                        r = new StringBuilder(256);
12161                    } else {
12162                        r.append(' ');
12163                    }
12164                    r.append(p.info.name);
12165                }
12166            }
12167            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12168                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12169                if (appOpPkgs != null) {
12170                    appOpPkgs.remove(pkg.packageName);
12171                }
12172            }
12173        }
12174        if (r != null) {
12175            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12176        }
12177
12178        N = pkg.requestedPermissions.size();
12179        r = null;
12180        for (i=0; i<N; i++) {
12181            String perm = pkg.requestedPermissions.get(i);
12182            BasePermission bp = mSettings.mPermissions.get(perm);
12183            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12184                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12185                if (appOpPkgs != null) {
12186                    appOpPkgs.remove(pkg.packageName);
12187                    if (appOpPkgs.isEmpty()) {
12188                        mAppOpPermissionPackages.remove(perm);
12189                    }
12190                }
12191            }
12192        }
12193        if (r != null) {
12194            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12195        }
12196
12197        N = pkg.instrumentation.size();
12198        r = null;
12199        for (i=0; i<N; i++) {
12200            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12201            mInstrumentation.remove(a.getComponentName());
12202            if (DEBUG_REMOVE && chatty) {
12203                if (r == null) {
12204                    r = new StringBuilder(256);
12205                } else {
12206                    r.append(' ');
12207                }
12208                r.append(a.info.name);
12209            }
12210        }
12211        if (r != null) {
12212            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12213        }
12214
12215        r = null;
12216        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12217            // Only system apps can hold shared libraries.
12218            if (pkg.libraryNames != null) {
12219                for (i = 0; i < pkg.libraryNames.size(); i++) {
12220                    String name = pkg.libraryNames.get(i);
12221                    if (removeSharedLibraryLPw(name, 0)) {
12222                        if (DEBUG_REMOVE && chatty) {
12223                            if (r == null) {
12224                                r = new StringBuilder(256);
12225                            } else {
12226                                r.append(' ');
12227                            }
12228                            r.append(name);
12229                        }
12230                    }
12231                }
12232            }
12233        }
12234
12235        r = null;
12236
12237        // Any package can hold static shared libraries.
12238        if (pkg.staticSharedLibName != null) {
12239            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12240                if (DEBUG_REMOVE && chatty) {
12241                    if (r == null) {
12242                        r = new StringBuilder(256);
12243                    } else {
12244                        r.append(' ');
12245                    }
12246                    r.append(pkg.staticSharedLibName);
12247                }
12248            }
12249        }
12250
12251        if (r != null) {
12252            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12253        }
12254    }
12255
12256    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12257        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12258            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12259                return true;
12260            }
12261        }
12262        return false;
12263    }
12264
12265    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12266    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12267    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12268
12269    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12270        // Update the parent permissions
12271        updatePermissionsLPw(pkg.packageName, pkg, flags);
12272        // Update the child permissions
12273        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12274        for (int i = 0; i < childCount; i++) {
12275            PackageParser.Package childPkg = pkg.childPackages.get(i);
12276            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12277        }
12278    }
12279
12280    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12281            int flags) {
12282        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12283        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12284    }
12285
12286    private void updatePermissionsLPw(String changingPkg,
12287            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12288        // Make sure there are no dangling permission trees.
12289        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12290        while (it.hasNext()) {
12291            final BasePermission bp = it.next();
12292            if (bp.packageSetting == null) {
12293                // We may not yet have parsed the package, so just see if
12294                // we still know about its settings.
12295                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12296            }
12297            if (bp.packageSetting == null) {
12298                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12299                        + " from package " + bp.sourcePackage);
12300                it.remove();
12301            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12302                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12303                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12304                            + " from package " + bp.sourcePackage);
12305                    flags |= UPDATE_PERMISSIONS_ALL;
12306                    it.remove();
12307                }
12308            }
12309        }
12310
12311        // Make sure all dynamic permissions have been assigned to a package,
12312        // and make sure there are no dangling permissions.
12313        it = mSettings.mPermissions.values().iterator();
12314        while (it.hasNext()) {
12315            final BasePermission bp = it.next();
12316            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12317                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12318                        + bp.name + " pkg=" + bp.sourcePackage
12319                        + " info=" + bp.pendingInfo);
12320                if (bp.packageSetting == null && bp.pendingInfo != null) {
12321                    final BasePermission tree = findPermissionTreeLP(bp.name);
12322                    if (tree != null && tree.perm != null) {
12323                        bp.packageSetting = tree.packageSetting;
12324                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12325                                new PermissionInfo(bp.pendingInfo));
12326                        bp.perm.info.packageName = tree.perm.info.packageName;
12327                        bp.perm.info.name = bp.name;
12328                        bp.uid = tree.uid;
12329                    }
12330                }
12331            }
12332            if (bp.packageSetting == null) {
12333                // We may not yet have parsed the package, so just see if
12334                // we still know about its settings.
12335                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12336            }
12337            if (bp.packageSetting == null) {
12338                Slog.w(TAG, "Removing dangling permission: " + bp.name
12339                        + " from package " + bp.sourcePackage);
12340                it.remove();
12341            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12342                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12343                    Slog.i(TAG, "Removing old permission: " + bp.name
12344                            + " from package " + bp.sourcePackage);
12345                    flags |= UPDATE_PERMISSIONS_ALL;
12346                    it.remove();
12347                }
12348            }
12349        }
12350
12351        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12352        // Now update the permissions for all packages, in particular
12353        // replace the granted permissions of the system packages.
12354        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12355            for (PackageParser.Package pkg : mPackages.values()) {
12356                if (pkg != pkgInfo) {
12357                    // Only replace for packages on requested volume
12358                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12359                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12360                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12361                    grantPermissionsLPw(pkg, replace, changingPkg);
12362                }
12363            }
12364        }
12365
12366        if (pkgInfo != null) {
12367            // Only replace for packages on requested volume
12368            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12369            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12370                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12371            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12372        }
12373        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12374    }
12375
12376    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12377            String packageOfInterest) {
12378        // IMPORTANT: There are two types of permissions: install and runtime.
12379        // Install time permissions are granted when the app is installed to
12380        // all device users and users added in the future. Runtime permissions
12381        // are granted at runtime explicitly to specific users. Normal and signature
12382        // protected permissions are install time permissions. Dangerous permissions
12383        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12384        // otherwise they are runtime permissions. This function does not manage
12385        // runtime permissions except for the case an app targeting Lollipop MR1
12386        // being upgraded to target a newer SDK, in which case dangerous permissions
12387        // are transformed from install time to runtime ones.
12388
12389        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12390        if (ps == null) {
12391            return;
12392        }
12393
12394        PermissionsState permissionsState = ps.getPermissionsState();
12395        PermissionsState origPermissions = permissionsState;
12396
12397        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12398
12399        boolean runtimePermissionsRevoked = false;
12400        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12401
12402        boolean changedInstallPermission = false;
12403
12404        if (replace) {
12405            ps.installPermissionsFixed = false;
12406            if (!ps.isSharedUser()) {
12407                origPermissions = new PermissionsState(permissionsState);
12408                permissionsState.reset();
12409            } else {
12410                // We need to know only about runtime permission changes since the
12411                // calling code always writes the install permissions state but
12412                // the runtime ones are written only if changed. The only cases of
12413                // changed runtime permissions here are promotion of an install to
12414                // runtime and revocation of a runtime from a shared user.
12415                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12416                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12417                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12418                    runtimePermissionsRevoked = true;
12419                }
12420            }
12421        }
12422
12423        permissionsState.setGlobalGids(mGlobalGids);
12424
12425        final int N = pkg.requestedPermissions.size();
12426        for (int i=0; i<N; i++) {
12427            final String name = pkg.requestedPermissions.get(i);
12428            final BasePermission bp = mSettings.mPermissions.get(name);
12429            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12430                    >= Build.VERSION_CODES.M;
12431
12432            if (DEBUG_INSTALL) {
12433                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12434            }
12435
12436            if (bp == null || bp.packageSetting == null) {
12437                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12438                    if (DEBUG_PERMISSIONS) {
12439                        Slog.i(TAG, "Unknown permission " + name
12440                                + " in package " + pkg.packageName);
12441                    }
12442                }
12443                continue;
12444            }
12445
12446
12447            // Limit ephemeral apps to ephemeral allowed permissions.
12448            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12449                if (DEBUG_PERMISSIONS) {
12450                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12451                            + pkg.packageName);
12452                }
12453                continue;
12454            }
12455
12456            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12457                if (DEBUG_PERMISSIONS) {
12458                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12459                            + pkg.packageName);
12460                }
12461                continue;
12462            }
12463
12464            final String perm = bp.name;
12465            boolean allowedSig = false;
12466            int grant = GRANT_DENIED;
12467
12468            // Keep track of app op permissions.
12469            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12470                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12471                if (pkgs == null) {
12472                    pkgs = new ArraySet<>();
12473                    mAppOpPermissionPackages.put(bp.name, pkgs);
12474                }
12475                pkgs.add(pkg.packageName);
12476            }
12477
12478            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12479            switch (level) {
12480                case PermissionInfo.PROTECTION_NORMAL: {
12481                    // For all apps normal permissions are install time ones.
12482                    grant = GRANT_INSTALL;
12483                } break;
12484
12485                case PermissionInfo.PROTECTION_DANGEROUS: {
12486                    // If a permission review is required for legacy apps we represent
12487                    // their permissions as always granted runtime ones since we need
12488                    // to keep the review required permission flag per user while an
12489                    // install permission's state is shared across all users.
12490                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12491                        // For legacy apps dangerous permissions are install time ones.
12492                        grant = GRANT_INSTALL;
12493                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12494                        // For legacy apps that became modern, install becomes runtime.
12495                        grant = GRANT_UPGRADE;
12496                    } else if (mPromoteSystemApps
12497                            && isSystemApp(ps)
12498                            && mExistingSystemPackages.contains(ps.name)) {
12499                        // For legacy system apps, install becomes runtime.
12500                        // We cannot check hasInstallPermission() for system apps since those
12501                        // permissions were granted implicitly and not persisted pre-M.
12502                        grant = GRANT_UPGRADE;
12503                    } else {
12504                        // For modern apps keep runtime permissions unchanged.
12505                        grant = GRANT_RUNTIME;
12506                    }
12507                } break;
12508
12509                case PermissionInfo.PROTECTION_SIGNATURE: {
12510                    // For all apps signature permissions are install time ones.
12511                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12512                    if (allowedSig) {
12513                        grant = GRANT_INSTALL;
12514                    }
12515                } break;
12516            }
12517
12518            if (DEBUG_PERMISSIONS) {
12519                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12520            }
12521
12522            if (grant != GRANT_DENIED) {
12523                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12524                    // If this is an existing, non-system package, then
12525                    // we can't add any new permissions to it.
12526                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12527                        // Except...  if this is a permission that was added
12528                        // to the platform (note: need to only do this when
12529                        // updating the platform).
12530                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12531                            grant = GRANT_DENIED;
12532                        }
12533                    }
12534                }
12535
12536                switch (grant) {
12537                    case GRANT_INSTALL: {
12538                        // Revoke this as runtime permission to handle the case of
12539                        // a runtime permission being downgraded to an install one.
12540                        // Also in permission review mode we keep dangerous permissions
12541                        // for legacy apps
12542                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12543                            if (origPermissions.getRuntimePermissionState(
12544                                    bp.name, userId) != null) {
12545                                // Revoke the runtime permission and clear the flags.
12546                                origPermissions.revokeRuntimePermission(bp, userId);
12547                                origPermissions.updatePermissionFlags(bp, userId,
12548                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12549                                // If we revoked a permission permission, we have to write.
12550                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12551                                        changedRuntimePermissionUserIds, userId);
12552                            }
12553                        }
12554                        // Grant an install permission.
12555                        if (permissionsState.grantInstallPermission(bp) !=
12556                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12557                            changedInstallPermission = true;
12558                        }
12559                    } break;
12560
12561                    case GRANT_RUNTIME: {
12562                        // Grant previously granted runtime permissions.
12563                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12564                            PermissionState permissionState = origPermissions
12565                                    .getRuntimePermissionState(bp.name, userId);
12566                            int flags = permissionState != null
12567                                    ? permissionState.getFlags() : 0;
12568                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12569                                // Don't propagate the permission in a permission review mode if
12570                                // the former was revoked, i.e. marked to not propagate on upgrade.
12571                                // Note that in a permission review mode install permissions are
12572                                // represented as constantly granted runtime ones since we need to
12573                                // keep a per user state associated with the permission. Also the
12574                                // revoke on upgrade flag is no longer applicable and is reset.
12575                                final boolean revokeOnUpgrade = (flags & PackageManager
12576                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12577                                if (revokeOnUpgrade) {
12578                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12579                                    // Since we changed the flags, we have to write.
12580                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12581                                            changedRuntimePermissionUserIds, userId);
12582                                }
12583                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12584                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12585                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12586                                        // If we cannot put the permission as it was,
12587                                        // we have to write.
12588                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12589                                                changedRuntimePermissionUserIds, userId);
12590                                    }
12591                                }
12592
12593                                // If the app supports runtime permissions no need for a review.
12594                                if (mPermissionReviewRequired
12595                                        && appSupportsRuntimePermissions
12596                                        && (flags & PackageManager
12597                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12598                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12599                                    // Since we changed the flags, we have to write.
12600                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12601                                            changedRuntimePermissionUserIds, userId);
12602                                }
12603                            } else if (mPermissionReviewRequired
12604                                    && !appSupportsRuntimePermissions) {
12605                                // For legacy apps that need a permission review, every new
12606                                // runtime permission is granted but it is pending a review.
12607                                // We also need to review only platform defined runtime
12608                                // permissions as these are the only ones the platform knows
12609                                // how to disable the API to simulate revocation as legacy
12610                                // apps don't expect to run with revoked permissions.
12611                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12612                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12613                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12614                                        // We changed the flags, hence have to write.
12615                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12616                                                changedRuntimePermissionUserIds, userId);
12617                                    }
12618                                }
12619                                if (permissionsState.grantRuntimePermission(bp, userId)
12620                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12621                                    // We changed the permission, hence have to write.
12622                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12623                                            changedRuntimePermissionUserIds, userId);
12624                                }
12625                            }
12626                            // Propagate the permission flags.
12627                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12628                        }
12629                    } break;
12630
12631                    case GRANT_UPGRADE: {
12632                        // Grant runtime permissions for a previously held install permission.
12633                        PermissionState permissionState = origPermissions
12634                                .getInstallPermissionState(bp.name);
12635                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12636
12637                        if (origPermissions.revokeInstallPermission(bp)
12638                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12639                            // We will be transferring the permission flags, so clear them.
12640                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12641                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12642                            changedInstallPermission = true;
12643                        }
12644
12645                        // If the permission is not to be promoted to runtime we ignore it and
12646                        // also its other flags as they are not applicable to install permissions.
12647                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12648                            for (int userId : currentUserIds) {
12649                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12650                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12651                                    // Transfer the permission flags.
12652                                    permissionsState.updatePermissionFlags(bp, userId,
12653                                            flags, flags);
12654                                    // If we granted the permission, we have to write.
12655                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12656                                            changedRuntimePermissionUserIds, userId);
12657                                }
12658                            }
12659                        }
12660                    } break;
12661
12662                    default: {
12663                        if (packageOfInterest == null
12664                                || packageOfInterest.equals(pkg.packageName)) {
12665                            if (DEBUG_PERMISSIONS) {
12666                                Slog.i(TAG, "Not granting permission " + perm
12667                                        + " to package " + pkg.packageName
12668                                        + " because it was previously installed without");
12669                            }
12670                        }
12671                    } break;
12672                }
12673            } else {
12674                if (permissionsState.revokeInstallPermission(bp) !=
12675                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12676                    // Also drop the permission flags.
12677                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12678                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12679                    changedInstallPermission = true;
12680                    Slog.i(TAG, "Un-granting permission " + perm
12681                            + " from package " + pkg.packageName
12682                            + " (protectionLevel=" + bp.protectionLevel
12683                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12684                            + ")");
12685                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12686                    // Don't print warning for app op permissions, since it is fine for them
12687                    // not to be granted, there is a UI for the user to decide.
12688                    if (DEBUG_PERMISSIONS
12689                            && (packageOfInterest == null
12690                                    || packageOfInterest.equals(pkg.packageName))) {
12691                        Slog.i(TAG, "Not granting permission " + perm
12692                                + " to package " + pkg.packageName
12693                                + " (protectionLevel=" + bp.protectionLevel
12694                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12695                                + ")");
12696                    }
12697                }
12698            }
12699        }
12700
12701        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12702                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12703            // This is the first that we have heard about this package, so the
12704            // permissions we have now selected are fixed until explicitly
12705            // changed.
12706            ps.installPermissionsFixed = true;
12707        }
12708
12709        // Persist the runtime permissions state for users with changes. If permissions
12710        // were revoked because no app in the shared user declares them we have to
12711        // write synchronously to avoid losing runtime permissions state.
12712        for (int userId : changedRuntimePermissionUserIds) {
12713            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12714        }
12715    }
12716
12717    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12718        boolean allowed = false;
12719        final int NP = PackageParser.NEW_PERMISSIONS.length;
12720        for (int ip=0; ip<NP; ip++) {
12721            final PackageParser.NewPermissionInfo npi
12722                    = PackageParser.NEW_PERMISSIONS[ip];
12723            if (npi.name.equals(perm)
12724                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12725                allowed = true;
12726                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12727                        + pkg.packageName);
12728                break;
12729            }
12730        }
12731        return allowed;
12732    }
12733
12734    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12735            BasePermission bp, PermissionsState origPermissions) {
12736        boolean privilegedPermission = (bp.protectionLevel
12737                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12738        boolean privappPermissionsDisable =
12739                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12740        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12741        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12742        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12743                && !platformPackage && platformPermission) {
12744            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12745                    .getPrivAppPermissions(pkg.packageName);
12746            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12747            if (!whitelisted) {
12748                Slog.w(TAG, "Privileged permission " + perm + " for package "
12749                        + pkg.packageName + " - not in privapp-permissions whitelist");
12750                // Only report violations for apps on system image
12751                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12752                    if (mPrivappPermissionsViolations == null) {
12753                        mPrivappPermissionsViolations = new ArraySet<>();
12754                    }
12755                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12756                }
12757                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12758                    return false;
12759                }
12760            }
12761        }
12762        boolean allowed = (compareSignatures(
12763                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12764                        == PackageManager.SIGNATURE_MATCH)
12765                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12766                        == PackageManager.SIGNATURE_MATCH);
12767        if (!allowed && privilegedPermission) {
12768            if (isSystemApp(pkg)) {
12769                // For updated system applications, a system permission
12770                // is granted only if it had been defined by the original application.
12771                if (pkg.isUpdatedSystemApp()) {
12772                    final PackageSetting sysPs = mSettings
12773                            .getDisabledSystemPkgLPr(pkg.packageName);
12774                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12775                        // If the original was granted this permission, we take
12776                        // that grant decision as read and propagate it to the
12777                        // update.
12778                        if (sysPs.isPrivileged()) {
12779                            allowed = true;
12780                        }
12781                    } else {
12782                        // The system apk may have been updated with an older
12783                        // version of the one on the data partition, but which
12784                        // granted a new system permission that it didn't have
12785                        // before.  In this case we do want to allow the app to
12786                        // now get the new permission if the ancestral apk is
12787                        // privileged to get it.
12788                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12789                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12790                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12791                                    allowed = true;
12792                                    break;
12793                                }
12794                            }
12795                        }
12796                        // Also if a privileged parent package on the system image or any of
12797                        // its children requested a privileged permission, the updated child
12798                        // packages can also get the permission.
12799                        if (pkg.parentPackage != null) {
12800                            final PackageSetting disabledSysParentPs = mSettings
12801                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12802                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12803                                    && disabledSysParentPs.isPrivileged()) {
12804                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12805                                    allowed = true;
12806                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12807                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12808                                    for (int i = 0; i < count; i++) {
12809                                        PackageParser.Package disabledSysChildPkg =
12810                                                disabledSysParentPs.pkg.childPackages.get(i);
12811                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12812                                                perm)) {
12813                                            allowed = true;
12814                                            break;
12815                                        }
12816                                    }
12817                                }
12818                            }
12819                        }
12820                    }
12821                } else {
12822                    allowed = isPrivilegedApp(pkg);
12823                }
12824            }
12825        }
12826        if (!allowed) {
12827            if (!allowed && (bp.protectionLevel
12828                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12829                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12830                // If this was a previously normal/dangerous permission that got moved
12831                // to a system permission as part of the runtime permission redesign, then
12832                // we still want to blindly grant it to old apps.
12833                allowed = true;
12834            }
12835            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12836                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12837                // If this permission is to be granted to the system installer and
12838                // this app is an installer, then it gets the permission.
12839                allowed = true;
12840            }
12841            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12842                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12843                // If this permission is to be granted to the system verifier and
12844                // this app is a verifier, then it gets the permission.
12845                allowed = true;
12846            }
12847            if (!allowed && (bp.protectionLevel
12848                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12849                    && isSystemApp(pkg)) {
12850                // Any pre-installed system app is allowed to get this permission.
12851                allowed = true;
12852            }
12853            if (!allowed && (bp.protectionLevel
12854                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12855                // For development permissions, a development permission
12856                // is granted only if it was already granted.
12857                allowed = origPermissions.hasInstallPermission(perm);
12858            }
12859            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12860                    && pkg.packageName.equals(mSetupWizardPackage)) {
12861                // If this permission is to be granted to the system setup wizard and
12862                // this app is a setup wizard, then it gets the permission.
12863                allowed = true;
12864            }
12865        }
12866        return allowed;
12867    }
12868
12869    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12870        final int permCount = pkg.requestedPermissions.size();
12871        for (int j = 0; j < permCount; j++) {
12872            String requestedPermission = pkg.requestedPermissions.get(j);
12873            if (permission.equals(requestedPermission)) {
12874                return true;
12875            }
12876        }
12877        return false;
12878    }
12879
12880    final class ActivityIntentResolver
12881            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12882        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12883                boolean defaultOnly, int userId) {
12884            if (!sUserManager.exists(userId)) return null;
12885            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12886            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12887        }
12888
12889        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12890                int userId) {
12891            if (!sUserManager.exists(userId)) return null;
12892            mFlags = flags;
12893            return super.queryIntent(intent, resolvedType,
12894                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12895                    userId);
12896        }
12897
12898        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12899                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12900            if (!sUserManager.exists(userId)) return null;
12901            if (packageActivities == null) {
12902                return null;
12903            }
12904            mFlags = flags;
12905            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12906            final int N = packageActivities.size();
12907            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12908                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12909
12910            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12911            for (int i = 0; i < N; ++i) {
12912                intentFilters = packageActivities.get(i).intents;
12913                if (intentFilters != null && intentFilters.size() > 0) {
12914                    PackageParser.ActivityIntentInfo[] array =
12915                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12916                    intentFilters.toArray(array);
12917                    listCut.add(array);
12918                }
12919            }
12920            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12921        }
12922
12923        /**
12924         * Finds a privileged activity that matches the specified activity names.
12925         */
12926        private PackageParser.Activity findMatchingActivity(
12927                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12928            for (PackageParser.Activity sysActivity : activityList) {
12929                if (sysActivity.info.name.equals(activityInfo.name)) {
12930                    return sysActivity;
12931                }
12932                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12933                    return sysActivity;
12934                }
12935                if (sysActivity.info.targetActivity != null) {
12936                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12937                        return sysActivity;
12938                    }
12939                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12940                        return sysActivity;
12941                    }
12942                }
12943            }
12944            return null;
12945        }
12946
12947        public class IterGenerator<E> {
12948            public Iterator<E> generate(ActivityIntentInfo info) {
12949                return null;
12950            }
12951        }
12952
12953        public class ActionIterGenerator extends IterGenerator<String> {
12954            @Override
12955            public Iterator<String> generate(ActivityIntentInfo info) {
12956                return info.actionsIterator();
12957            }
12958        }
12959
12960        public class CategoriesIterGenerator extends IterGenerator<String> {
12961            @Override
12962            public Iterator<String> generate(ActivityIntentInfo info) {
12963                return info.categoriesIterator();
12964            }
12965        }
12966
12967        public class SchemesIterGenerator extends IterGenerator<String> {
12968            @Override
12969            public Iterator<String> generate(ActivityIntentInfo info) {
12970                return info.schemesIterator();
12971            }
12972        }
12973
12974        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12975            @Override
12976            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12977                return info.authoritiesIterator();
12978            }
12979        }
12980
12981        /**
12982         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12983         * MODIFIED. Do not pass in a list that should not be changed.
12984         */
12985        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12986                IterGenerator<T> generator, Iterator<T> searchIterator) {
12987            // loop through the set of actions; every one must be found in the intent filter
12988            while (searchIterator.hasNext()) {
12989                // we must have at least one filter in the list to consider a match
12990                if (intentList.size() == 0) {
12991                    break;
12992                }
12993
12994                final T searchAction = searchIterator.next();
12995
12996                // loop through the set of intent filters
12997                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12998                while (intentIter.hasNext()) {
12999                    final ActivityIntentInfo intentInfo = intentIter.next();
13000                    boolean selectionFound = false;
13001
13002                    // loop through the intent filter's selection criteria; at least one
13003                    // of them must match the searched criteria
13004                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13005                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13006                        final T intentSelection = intentSelectionIter.next();
13007                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13008                            selectionFound = true;
13009                            break;
13010                        }
13011                    }
13012
13013                    // the selection criteria wasn't found in this filter's set; this filter
13014                    // is not a potential match
13015                    if (!selectionFound) {
13016                        intentIter.remove();
13017                    }
13018                }
13019            }
13020        }
13021
13022        private boolean isProtectedAction(ActivityIntentInfo filter) {
13023            final Iterator<String> actionsIter = filter.actionsIterator();
13024            while (actionsIter != null && actionsIter.hasNext()) {
13025                final String filterAction = actionsIter.next();
13026                if (PROTECTED_ACTIONS.contains(filterAction)) {
13027                    return true;
13028                }
13029            }
13030            return false;
13031        }
13032
13033        /**
13034         * Adjusts the priority of the given intent filter according to policy.
13035         * <p>
13036         * <ul>
13037         * <li>The priority for non privileged applications is capped to '0'</li>
13038         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13039         * <li>The priority for unbundled updates to privileged applications is capped to the
13040         *      priority defined on the system partition</li>
13041         * </ul>
13042         * <p>
13043         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13044         * allowed to obtain any priority on any action.
13045         */
13046        private void adjustPriority(
13047                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13048            // nothing to do; priority is fine as-is
13049            if (intent.getPriority() <= 0) {
13050                return;
13051            }
13052
13053            final ActivityInfo activityInfo = intent.activity.info;
13054            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13055
13056            final boolean privilegedApp =
13057                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13058            if (!privilegedApp) {
13059                // non-privileged applications can never define a priority >0
13060                if (DEBUG_FILTERS) {
13061                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13062                            + " package: " + applicationInfo.packageName
13063                            + " activity: " + intent.activity.className
13064                            + " origPrio: " + intent.getPriority());
13065                }
13066                intent.setPriority(0);
13067                return;
13068            }
13069
13070            if (systemActivities == null) {
13071                // the system package is not disabled; we're parsing the system partition
13072                if (isProtectedAction(intent)) {
13073                    if (mDeferProtectedFilters) {
13074                        // We can't deal with these just yet. No component should ever obtain a
13075                        // >0 priority for a protected actions, with ONE exception -- the setup
13076                        // wizard. The setup wizard, however, cannot be known until we're able to
13077                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13078                        // until all intent filters have been processed. Chicken, meet egg.
13079                        // Let the filter temporarily have a high priority and rectify the
13080                        // priorities after all system packages have been scanned.
13081                        mProtectedFilters.add(intent);
13082                        if (DEBUG_FILTERS) {
13083                            Slog.i(TAG, "Protected action; save for later;"
13084                                    + " package: " + applicationInfo.packageName
13085                                    + " activity: " + intent.activity.className
13086                                    + " origPrio: " + intent.getPriority());
13087                        }
13088                        return;
13089                    } else {
13090                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13091                            Slog.i(TAG, "No setup wizard;"
13092                                + " All protected intents capped to priority 0");
13093                        }
13094                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13095                            if (DEBUG_FILTERS) {
13096                                Slog.i(TAG, "Found setup wizard;"
13097                                    + " allow priority " + intent.getPriority() + ";"
13098                                    + " package: " + intent.activity.info.packageName
13099                                    + " activity: " + intent.activity.className
13100                                    + " priority: " + intent.getPriority());
13101                            }
13102                            // setup wizard gets whatever it wants
13103                            return;
13104                        }
13105                        if (DEBUG_FILTERS) {
13106                            Slog.i(TAG, "Protected action; cap priority to 0;"
13107                                    + " package: " + intent.activity.info.packageName
13108                                    + " activity: " + intent.activity.className
13109                                    + " origPrio: " + intent.getPriority());
13110                        }
13111                        intent.setPriority(0);
13112                        return;
13113                    }
13114                }
13115                // privileged apps on the system image get whatever priority they request
13116                return;
13117            }
13118
13119            // privileged app unbundled update ... try to find the same activity
13120            final PackageParser.Activity foundActivity =
13121                    findMatchingActivity(systemActivities, activityInfo);
13122            if (foundActivity == null) {
13123                // this is a new activity; it cannot obtain >0 priority
13124                if (DEBUG_FILTERS) {
13125                    Slog.i(TAG, "New activity; cap priority to 0;"
13126                            + " package: " + applicationInfo.packageName
13127                            + " activity: " + intent.activity.className
13128                            + " origPrio: " + intent.getPriority());
13129                }
13130                intent.setPriority(0);
13131                return;
13132            }
13133
13134            // found activity, now check for filter equivalence
13135
13136            // a shallow copy is enough; we modify the list, not its contents
13137            final List<ActivityIntentInfo> intentListCopy =
13138                    new ArrayList<>(foundActivity.intents);
13139            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13140
13141            // find matching action subsets
13142            final Iterator<String> actionsIterator = intent.actionsIterator();
13143            if (actionsIterator != null) {
13144                getIntentListSubset(
13145                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13146                if (intentListCopy.size() == 0) {
13147                    // no more intents to match; we're not equivalent
13148                    if (DEBUG_FILTERS) {
13149                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13150                                + " package: " + applicationInfo.packageName
13151                                + " activity: " + intent.activity.className
13152                                + " origPrio: " + intent.getPriority());
13153                    }
13154                    intent.setPriority(0);
13155                    return;
13156                }
13157            }
13158
13159            // find matching category subsets
13160            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13161            if (categoriesIterator != null) {
13162                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13163                        categoriesIterator);
13164                if (intentListCopy.size() == 0) {
13165                    // no more intents to match; we're not equivalent
13166                    if (DEBUG_FILTERS) {
13167                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13168                                + " package: " + applicationInfo.packageName
13169                                + " activity: " + intent.activity.className
13170                                + " origPrio: " + intent.getPriority());
13171                    }
13172                    intent.setPriority(0);
13173                    return;
13174                }
13175            }
13176
13177            // find matching schemes subsets
13178            final Iterator<String> schemesIterator = intent.schemesIterator();
13179            if (schemesIterator != null) {
13180                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13181                        schemesIterator);
13182                if (intentListCopy.size() == 0) {
13183                    // no more intents to match; we're not equivalent
13184                    if (DEBUG_FILTERS) {
13185                        Slog.i(TAG, "Mismatched scheme; 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 authorities subsets
13196            final Iterator<IntentFilter.AuthorityEntry>
13197                    authoritiesIterator = intent.authoritiesIterator();
13198            if (authoritiesIterator != null) {
13199                getIntentListSubset(intentListCopy,
13200                        new AuthoritiesIterGenerator(),
13201                        authoritiesIterator);
13202                if (intentListCopy.size() == 0) {
13203                    // no more intents to match; we're not equivalent
13204                    if (DEBUG_FILTERS) {
13205                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13206                                + " package: " + applicationInfo.packageName
13207                                + " activity: " + intent.activity.className
13208                                + " origPrio: " + intent.getPriority());
13209                    }
13210                    intent.setPriority(0);
13211                    return;
13212                }
13213            }
13214
13215            // we found matching filter(s); app gets the max priority of all intents
13216            int cappedPriority = 0;
13217            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13218                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13219            }
13220            if (intent.getPriority() > cappedPriority) {
13221                if (DEBUG_FILTERS) {
13222                    Slog.i(TAG, "Found matching filter(s);"
13223                            + " cap priority to " + cappedPriority + ";"
13224                            + " package: " + applicationInfo.packageName
13225                            + " activity: " + intent.activity.className
13226                            + " origPrio: " + intent.getPriority());
13227                }
13228                intent.setPriority(cappedPriority);
13229                return;
13230            }
13231            // all this for nothing; the requested priority was <= what was on the system
13232        }
13233
13234        public final void addActivity(PackageParser.Activity a, String type) {
13235            mActivities.put(a.getComponentName(), a);
13236            if (DEBUG_SHOW_INFO)
13237                Log.v(
13238                TAG, "  " + type + " " +
13239                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13240            if (DEBUG_SHOW_INFO)
13241                Log.v(TAG, "    Class=" + a.info.name);
13242            final int NI = a.intents.size();
13243            for (int j=0; j<NI; j++) {
13244                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13245                if ("activity".equals(type)) {
13246                    final PackageSetting ps =
13247                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13248                    final List<PackageParser.Activity> systemActivities =
13249                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13250                    adjustPriority(systemActivities, intent);
13251                }
13252                if (DEBUG_SHOW_INFO) {
13253                    Log.v(TAG, "    IntentFilter:");
13254                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13255                }
13256                if (!intent.debugCheck()) {
13257                    Log.w(TAG, "==> For Activity " + a.info.name);
13258                }
13259                addFilter(intent);
13260            }
13261        }
13262
13263        public final void removeActivity(PackageParser.Activity a, String type) {
13264            mActivities.remove(a.getComponentName());
13265            if (DEBUG_SHOW_INFO) {
13266                Log.v(TAG, "  " + type + " "
13267                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13268                                : a.info.name) + ":");
13269                Log.v(TAG, "    Class=" + a.info.name);
13270            }
13271            final int NI = a.intents.size();
13272            for (int j=0; j<NI; j++) {
13273                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13274                if (DEBUG_SHOW_INFO) {
13275                    Log.v(TAG, "    IntentFilter:");
13276                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13277                }
13278                removeFilter(intent);
13279            }
13280        }
13281
13282        @Override
13283        protected boolean allowFilterResult(
13284                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13285            ActivityInfo filterAi = filter.activity.info;
13286            for (int i=dest.size()-1; i>=0; i--) {
13287                ActivityInfo destAi = dest.get(i).activityInfo;
13288                if (destAi.name == filterAi.name
13289                        && destAi.packageName == filterAi.packageName) {
13290                    return false;
13291                }
13292            }
13293            return true;
13294        }
13295
13296        @Override
13297        protected ActivityIntentInfo[] newArray(int size) {
13298            return new ActivityIntentInfo[size];
13299        }
13300
13301        @Override
13302        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13303            if (!sUserManager.exists(userId)) return true;
13304            PackageParser.Package p = filter.activity.owner;
13305            if (p != null) {
13306                PackageSetting ps = (PackageSetting)p.mExtras;
13307                if (ps != null) {
13308                    // System apps are never considered stopped for purposes of
13309                    // filtering, because there may be no way for the user to
13310                    // actually re-launch them.
13311                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13312                            && ps.getStopped(userId);
13313                }
13314            }
13315            return false;
13316        }
13317
13318        @Override
13319        protected boolean isPackageForFilter(String packageName,
13320                PackageParser.ActivityIntentInfo info) {
13321            return packageName.equals(info.activity.owner.packageName);
13322        }
13323
13324        @Override
13325        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13326                int match, int userId) {
13327            if (!sUserManager.exists(userId)) return null;
13328            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13329                return null;
13330            }
13331            final PackageParser.Activity activity = info.activity;
13332            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13333            if (ps == null) {
13334                return null;
13335            }
13336            final PackageUserState userState = ps.readUserState(userId);
13337            ActivityInfo ai =
13338                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13339            if (ai == null) {
13340                return null;
13341            }
13342            final boolean matchExplicitlyVisibleOnly =
13343                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13344            final boolean matchVisibleToInstantApp =
13345                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13346            final boolean componentVisible =
13347                    matchVisibleToInstantApp
13348                    && info.isVisibleToInstantApp()
13349                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13350            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13351            // throw out filters that aren't visible to ephemeral apps
13352            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13353                return null;
13354            }
13355            // throw out instant app filters if we're not explicitly requesting them
13356            if (!matchInstantApp && userState.instantApp) {
13357                return null;
13358            }
13359            // throw out instant app filters if updates are available; will trigger
13360            // instant app resolution
13361            if (userState.instantApp && ps.isUpdateAvailable()) {
13362                return null;
13363            }
13364            final ResolveInfo res = new ResolveInfo();
13365            res.activityInfo = ai;
13366            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13367                res.filter = info;
13368            }
13369            if (info != null) {
13370                res.handleAllWebDataURI = info.handleAllWebDataURI();
13371            }
13372            res.priority = info.getPriority();
13373            res.preferredOrder = activity.owner.mPreferredOrder;
13374            //System.out.println("Result: " + res.activityInfo.className +
13375            //                   " = " + res.priority);
13376            res.match = match;
13377            res.isDefault = info.hasDefault;
13378            res.labelRes = info.labelRes;
13379            res.nonLocalizedLabel = info.nonLocalizedLabel;
13380            if (userNeedsBadging(userId)) {
13381                res.noResourceId = true;
13382            } else {
13383                res.icon = info.icon;
13384            }
13385            res.iconResourceId = info.icon;
13386            res.system = res.activityInfo.applicationInfo.isSystemApp();
13387            res.isInstantAppAvailable = userState.instantApp;
13388            return res;
13389        }
13390
13391        @Override
13392        protected void sortResults(List<ResolveInfo> results) {
13393            Collections.sort(results, mResolvePrioritySorter);
13394        }
13395
13396        @Override
13397        protected void dumpFilter(PrintWriter out, String prefix,
13398                PackageParser.ActivityIntentInfo filter) {
13399            out.print(prefix); out.print(
13400                    Integer.toHexString(System.identityHashCode(filter.activity)));
13401                    out.print(' ');
13402                    filter.activity.printComponentShortName(out);
13403                    out.print(" filter ");
13404                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13405        }
13406
13407        @Override
13408        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13409            return filter.activity;
13410        }
13411
13412        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13413            PackageParser.Activity activity = (PackageParser.Activity)label;
13414            out.print(prefix); out.print(
13415                    Integer.toHexString(System.identityHashCode(activity)));
13416                    out.print(' ');
13417                    activity.printComponentShortName(out);
13418            if (count > 1) {
13419                out.print(" ("); out.print(count); out.print(" filters)");
13420            }
13421            out.println();
13422        }
13423
13424        // Keys are String (activity class name), values are Activity.
13425        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13426                = new ArrayMap<ComponentName, PackageParser.Activity>();
13427        private int mFlags;
13428    }
13429
13430    private final class ServiceIntentResolver
13431            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13432        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13433                boolean defaultOnly, int userId) {
13434            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13435            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13436        }
13437
13438        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13439                int userId) {
13440            if (!sUserManager.exists(userId)) return null;
13441            mFlags = flags;
13442            return super.queryIntent(intent, resolvedType,
13443                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13444                    userId);
13445        }
13446
13447        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13448                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13449            if (!sUserManager.exists(userId)) return null;
13450            if (packageServices == null) {
13451                return null;
13452            }
13453            mFlags = flags;
13454            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13455            final int N = packageServices.size();
13456            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13457                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13458
13459            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13460            for (int i = 0; i < N; ++i) {
13461                intentFilters = packageServices.get(i).intents;
13462                if (intentFilters != null && intentFilters.size() > 0) {
13463                    PackageParser.ServiceIntentInfo[] array =
13464                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13465                    intentFilters.toArray(array);
13466                    listCut.add(array);
13467                }
13468            }
13469            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13470        }
13471
13472        public final void addService(PackageParser.Service s) {
13473            mServices.put(s.getComponentName(), s);
13474            if (DEBUG_SHOW_INFO) {
13475                Log.v(TAG, "  "
13476                        + (s.info.nonLocalizedLabel != null
13477                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13478                Log.v(TAG, "    Class=" + s.info.name);
13479            }
13480            final int NI = s.intents.size();
13481            int j;
13482            for (j=0; j<NI; j++) {
13483                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13484                if (DEBUG_SHOW_INFO) {
13485                    Log.v(TAG, "    IntentFilter:");
13486                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13487                }
13488                if (!intent.debugCheck()) {
13489                    Log.w(TAG, "==> For Service " + s.info.name);
13490                }
13491                addFilter(intent);
13492            }
13493        }
13494
13495        public final void removeService(PackageParser.Service s) {
13496            mServices.remove(s.getComponentName());
13497            if (DEBUG_SHOW_INFO) {
13498                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13499                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13500                Log.v(TAG, "    Class=" + s.info.name);
13501            }
13502            final int NI = s.intents.size();
13503            int j;
13504            for (j=0; j<NI; j++) {
13505                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13506                if (DEBUG_SHOW_INFO) {
13507                    Log.v(TAG, "    IntentFilter:");
13508                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13509                }
13510                removeFilter(intent);
13511            }
13512        }
13513
13514        @Override
13515        protected boolean allowFilterResult(
13516                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13517            ServiceInfo filterSi = filter.service.info;
13518            for (int i=dest.size()-1; i>=0; i--) {
13519                ServiceInfo destAi = dest.get(i).serviceInfo;
13520                if (destAi.name == filterSi.name
13521                        && destAi.packageName == filterSi.packageName) {
13522                    return false;
13523                }
13524            }
13525            return true;
13526        }
13527
13528        @Override
13529        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13530            return new PackageParser.ServiceIntentInfo[size];
13531        }
13532
13533        @Override
13534        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13535            if (!sUserManager.exists(userId)) return true;
13536            PackageParser.Package p = filter.service.owner;
13537            if (p != null) {
13538                PackageSetting ps = (PackageSetting)p.mExtras;
13539                if (ps != null) {
13540                    // System apps are never considered stopped for purposes of
13541                    // filtering, because there may be no way for the user to
13542                    // actually re-launch them.
13543                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13544                            && ps.getStopped(userId);
13545                }
13546            }
13547            return false;
13548        }
13549
13550        @Override
13551        protected boolean isPackageForFilter(String packageName,
13552                PackageParser.ServiceIntentInfo info) {
13553            return packageName.equals(info.service.owner.packageName);
13554        }
13555
13556        @Override
13557        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13558                int match, int userId) {
13559            if (!sUserManager.exists(userId)) return null;
13560            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13561            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13562                return null;
13563            }
13564            final PackageParser.Service service = info.service;
13565            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13566            if (ps == null) {
13567                return null;
13568            }
13569            final PackageUserState userState = ps.readUserState(userId);
13570            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13571                    userState, userId);
13572            if (si == null) {
13573                return null;
13574            }
13575            final boolean matchVisibleToInstantApp =
13576                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13577            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13578            // throw out filters that aren't visible to ephemeral apps
13579            if (matchVisibleToInstantApp
13580                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13581                return null;
13582            }
13583            // throw out ephemeral filters if we're not explicitly requesting them
13584            if (!isInstantApp && userState.instantApp) {
13585                return null;
13586            }
13587            // throw out instant app filters if updates are available; will trigger
13588            // instant app resolution
13589            if (userState.instantApp && ps.isUpdateAvailable()) {
13590                return null;
13591            }
13592            final ResolveInfo res = new ResolveInfo();
13593            res.serviceInfo = si;
13594            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13595                res.filter = filter;
13596            }
13597            res.priority = info.getPriority();
13598            res.preferredOrder = service.owner.mPreferredOrder;
13599            res.match = match;
13600            res.isDefault = info.hasDefault;
13601            res.labelRes = info.labelRes;
13602            res.nonLocalizedLabel = info.nonLocalizedLabel;
13603            res.icon = info.icon;
13604            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13605            return res;
13606        }
13607
13608        @Override
13609        protected void sortResults(List<ResolveInfo> results) {
13610            Collections.sort(results, mResolvePrioritySorter);
13611        }
13612
13613        @Override
13614        protected void dumpFilter(PrintWriter out, String prefix,
13615                PackageParser.ServiceIntentInfo filter) {
13616            out.print(prefix); out.print(
13617                    Integer.toHexString(System.identityHashCode(filter.service)));
13618                    out.print(' ');
13619                    filter.service.printComponentShortName(out);
13620                    out.print(" filter ");
13621                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13622        }
13623
13624        @Override
13625        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13626            return filter.service;
13627        }
13628
13629        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13630            PackageParser.Service service = (PackageParser.Service)label;
13631            out.print(prefix); out.print(
13632                    Integer.toHexString(System.identityHashCode(service)));
13633                    out.print(' ');
13634                    service.printComponentShortName(out);
13635            if (count > 1) {
13636                out.print(" ("); out.print(count); out.print(" filters)");
13637            }
13638            out.println();
13639        }
13640
13641//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13642//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13643//            final List<ResolveInfo> retList = Lists.newArrayList();
13644//            while (i.hasNext()) {
13645//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13646//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13647//                    retList.add(resolveInfo);
13648//                }
13649//            }
13650//            return retList;
13651//        }
13652
13653        // Keys are String (activity class name), values are Activity.
13654        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13655                = new ArrayMap<ComponentName, PackageParser.Service>();
13656        private int mFlags;
13657    }
13658
13659    private final class ProviderIntentResolver
13660            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13661        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13662                boolean defaultOnly, int userId) {
13663            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13664            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13665        }
13666
13667        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13668                int userId) {
13669            if (!sUserManager.exists(userId))
13670                return null;
13671            mFlags = flags;
13672            return super.queryIntent(intent, resolvedType,
13673                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13674                    userId);
13675        }
13676
13677        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13678                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13679            if (!sUserManager.exists(userId))
13680                return null;
13681            if (packageProviders == null) {
13682                return null;
13683            }
13684            mFlags = flags;
13685            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13686            final int N = packageProviders.size();
13687            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13688                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13689
13690            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13691            for (int i = 0; i < N; ++i) {
13692                intentFilters = packageProviders.get(i).intents;
13693                if (intentFilters != null && intentFilters.size() > 0) {
13694                    PackageParser.ProviderIntentInfo[] array =
13695                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13696                    intentFilters.toArray(array);
13697                    listCut.add(array);
13698                }
13699            }
13700            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13701        }
13702
13703        public final void addProvider(PackageParser.Provider p) {
13704            if (mProviders.containsKey(p.getComponentName())) {
13705                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13706                return;
13707            }
13708
13709            mProviders.put(p.getComponentName(), p);
13710            if (DEBUG_SHOW_INFO) {
13711                Log.v(TAG, "  "
13712                        + (p.info.nonLocalizedLabel != null
13713                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13714                Log.v(TAG, "    Class=" + p.info.name);
13715            }
13716            final int NI = p.intents.size();
13717            int j;
13718            for (j = 0; j < NI; j++) {
13719                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13720                if (DEBUG_SHOW_INFO) {
13721                    Log.v(TAG, "    IntentFilter:");
13722                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13723                }
13724                if (!intent.debugCheck()) {
13725                    Log.w(TAG, "==> For Provider " + p.info.name);
13726                }
13727                addFilter(intent);
13728            }
13729        }
13730
13731        public final void removeProvider(PackageParser.Provider p) {
13732            mProviders.remove(p.getComponentName());
13733            if (DEBUG_SHOW_INFO) {
13734                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13735                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13736                Log.v(TAG, "    Class=" + p.info.name);
13737            }
13738            final int NI = p.intents.size();
13739            int j;
13740            for (j = 0; j < NI; j++) {
13741                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13742                if (DEBUG_SHOW_INFO) {
13743                    Log.v(TAG, "    IntentFilter:");
13744                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13745                }
13746                removeFilter(intent);
13747            }
13748        }
13749
13750        @Override
13751        protected boolean allowFilterResult(
13752                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13753            ProviderInfo filterPi = filter.provider.info;
13754            for (int i = dest.size() - 1; i >= 0; i--) {
13755                ProviderInfo destPi = dest.get(i).providerInfo;
13756                if (destPi.name == filterPi.name
13757                        && destPi.packageName == filterPi.packageName) {
13758                    return false;
13759                }
13760            }
13761            return true;
13762        }
13763
13764        @Override
13765        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13766            return new PackageParser.ProviderIntentInfo[size];
13767        }
13768
13769        @Override
13770        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13771            if (!sUserManager.exists(userId))
13772                return true;
13773            PackageParser.Package p = filter.provider.owner;
13774            if (p != null) {
13775                PackageSetting ps = (PackageSetting) p.mExtras;
13776                if (ps != null) {
13777                    // System apps are never considered stopped for purposes of
13778                    // filtering, because there may be no way for the user to
13779                    // actually re-launch them.
13780                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13781                            && ps.getStopped(userId);
13782                }
13783            }
13784            return false;
13785        }
13786
13787        @Override
13788        protected boolean isPackageForFilter(String packageName,
13789                PackageParser.ProviderIntentInfo info) {
13790            return packageName.equals(info.provider.owner.packageName);
13791        }
13792
13793        @Override
13794        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13795                int match, int userId) {
13796            if (!sUserManager.exists(userId))
13797                return null;
13798            final PackageParser.ProviderIntentInfo info = filter;
13799            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13800                return null;
13801            }
13802            final PackageParser.Provider provider = info.provider;
13803            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13804            if (ps == null) {
13805                return null;
13806            }
13807            final PackageUserState userState = ps.readUserState(userId);
13808            final boolean matchVisibleToInstantApp =
13809                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13810            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13811            // throw out filters that aren't visible to instant applications
13812            if (matchVisibleToInstantApp
13813                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13814                return null;
13815            }
13816            // throw out instant application filters if we're not explicitly requesting them
13817            if (!isInstantApp && userState.instantApp) {
13818                return null;
13819            }
13820            // throw out instant application filters if updates are available; will trigger
13821            // instant application resolution
13822            if (userState.instantApp && ps.isUpdateAvailable()) {
13823                return null;
13824            }
13825            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13826                    userState, userId);
13827            if (pi == null) {
13828                return null;
13829            }
13830            final ResolveInfo res = new ResolveInfo();
13831            res.providerInfo = pi;
13832            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13833                res.filter = filter;
13834            }
13835            res.priority = info.getPriority();
13836            res.preferredOrder = provider.owner.mPreferredOrder;
13837            res.match = match;
13838            res.isDefault = info.hasDefault;
13839            res.labelRes = info.labelRes;
13840            res.nonLocalizedLabel = info.nonLocalizedLabel;
13841            res.icon = info.icon;
13842            res.system = res.providerInfo.applicationInfo.isSystemApp();
13843            return res;
13844        }
13845
13846        @Override
13847        protected void sortResults(List<ResolveInfo> results) {
13848            Collections.sort(results, mResolvePrioritySorter);
13849        }
13850
13851        @Override
13852        protected void dumpFilter(PrintWriter out, String prefix,
13853                PackageParser.ProviderIntentInfo filter) {
13854            out.print(prefix);
13855            out.print(
13856                    Integer.toHexString(System.identityHashCode(filter.provider)));
13857            out.print(' ');
13858            filter.provider.printComponentShortName(out);
13859            out.print(" filter ");
13860            out.println(Integer.toHexString(System.identityHashCode(filter)));
13861        }
13862
13863        @Override
13864        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13865            return filter.provider;
13866        }
13867
13868        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13869            PackageParser.Provider provider = (PackageParser.Provider)label;
13870            out.print(prefix); out.print(
13871                    Integer.toHexString(System.identityHashCode(provider)));
13872                    out.print(' ');
13873                    provider.printComponentShortName(out);
13874            if (count > 1) {
13875                out.print(" ("); out.print(count); out.print(" filters)");
13876            }
13877            out.println();
13878        }
13879
13880        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13881                = new ArrayMap<ComponentName, PackageParser.Provider>();
13882        private int mFlags;
13883    }
13884
13885    static final class EphemeralIntentResolver
13886            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13887        /**
13888         * The result that has the highest defined order. Ordering applies on a
13889         * per-package basis. Mapping is from package name to Pair of order and
13890         * EphemeralResolveInfo.
13891         * <p>
13892         * NOTE: This is implemented as a field variable for convenience and efficiency.
13893         * By having a field variable, we're able to track filter ordering as soon as
13894         * a non-zero order is defined. Otherwise, multiple loops across the result set
13895         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13896         * this needs to be contained entirely within {@link #filterResults}.
13897         */
13898        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13899
13900        @Override
13901        protected AuxiliaryResolveInfo[] newArray(int size) {
13902            return new AuxiliaryResolveInfo[size];
13903        }
13904
13905        @Override
13906        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13907            return true;
13908        }
13909
13910        @Override
13911        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13912                int userId) {
13913            if (!sUserManager.exists(userId)) {
13914                return null;
13915            }
13916            final String packageName = responseObj.resolveInfo.getPackageName();
13917            final Integer order = responseObj.getOrder();
13918            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13919                    mOrderResult.get(packageName);
13920            // ordering is enabled and this item's order isn't high enough
13921            if (lastOrderResult != null && lastOrderResult.first >= order) {
13922                return null;
13923            }
13924            final InstantAppResolveInfo res = responseObj.resolveInfo;
13925            if (order > 0) {
13926                // non-zero order, enable ordering
13927                mOrderResult.put(packageName, new Pair<>(order, res));
13928            }
13929            return responseObj;
13930        }
13931
13932        @Override
13933        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13934            // only do work if ordering is enabled [most of the time it won't be]
13935            if (mOrderResult.size() == 0) {
13936                return;
13937            }
13938            int resultSize = results.size();
13939            for (int i = 0; i < resultSize; i++) {
13940                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13941                final String packageName = info.getPackageName();
13942                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13943                if (savedInfo == null) {
13944                    // package doesn't having ordering
13945                    continue;
13946                }
13947                if (savedInfo.second == info) {
13948                    // circled back to the highest ordered item; remove from order list
13949                    mOrderResult.remove(savedInfo);
13950                    if (mOrderResult.size() == 0) {
13951                        // no more ordered items
13952                        break;
13953                    }
13954                    continue;
13955                }
13956                // item has a worse order, remove it from the result list
13957                results.remove(i);
13958                resultSize--;
13959                i--;
13960            }
13961        }
13962    }
13963
13964    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13965            new Comparator<ResolveInfo>() {
13966        public int compare(ResolveInfo r1, ResolveInfo r2) {
13967            int v1 = r1.priority;
13968            int v2 = r2.priority;
13969            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13970            if (v1 != v2) {
13971                return (v1 > v2) ? -1 : 1;
13972            }
13973            v1 = r1.preferredOrder;
13974            v2 = r2.preferredOrder;
13975            if (v1 != v2) {
13976                return (v1 > v2) ? -1 : 1;
13977            }
13978            if (r1.isDefault != r2.isDefault) {
13979                return r1.isDefault ? -1 : 1;
13980            }
13981            v1 = r1.match;
13982            v2 = r2.match;
13983            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13984            if (v1 != v2) {
13985                return (v1 > v2) ? -1 : 1;
13986            }
13987            if (r1.system != r2.system) {
13988                return r1.system ? -1 : 1;
13989            }
13990            if (r1.activityInfo != null) {
13991                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13992            }
13993            if (r1.serviceInfo != null) {
13994                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13995            }
13996            if (r1.providerInfo != null) {
13997                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13998            }
13999            return 0;
14000        }
14001    };
14002
14003    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14004            new Comparator<ProviderInfo>() {
14005        public int compare(ProviderInfo p1, ProviderInfo p2) {
14006            final int v1 = p1.initOrder;
14007            final int v2 = p2.initOrder;
14008            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14009        }
14010    };
14011
14012    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14013            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14014            final int[] userIds) {
14015        mHandler.post(new Runnable() {
14016            @Override
14017            public void run() {
14018                try {
14019                    final IActivityManager am = ActivityManager.getService();
14020                    if (am == null) return;
14021                    final int[] resolvedUserIds;
14022                    if (userIds == null) {
14023                        resolvedUserIds = am.getRunningUserIds();
14024                    } else {
14025                        resolvedUserIds = userIds;
14026                    }
14027                    for (int id : resolvedUserIds) {
14028                        final Intent intent = new Intent(action,
14029                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14030                        if (extras != null) {
14031                            intent.putExtras(extras);
14032                        }
14033                        if (targetPkg != null) {
14034                            intent.setPackage(targetPkg);
14035                        }
14036                        // Modify the UID when posting to other users
14037                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14038                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14039                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14040                            intent.putExtra(Intent.EXTRA_UID, uid);
14041                        }
14042                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14043                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14044                        if (DEBUG_BROADCASTS) {
14045                            RuntimeException here = new RuntimeException("here");
14046                            here.fillInStackTrace();
14047                            Slog.d(TAG, "Sending to user " + id + ": "
14048                                    + intent.toShortString(false, true, false, false)
14049                                    + " " + intent.getExtras(), here);
14050                        }
14051                        am.broadcastIntent(null, intent, null, finishedReceiver,
14052                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14053                                null, finishedReceiver != null, false, id);
14054                    }
14055                } catch (RemoteException ex) {
14056                }
14057            }
14058        });
14059    }
14060
14061    /**
14062     * Check if the external storage media is available. This is true if there
14063     * is a mounted external storage medium or if the external storage is
14064     * emulated.
14065     */
14066    private boolean isExternalMediaAvailable() {
14067        return mMediaMounted || Environment.isExternalStorageEmulated();
14068    }
14069
14070    @Override
14071    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14072        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14073            return null;
14074        }
14075        // writer
14076        synchronized (mPackages) {
14077            if (!isExternalMediaAvailable()) {
14078                // If the external storage is no longer mounted at this point,
14079                // the caller may not have been able to delete all of this
14080                // packages files and can not delete any more.  Bail.
14081                return null;
14082            }
14083            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14084            if (lastPackage != null) {
14085                pkgs.remove(lastPackage);
14086            }
14087            if (pkgs.size() > 0) {
14088                return pkgs.get(0);
14089            }
14090        }
14091        return null;
14092    }
14093
14094    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14095        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14096                userId, andCode ? 1 : 0, packageName);
14097        if (mSystemReady) {
14098            msg.sendToTarget();
14099        } else {
14100            if (mPostSystemReadyMessages == null) {
14101                mPostSystemReadyMessages = new ArrayList<>();
14102            }
14103            mPostSystemReadyMessages.add(msg);
14104        }
14105    }
14106
14107    void startCleaningPackages() {
14108        // reader
14109        if (!isExternalMediaAvailable()) {
14110            return;
14111        }
14112        synchronized (mPackages) {
14113            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14114                return;
14115            }
14116        }
14117        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14118        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14119        IActivityManager am = ActivityManager.getService();
14120        if (am != null) {
14121            int dcsUid = -1;
14122            synchronized (mPackages) {
14123                if (!mDefaultContainerWhitelisted) {
14124                    mDefaultContainerWhitelisted = true;
14125                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14126                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14127                }
14128            }
14129            try {
14130                if (dcsUid > 0) {
14131                    am.backgroundWhitelistUid(dcsUid);
14132                }
14133                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14134                        UserHandle.USER_SYSTEM);
14135            } catch (RemoteException e) {
14136            }
14137        }
14138    }
14139
14140    @Override
14141    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14142            int installFlags, String installerPackageName, int userId) {
14143        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14144
14145        final int callingUid = Binder.getCallingUid();
14146        enforceCrossUserPermission(callingUid, userId,
14147                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14148
14149        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14150            try {
14151                if (observer != null) {
14152                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14153                }
14154            } catch (RemoteException re) {
14155            }
14156            return;
14157        }
14158
14159        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14160            installFlags |= PackageManager.INSTALL_FROM_ADB;
14161
14162        } else {
14163            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14164            // about installerPackageName.
14165
14166            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14167            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14168        }
14169
14170        UserHandle user;
14171        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14172            user = UserHandle.ALL;
14173        } else {
14174            user = new UserHandle(userId);
14175        }
14176
14177        // Only system components can circumvent runtime permissions when installing.
14178        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14179                && mContext.checkCallingOrSelfPermission(Manifest.permission
14180                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14181            throw new SecurityException("You need the "
14182                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14183                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14184        }
14185
14186        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14187                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14188            throw new IllegalArgumentException(
14189                    "New installs into ASEC containers no longer supported");
14190        }
14191
14192        final File originFile = new File(originPath);
14193        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14194
14195        final Message msg = mHandler.obtainMessage(INIT_COPY);
14196        final VerificationInfo verificationInfo = new VerificationInfo(
14197                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14198        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14199                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14200                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14201                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14202        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14203        msg.obj = params;
14204
14205        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14206                System.identityHashCode(msg.obj));
14207        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14208                System.identityHashCode(msg.obj));
14209
14210        mHandler.sendMessage(msg);
14211    }
14212
14213
14214    /**
14215     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14216     * it is acting on behalf on an enterprise or the user).
14217     *
14218     * Note that the ordering of the conditionals in this method is important. The checks we perform
14219     * are as follows, in this order:
14220     *
14221     * 1) If the install is being performed by a system app, we can trust the app to have set the
14222     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14223     *    what it is.
14224     * 2) If the install is being performed by a device or profile owner app, the install reason
14225     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14226     *    set the install reason correctly. If the app targets an older SDK version where install
14227     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14228     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14229     * 3) In all other cases, the install is being performed by a regular app that is neither part
14230     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14231     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14232     *    set to enterprise policy and if so, change it to unknown instead.
14233     */
14234    private int fixUpInstallReason(String installerPackageName, int installerUid,
14235            int installReason) {
14236        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14237                == PERMISSION_GRANTED) {
14238            // If the install is being performed by a system app, we trust that app to have set the
14239            // install reason correctly.
14240            return installReason;
14241        }
14242
14243        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14244            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14245        if (dpm != null) {
14246            ComponentName owner = null;
14247            try {
14248                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14249                if (owner == null) {
14250                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14251                }
14252            } catch (RemoteException e) {
14253            }
14254            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14255                // If the install is being performed by a device or profile owner, the install
14256                // reason should be enterprise policy.
14257                return PackageManager.INSTALL_REASON_POLICY;
14258            }
14259        }
14260
14261        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14262            // If the install is being performed by a regular app (i.e. neither system app nor
14263            // device or profile owner), we have no reason to believe that the app is acting on
14264            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14265            // change it to unknown instead.
14266            return PackageManager.INSTALL_REASON_UNKNOWN;
14267        }
14268
14269        // If the install is being performed by a regular app and the install reason was set to any
14270        // value but enterprise policy, leave the install reason unchanged.
14271        return installReason;
14272    }
14273
14274    void installStage(String packageName, File stagedDir, String stagedCid,
14275            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14276            String installerPackageName, int installerUid, UserHandle user,
14277            Certificate[][] certificates) {
14278        if (DEBUG_EPHEMERAL) {
14279            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14280                Slog.d(TAG, "Ephemeral install of " + packageName);
14281            }
14282        }
14283        final VerificationInfo verificationInfo = new VerificationInfo(
14284                sessionParams.originatingUri, sessionParams.referrerUri,
14285                sessionParams.originatingUid, installerUid);
14286
14287        final OriginInfo origin;
14288        if (stagedDir != null) {
14289            origin = OriginInfo.fromStagedFile(stagedDir);
14290        } else {
14291            origin = OriginInfo.fromStagedContainer(stagedCid);
14292        }
14293
14294        final Message msg = mHandler.obtainMessage(INIT_COPY);
14295        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14296                sessionParams.installReason);
14297        final InstallParams params = new InstallParams(origin, null, observer,
14298                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14299                verificationInfo, user, sessionParams.abiOverride,
14300                sessionParams.grantedRuntimePermissions, certificates, installReason);
14301        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14302        msg.obj = params;
14303
14304        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14305                System.identityHashCode(msg.obj));
14306        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14307                System.identityHashCode(msg.obj));
14308
14309        mHandler.sendMessage(msg);
14310    }
14311
14312    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14313            int userId) {
14314        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14315        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14316
14317        // Send a session commit broadcast
14318        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14319        info.installReason = pkgSetting.getInstallReason(userId);
14320        info.appPackageName = packageName;
14321        sendSessionCommitBroadcast(info, userId);
14322    }
14323
14324    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14325        if (ArrayUtils.isEmpty(userIds)) {
14326            return;
14327        }
14328        Bundle extras = new Bundle(1);
14329        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14330        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14331
14332        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14333                packageName, extras, 0, null, null, userIds);
14334        if (isSystem) {
14335            mHandler.post(() -> {
14336                        for (int userId : userIds) {
14337                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14338                        }
14339                    }
14340            );
14341        }
14342    }
14343
14344    /**
14345     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14346     * automatically without needing an explicit launch.
14347     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14348     */
14349    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14350        // If user is not running, the app didn't miss any broadcast
14351        if (!mUserManagerInternal.isUserRunning(userId)) {
14352            return;
14353        }
14354        final IActivityManager am = ActivityManager.getService();
14355        try {
14356            // Deliver LOCKED_BOOT_COMPLETED first
14357            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14358                    .setPackage(packageName);
14359            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14360            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14361                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14362
14363            // Deliver BOOT_COMPLETED only if user is unlocked
14364            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14365                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14366                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14367                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14368            }
14369        } catch (RemoteException e) {
14370            throw e.rethrowFromSystemServer();
14371        }
14372    }
14373
14374    @Override
14375    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14376            int userId) {
14377        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14378        PackageSetting pkgSetting;
14379        final int callingUid = Binder.getCallingUid();
14380        enforceCrossUserPermission(callingUid, userId,
14381                true /* requireFullPermission */, true /* checkShell */,
14382                "setApplicationHiddenSetting for user " + userId);
14383
14384        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14385            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14386            return false;
14387        }
14388
14389        long callingId = Binder.clearCallingIdentity();
14390        try {
14391            boolean sendAdded = false;
14392            boolean sendRemoved = false;
14393            // writer
14394            synchronized (mPackages) {
14395                pkgSetting = mSettings.mPackages.get(packageName);
14396                if (pkgSetting == null) {
14397                    return false;
14398                }
14399                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14400                    return false;
14401                }
14402                // Do not allow "android" is being disabled
14403                if ("android".equals(packageName)) {
14404                    Slog.w(TAG, "Cannot hide package: android");
14405                    return false;
14406                }
14407                // Cannot hide static shared libs as they are considered
14408                // a part of the using app (emulating static linking). Also
14409                // static libs are installed always on internal storage.
14410                PackageParser.Package pkg = mPackages.get(packageName);
14411                if (pkg != null && pkg.staticSharedLibName != null) {
14412                    Slog.w(TAG, "Cannot hide package: " + packageName
14413                            + " providing static shared library: "
14414                            + pkg.staticSharedLibName);
14415                    return false;
14416                }
14417                // Only allow protected packages to hide themselves.
14418                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14419                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14420                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14421                    return false;
14422                }
14423
14424                if (pkgSetting.getHidden(userId) != hidden) {
14425                    pkgSetting.setHidden(hidden, userId);
14426                    mSettings.writePackageRestrictionsLPr(userId);
14427                    if (hidden) {
14428                        sendRemoved = true;
14429                    } else {
14430                        sendAdded = true;
14431                    }
14432                }
14433            }
14434            if (sendAdded) {
14435                sendPackageAddedForUser(packageName, pkgSetting, userId);
14436                return true;
14437            }
14438            if (sendRemoved) {
14439                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14440                        "hiding pkg");
14441                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14442                return true;
14443            }
14444        } finally {
14445            Binder.restoreCallingIdentity(callingId);
14446        }
14447        return false;
14448    }
14449
14450    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14451            int userId) {
14452        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14453        info.removedPackage = packageName;
14454        info.installerPackageName = pkgSetting.installerPackageName;
14455        info.removedUsers = new int[] {userId};
14456        info.broadcastUsers = new int[] {userId};
14457        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14458        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14459    }
14460
14461    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14462        if (pkgList.length > 0) {
14463            Bundle extras = new Bundle(1);
14464            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14465
14466            sendPackageBroadcast(
14467                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14468                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14469                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14470                    new int[] {userId});
14471        }
14472    }
14473
14474    /**
14475     * Returns true if application is not found or there was an error. Otherwise it returns
14476     * the hidden state of the package for the given user.
14477     */
14478    @Override
14479    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14480        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14481        final int callingUid = Binder.getCallingUid();
14482        enforceCrossUserPermission(callingUid, userId,
14483                true /* requireFullPermission */, false /* checkShell */,
14484                "getApplicationHidden for user " + userId);
14485        PackageSetting ps;
14486        long callingId = Binder.clearCallingIdentity();
14487        try {
14488            // writer
14489            synchronized (mPackages) {
14490                ps = mSettings.mPackages.get(packageName);
14491                if (ps == null) {
14492                    return true;
14493                }
14494                if (filterAppAccessLPr(ps, callingUid, userId)) {
14495                    return true;
14496                }
14497                return ps.getHidden(userId);
14498            }
14499        } finally {
14500            Binder.restoreCallingIdentity(callingId);
14501        }
14502    }
14503
14504    /**
14505     * @hide
14506     */
14507    @Override
14508    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14509            int installReason) {
14510        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14511                null);
14512        PackageSetting pkgSetting;
14513        final int callingUid = Binder.getCallingUid();
14514        enforceCrossUserPermission(callingUid, userId,
14515                true /* requireFullPermission */, true /* checkShell */,
14516                "installExistingPackage for user " + userId);
14517        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14518            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14519        }
14520
14521        long callingId = Binder.clearCallingIdentity();
14522        try {
14523            boolean installed = false;
14524            final boolean instantApp =
14525                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14526            final boolean fullApp =
14527                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14528
14529            // writer
14530            synchronized (mPackages) {
14531                pkgSetting = mSettings.mPackages.get(packageName);
14532                if (pkgSetting == null) {
14533                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14534                }
14535                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14536                    // only allow the existing package to be used if it's installed as a full
14537                    // application for at least one user
14538                    boolean installAllowed = false;
14539                    for (int checkUserId : sUserManager.getUserIds()) {
14540                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14541                        if (installAllowed) {
14542                            break;
14543                        }
14544                    }
14545                    if (!installAllowed) {
14546                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14547                    }
14548                }
14549                if (!pkgSetting.getInstalled(userId)) {
14550                    pkgSetting.setInstalled(true, userId);
14551                    pkgSetting.setHidden(false, userId);
14552                    pkgSetting.setInstallReason(installReason, userId);
14553                    mSettings.writePackageRestrictionsLPr(userId);
14554                    mSettings.writeKernelMappingLPr(pkgSetting);
14555                    installed = true;
14556                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14557                    // upgrade app from instant to full; we don't allow app downgrade
14558                    installed = true;
14559                }
14560                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14561            }
14562
14563            if (installed) {
14564                if (pkgSetting.pkg != null) {
14565                    synchronized (mInstallLock) {
14566                        // We don't need to freeze for a brand new install
14567                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14568                    }
14569                }
14570                sendPackageAddedForUser(packageName, pkgSetting, userId);
14571                synchronized (mPackages) {
14572                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14573                }
14574            }
14575        } finally {
14576            Binder.restoreCallingIdentity(callingId);
14577        }
14578
14579        return PackageManager.INSTALL_SUCCEEDED;
14580    }
14581
14582    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14583            boolean instantApp, boolean fullApp) {
14584        // no state specified; do nothing
14585        if (!instantApp && !fullApp) {
14586            return;
14587        }
14588        if (userId != UserHandle.USER_ALL) {
14589            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14590                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14591            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14592                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14593            }
14594        } else {
14595            for (int currentUserId : sUserManager.getUserIds()) {
14596                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14597                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14598                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14599                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14600                }
14601            }
14602        }
14603    }
14604
14605    boolean isUserRestricted(int userId, String restrictionKey) {
14606        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14607        if (restrictions.getBoolean(restrictionKey, false)) {
14608            Log.w(TAG, "User is restricted: " + restrictionKey);
14609            return true;
14610        }
14611        return false;
14612    }
14613
14614    @Override
14615    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14616            int userId) {
14617        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14618        final int callingUid = Binder.getCallingUid();
14619        enforceCrossUserPermission(callingUid, userId,
14620                true /* requireFullPermission */, true /* checkShell */,
14621                "setPackagesSuspended for user " + userId);
14622
14623        if (ArrayUtils.isEmpty(packageNames)) {
14624            return packageNames;
14625        }
14626
14627        // List of package names for whom the suspended state has changed.
14628        List<String> changedPackages = new ArrayList<>(packageNames.length);
14629        // List of package names for whom the suspended state is not set as requested in this
14630        // method.
14631        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14632        long callingId = Binder.clearCallingIdentity();
14633        try {
14634            for (int i = 0; i < packageNames.length; i++) {
14635                String packageName = packageNames[i];
14636                boolean changed = false;
14637                final int appId;
14638                synchronized (mPackages) {
14639                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14640                    if (pkgSetting == null
14641                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14642                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14643                                + "\". Skipping suspending/un-suspending.");
14644                        unactionedPackages.add(packageName);
14645                        continue;
14646                    }
14647                    appId = pkgSetting.appId;
14648                    if (pkgSetting.getSuspended(userId) != suspended) {
14649                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14650                            unactionedPackages.add(packageName);
14651                            continue;
14652                        }
14653                        pkgSetting.setSuspended(suspended, userId);
14654                        mSettings.writePackageRestrictionsLPr(userId);
14655                        changed = true;
14656                        changedPackages.add(packageName);
14657                    }
14658                }
14659
14660                if (changed && suspended) {
14661                    killApplication(packageName, UserHandle.getUid(userId, appId),
14662                            "suspending package");
14663                }
14664            }
14665        } finally {
14666            Binder.restoreCallingIdentity(callingId);
14667        }
14668
14669        if (!changedPackages.isEmpty()) {
14670            sendPackagesSuspendedForUser(changedPackages.toArray(
14671                    new String[changedPackages.size()]), userId, suspended);
14672        }
14673
14674        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14675    }
14676
14677    @Override
14678    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14679        final int callingUid = Binder.getCallingUid();
14680        enforceCrossUserPermission(callingUid, userId,
14681                true /* requireFullPermission */, false /* checkShell */,
14682                "isPackageSuspendedForUser for user " + userId);
14683        synchronized (mPackages) {
14684            final PackageSetting ps = mSettings.mPackages.get(packageName);
14685            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14686                throw new IllegalArgumentException("Unknown target package: " + packageName);
14687            }
14688            return ps.getSuspended(userId);
14689        }
14690    }
14691
14692    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14693        if (isPackageDeviceAdmin(packageName, userId)) {
14694            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14695                    + "\": has an active device admin");
14696            return false;
14697        }
14698
14699        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14700        if (packageName.equals(activeLauncherPackageName)) {
14701            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14702                    + "\": contains the active launcher");
14703            return false;
14704        }
14705
14706        if (packageName.equals(mRequiredInstallerPackage)) {
14707            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14708                    + "\": required for package installation");
14709            return false;
14710        }
14711
14712        if (packageName.equals(mRequiredUninstallerPackage)) {
14713            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14714                    + "\": required for package uninstallation");
14715            return false;
14716        }
14717
14718        if (packageName.equals(mRequiredVerifierPackage)) {
14719            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14720                    + "\": required for package verification");
14721            return false;
14722        }
14723
14724        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14725            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14726                    + "\": is the default dialer");
14727            return false;
14728        }
14729
14730        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14731            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14732                    + "\": protected package");
14733            return false;
14734        }
14735
14736        // Cannot suspend static shared libs as they are considered
14737        // a part of the using app (emulating static linking). Also
14738        // static libs are installed always on internal storage.
14739        PackageParser.Package pkg = mPackages.get(packageName);
14740        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14741            Slog.w(TAG, "Cannot suspend package: " + packageName
14742                    + " providing static shared library: "
14743                    + pkg.staticSharedLibName);
14744            return false;
14745        }
14746
14747        return true;
14748    }
14749
14750    private String getActiveLauncherPackageName(int userId) {
14751        Intent intent = new Intent(Intent.ACTION_MAIN);
14752        intent.addCategory(Intent.CATEGORY_HOME);
14753        ResolveInfo resolveInfo = resolveIntent(
14754                intent,
14755                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14756                PackageManager.MATCH_DEFAULT_ONLY,
14757                userId);
14758
14759        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14760    }
14761
14762    private String getDefaultDialerPackageName(int userId) {
14763        synchronized (mPackages) {
14764            return mSettings.getDefaultDialerPackageNameLPw(userId);
14765        }
14766    }
14767
14768    @Override
14769    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14770        mContext.enforceCallingOrSelfPermission(
14771                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14772                "Only package verification agents can verify applications");
14773
14774        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14775        final PackageVerificationResponse response = new PackageVerificationResponse(
14776                verificationCode, Binder.getCallingUid());
14777        msg.arg1 = id;
14778        msg.obj = response;
14779        mHandler.sendMessage(msg);
14780    }
14781
14782    @Override
14783    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14784            long millisecondsToDelay) {
14785        mContext.enforceCallingOrSelfPermission(
14786                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14787                "Only package verification agents can extend verification timeouts");
14788
14789        final PackageVerificationState state = mPendingVerification.get(id);
14790        final PackageVerificationResponse response = new PackageVerificationResponse(
14791                verificationCodeAtTimeout, Binder.getCallingUid());
14792
14793        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14794            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14795        }
14796        if (millisecondsToDelay < 0) {
14797            millisecondsToDelay = 0;
14798        }
14799        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14800                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14801            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14802        }
14803
14804        if ((state != null) && !state.timeoutExtended()) {
14805            state.extendTimeout();
14806
14807            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14808            msg.arg1 = id;
14809            msg.obj = response;
14810            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14811        }
14812    }
14813
14814    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14815            int verificationCode, UserHandle user) {
14816        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14817        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14818        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14819        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14820        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14821
14822        mContext.sendBroadcastAsUser(intent, user,
14823                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14824    }
14825
14826    private ComponentName matchComponentForVerifier(String packageName,
14827            List<ResolveInfo> receivers) {
14828        ActivityInfo targetReceiver = null;
14829
14830        final int NR = receivers.size();
14831        for (int i = 0; i < NR; i++) {
14832            final ResolveInfo info = receivers.get(i);
14833            if (info.activityInfo == null) {
14834                continue;
14835            }
14836
14837            if (packageName.equals(info.activityInfo.packageName)) {
14838                targetReceiver = info.activityInfo;
14839                break;
14840            }
14841        }
14842
14843        if (targetReceiver == null) {
14844            return null;
14845        }
14846
14847        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14848    }
14849
14850    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14851            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14852        if (pkgInfo.verifiers.length == 0) {
14853            return null;
14854        }
14855
14856        final int N = pkgInfo.verifiers.length;
14857        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14858        for (int i = 0; i < N; i++) {
14859            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14860
14861            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14862                    receivers);
14863            if (comp == null) {
14864                continue;
14865            }
14866
14867            final int verifierUid = getUidForVerifier(verifierInfo);
14868            if (verifierUid == -1) {
14869                continue;
14870            }
14871
14872            if (DEBUG_VERIFY) {
14873                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14874                        + " with the correct signature");
14875            }
14876            sufficientVerifiers.add(comp);
14877            verificationState.addSufficientVerifier(verifierUid);
14878        }
14879
14880        return sufficientVerifiers;
14881    }
14882
14883    private int getUidForVerifier(VerifierInfo verifierInfo) {
14884        synchronized (mPackages) {
14885            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14886            if (pkg == null) {
14887                return -1;
14888            } else if (pkg.mSignatures.length != 1) {
14889                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14890                        + " has more than one signature; ignoring");
14891                return -1;
14892            }
14893
14894            /*
14895             * If the public key of the package's signature does not match
14896             * our expected public key, then this is a different package and
14897             * we should skip.
14898             */
14899
14900            final byte[] expectedPublicKey;
14901            try {
14902                final Signature verifierSig = pkg.mSignatures[0];
14903                final PublicKey publicKey = verifierSig.getPublicKey();
14904                expectedPublicKey = publicKey.getEncoded();
14905            } catch (CertificateException e) {
14906                return -1;
14907            }
14908
14909            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14910
14911            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14912                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14913                        + " does not have the expected public key; ignoring");
14914                return -1;
14915            }
14916
14917            return pkg.applicationInfo.uid;
14918        }
14919    }
14920
14921    @Override
14922    public void finishPackageInstall(int token, boolean didLaunch) {
14923        enforceSystemOrRoot("Only the system is allowed to finish installs");
14924
14925        if (DEBUG_INSTALL) {
14926            Slog.v(TAG, "BM finishing package install for " + token);
14927        }
14928        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14929
14930        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14931        mHandler.sendMessage(msg);
14932    }
14933
14934    /**
14935     * Get the verification agent timeout.  Used for both the APK verifier and the
14936     * intent filter verifier.
14937     *
14938     * @return verification timeout in milliseconds
14939     */
14940    private long getVerificationTimeout() {
14941        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14942                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14943                DEFAULT_VERIFICATION_TIMEOUT);
14944    }
14945
14946    /**
14947     * Get the default verification agent response code.
14948     *
14949     * @return default verification response code
14950     */
14951    private int getDefaultVerificationResponse(UserHandle user) {
14952        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14953            return PackageManager.VERIFICATION_REJECT;
14954        }
14955        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14956                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14957                DEFAULT_VERIFICATION_RESPONSE);
14958    }
14959
14960    /**
14961     * Check whether or not package verification has been enabled.
14962     *
14963     * @return true if verification should be performed
14964     */
14965    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14966        if (!DEFAULT_VERIFY_ENABLE) {
14967            return false;
14968        }
14969
14970        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14971
14972        // Check if installing from ADB
14973        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14974            // Do not run verification in a test harness environment
14975            if (ActivityManager.isRunningInTestHarness()) {
14976                return false;
14977            }
14978            if (ensureVerifyAppsEnabled) {
14979                return true;
14980            }
14981            // Check if the developer does not want package verification for ADB installs
14982            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14983                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14984                return false;
14985            }
14986        } else {
14987            // only when not installed from ADB, skip verification for instant apps when
14988            // the installer and verifier are the same.
14989            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14990                if (mInstantAppInstallerActivity != null
14991                        && mInstantAppInstallerActivity.packageName.equals(
14992                                mRequiredVerifierPackage)) {
14993                    try {
14994                        mContext.getSystemService(AppOpsManager.class)
14995                                .checkPackage(installerUid, mRequiredVerifierPackage);
14996                        if (DEBUG_VERIFY) {
14997                            Slog.i(TAG, "disable verification for instant app");
14998                        }
14999                        return false;
15000                    } catch (SecurityException ignore) { }
15001                }
15002            }
15003        }
15004
15005        if (ensureVerifyAppsEnabled) {
15006            return true;
15007        }
15008
15009        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15010                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15011    }
15012
15013    @Override
15014    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15015            throws RemoteException {
15016        mContext.enforceCallingOrSelfPermission(
15017                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15018                "Only intentfilter verification agents can verify applications");
15019
15020        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15021        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15022                Binder.getCallingUid(), verificationCode, failedDomains);
15023        msg.arg1 = id;
15024        msg.obj = response;
15025        mHandler.sendMessage(msg);
15026    }
15027
15028    @Override
15029    public int getIntentVerificationStatus(String packageName, int userId) {
15030        final int callingUid = Binder.getCallingUid();
15031        if (getInstantAppPackageName(callingUid) != null) {
15032            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15033        }
15034        synchronized (mPackages) {
15035            final PackageSetting ps = mSettings.mPackages.get(packageName);
15036            if (ps == null
15037                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15038                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15039            }
15040            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15041        }
15042    }
15043
15044    @Override
15045    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15046        mContext.enforceCallingOrSelfPermission(
15047                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15048
15049        boolean result = false;
15050        synchronized (mPackages) {
15051            final PackageSetting ps = mSettings.mPackages.get(packageName);
15052            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15053                return false;
15054            }
15055            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15056        }
15057        if (result) {
15058            scheduleWritePackageRestrictionsLocked(userId);
15059        }
15060        return result;
15061    }
15062
15063    @Override
15064    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15065            String packageName) {
15066        final int callingUid = Binder.getCallingUid();
15067        if (getInstantAppPackageName(callingUid) != null) {
15068            return ParceledListSlice.emptyList();
15069        }
15070        synchronized (mPackages) {
15071            final PackageSetting ps = mSettings.mPackages.get(packageName);
15072            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15073                return ParceledListSlice.emptyList();
15074            }
15075            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15076        }
15077    }
15078
15079    @Override
15080    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15081        if (TextUtils.isEmpty(packageName)) {
15082            return ParceledListSlice.emptyList();
15083        }
15084        final int callingUid = Binder.getCallingUid();
15085        final int callingUserId = UserHandle.getUserId(callingUid);
15086        synchronized (mPackages) {
15087            PackageParser.Package pkg = mPackages.get(packageName);
15088            if (pkg == null || pkg.activities == null) {
15089                return ParceledListSlice.emptyList();
15090            }
15091            if (pkg.mExtras == null) {
15092                return ParceledListSlice.emptyList();
15093            }
15094            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15095            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15096                return ParceledListSlice.emptyList();
15097            }
15098            final int count = pkg.activities.size();
15099            ArrayList<IntentFilter> result = new ArrayList<>();
15100            for (int n=0; n<count; n++) {
15101                PackageParser.Activity activity = pkg.activities.get(n);
15102                if (activity.intents != null && activity.intents.size() > 0) {
15103                    result.addAll(activity.intents);
15104                }
15105            }
15106            return new ParceledListSlice<>(result);
15107        }
15108    }
15109
15110    @Override
15111    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15112        mContext.enforceCallingOrSelfPermission(
15113                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15114
15115        synchronized (mPackages) {
15116            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15117            if (packageName != null) {
15118                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15119                        packageName, userId);
15120            }
15121            return result;
15122        }
15123    }
15124
15125    @Override
15126    public String getDefaultBrowserPackageName(int userId) {
15127        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15128            return null;
15129        }
15130        synchronized (mPackages) {
15131            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15132        }
15133    }
15134
15135    /**
15136     * Get the "allow unknown sources" setting.
15137     *
15138     * @return the current "allow unknown sources" setting
15139     */
15140    private int getUnknownSourcesSettings() {
15141        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15142                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15143                -1);
15144    }
15145
15146    @Override
15147    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15148        final int callingUid = Binder.getCallingUid();
15149        if (getInstantAppPackageName(callingUid) != null) {
15150            return;
15151        }
15152        // writer
15153        synchronized (mPackages) {
15154            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15155            if (targetPackageSetting == null
15156                    || filterAppAccessLPr(
15157                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15158                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15159            }
15160
15161            PackageSetting installerPackageSetting;
15162            if (installerPackageName != null) {
15163                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15164                if (installerPackageSetting == null) {
15165                    throw new IllegalArgumentException("Unknown installer package: "
15166                            + installerPackageName);
15167                }
15168            } else {
15169                installerPackageSetting = null;
15170            }
15171
15172            Signature[] callerSignature;
15173            Object obj = mSettings.getUserIdLPr(callingUid);
15174            if (obj != null) {
15175                if (obj instanceof SharedUserSetting) {
15176                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15177                } else if (obj instanceof PackageSetting) {
15178                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15179                } else {
15180                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15181                }
15182            } else {
15183                throw new SecurityException("Unknown calling UID: " + callingUid);
15184            }
15185
15186            // Verify: can't set installerPackageName to a package that is
15187            // not signed with the same cert as the caller.
15188            if (installerPackageSetting != null) {
15189                if (compareSignatures(callerSignature,
15190                        installerPackageSetting.signatures.mSignatures)
15191                        != PackageManager.SIGNATURE_MATCH) {
15192                    throw new SecurityException(
15193                            "Caller does not have same cert as new installer package "
15194                            + installerPackageName);
15195                }
15196            }
15197
15198            // Verify: if target already has an installer package, it must
15199            // be signed with the same cert as the caller.
15200            if (targetPackageSetting.installerPackageName != null) {
15201                PackageSetting setting = mSettings.mPackages.get(
15202                        targetPackageSetting.installerPackageName);
15203                // If the currently set package isn't valid, then it's always
15204                // okay to change it.
15205                if (setting != null) {
15206                    if (compareSignatures(callerSignature,
15207                            setting.signatures.mSignatures)
15208                            != PackageManager.SIGNATURE_MATCH) {
15209                        throw new SecurityException(
15210                                "Caller does not have same cert as old installer package "
15211                                + targetPackageSetting.installerPackageName);
15212                    }
15213                }
15214            }
15215
15216            // Okay!
15217            targetPackageSetting.installerPackageName = installerPackageName;
15218            if (installerPackageName != null) {
15219                mSettings.mInstallerPackages.add(installerPackageName);
15220            }
15221            scheduleWriteSettingsLocked();
15222        }
15223    }
15224
15225    @Override
15226    public void setApplicationCategoryHint(String packageName, int categoryHint,
15227            String callerPackageName) {
15228        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15229            throw new SecurityException("Instant applications don't have access to this method");
15230        }
15231        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15232                callerPackageName);
15233        synchronized (mPackages) {
15234            PackageSetting ps = mSettings.mPackages.get(packageName);
15235            if (ps == null) {
15236                throw new IllegalArgumentException("Unknown target package " + packageName);
15237            }
15238            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15239                throw new IllegalArgumentException("Unknown target package " + packageName);
15240            }
15241            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15242                throw new IllegalArgumentException("Calling package " + callerPackageName
15243                        + " is not installer for " + packageName);
15244            }
15245
15246            if (ps.categoryHint != categoryHint) {
15247                ps.categoryHint = categoryHint;
15248                scheduleWriteSettingsLocked();
15249            }
15250        }
15251    }
15252
15253    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15254        // Queue up an async operation since the package installation may take a little while.
15255        mHandler.post(new Runnable() {
15256            public void run() {
15257                mHandler.removeCallbacks(this);
15258                 // Result object to be returned
15259                PackageInstalledInfo res = new PackageInstalledInfo();
15260                res.setReturnCode(currentStatus);
15261                res.uid = -1;
15262                res.pkg = null;
15263                res.removedInfo = null;
15264                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15265                    args.doPreInstall(res.returnCode);
15266                    synchronized (mInstallLock) {
15267                        installPackageTracedLI(args, res);
15268                    }
15269                    args.doPostInstall(res.returnCode, res.uid);
15270                }
15271
15272                // A restore should be performed at this point if (a) the install
15273                // succeeded, (b) the operation is not an update, and (c) the new
15274                // package has not opted out of backup participation.
15275                final boolean update = res.removedInfo != null
15276                        && res.removedInfo.removedPackage != null;
15277                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15278                boolean doRestore = !update
15279                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15280
15281                // Set up the post-install work request bookkeeping.  This will be used
15282                // and cleaned up by the post-install event handling regardless of whether
15283                // there's a restore pass performed.  Token values are >= 1.
15284                int token;
15285                if (mNextInstallToken < 0) mNextInstallToken = 1;
15286                token = mNextInstallToken++;
15287
15288                PostInstallData data = new PostInstallData(args, res);
15289                mRunningInstalls.put(token, data);
15290                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15291
15292                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15293                    // Pass responsibility to the Backup Manager.  It will perform a
15294                    // restore if appropriate, then pass responsibility back to the
15295                    // Package Manager to run the post-install observer callbacks
15296                    // and broadcasts.
15297                    IBackupManager bm = IBackupManager.Stub.asInterface(
15298                            ServiceManager.getService(Context.BACKUP_SERVICE));
15299                    if (bm != null) {
15300                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15301                                + " to BM for possible restore");
15302                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15303                        try {
15304                            // TODO: http://b/22388012
15305                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15306                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15307                            } else {
15308                                doRestore = false;
15309                            }
15310                        } catch (RemoteException e) {
15311                            // can't happen; the backup manager is local
15312                        } catch (Exception e) {
15313                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15314                            doRestore = false;
15315                        }
15316                    } else {
15317                        Slog.e(TAG, "Backup Manager not found!");
15318                        doRestore = false;
15319                    }
15320                }
15321
15322                if (!doRestore) {
15323                    // No restore possible, or the Backup Manager was mysteriously not
15324                    // available -- just fire the post-install work request directly.
15325                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15326
15327                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15328
15329                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15330                    mHandler.sendMessage(msg);
15331                }
15332            }
15333        });
15334    }
15335
15336    /**
15337     * Callback from PackageSettings whenever an app is first transitioned out of the
15338     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15339     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15340     * here whether the app is the target of an ongoing install, and only send the
15341     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15342     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15343     * handling.
15344     */
15345    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15346        // Serialize this with the rest of the install-process message chain.  In the
15347        // restore-at-install case, this Runnable will necessarily run before the
15348        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15349        // are coherent.  In the non-restore case, the app has already completed install
15350        // and been launched through some other means, so it is not in a problematic
15351        // state for observers to see the FIRST_LAUNCH signal.
15352        mHandler.post(new Runnable() {
15353            @Override
15354            public void run() {
15355                for (int i = 0; i < mRunningInstalls.size(); i++) {
15356                    final PostInstallData data = mRunningInstalls.valueAt(i);
15357                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15358                        continue;
15359                    }
15360                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15361                        // right package; but is it for the right user?
15362                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15363                            if (userId == data.res.newUsers[uIndex]) {
15364                                if (DEBUG_BACKUP) {
15365                                    Slog.i(TAG, "Package " + pkgName
15366                                            + " being restored so deferring FIRST_LAUNCH");
15367                                }
15368                                return;
15369                            }
15370                        }
15371                    }
15372                }
15373                // didn't find it, so not being restored
15374                if (DEBUG_BACKUP) {
15375                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15376                }
15377                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15378            }
15379        });
15380    }
15381
15382    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15383        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15384                installerPkg, null, userIds);
15385    }
15386
15387    private abstract class HandlerParams {
15388        private static final int MAX_RETRIES = 4;
15389
15390        /**
15391         * Number of times startCopy() has been attempted and had a non-fatal
15392         * error.
15393         */
15394        private int mRetries = 0;
15395
15396        /** User handle for the user requesting the information or installation. */
15397        private final UserHandle mUser;
15398        String traceMethod;
15399        int traceCookie;
15400
15401        HandlerParams(UserHandle user) {
15402            mUser = user;
15403        }
15404
15405        UserHandle getUser() {
15406            return mUser;
15407        }
15408
15409        HandlerParams setTraceMethod(String traceMethod) {
15410            this.traceMethod = traceMethod;
15411            return this;
15412        }
15413
15414        HandlerParams setTraceCookie(int traceCookie) {
15415            this.traceCookie = traceCookie;
15416            return this;
15417        }
15418
15419        final boolean startCopy() {
15420            boolean res;
15421            try {
15422                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15423
15424                if (++mRetries > MAX_RETRIES) {
15425                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15426                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15427                    handleServiceError();
15428                    return false;
15429                } else {
15430                    handleStartCopy();
15431                    res = true;
15432                }
15433            } catch (RemoteException e) {
15434                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15435                mHandler.sendEmptyMessage(MCS_RECONNECT);
15436                res = false;
15437            }
15438            handleReturnCode();
15439            return res;
15440        }
15441
15442        final void serviceError() {
15443            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15444            handleServiceError();
15445            handleReturnCode();
15446        }
15447
15448        abstract void handleStartCopy() throws RemoteException;
15449        abstract void handleServiceError();
15450        abstract void handleReturnCode();
15451    }
15452
15453    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15454        for (File path : paths) {
15455            try {
15456                mcs.clearDirectory(path.getAbsolutePath());
15457            } catch (RemoteException e) {
15458            }
15459        }
15460    }
15461
15462    static class OriginInfo {
15463        /**
15464         * Location where install is coming from, before it has been
15465         * copied/renamed into place. This could be a single monolithic APK
15466         * file, or a cluster directory. This location may be untrusted.
15467         */
15468        final File file;
15469        final String cid;
15470
15471        /**
15472         * Flag indicating that {@link #file} or {@link #cid} has already been
15473         * staged, meaning downstream users don't need to defensively copy the
15474         * contents.
15475         */
15476        final boolean staged;
15477
15478        /**
15479         * Flag indicating that {@link #file} or {@link #cid} is an already
15480         * installed app that is being moved.
15481         */
15482        final boolean existing;
15483
15484        final String resolvedPath;
15485        final File resolvedFile;
15486
15487        static OriginInfo fromNothing() {
15488            return new OriginInfo(null, null, false, false);
15489        }
15490
15491        static OriginInfo fromUntrustedFile(File file) {
15492            return new OriginInfo(file, null, false, false);
15493        }
15494
15495        static OriginInfo fromExistingFile(File file) {
15496            return new OriginInfo(file, null, false, true);
15497        }
15498
15499        static OriginInfo fromStagedFile(File file) {
15500            return new OriginInfo(file, null, true, false);
15501        }
15502
15503        static OriginInfo fromStagedContainer(String cid) {
15504            return new OriginInfo(null, cid, true, false);
15505        }
15506
15507        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15508            this.file = file;
15509            this.cid = cid;
15510            this.staged = staged;
15511            this.existing = existing;
15512
15513            if (cid != null) {
15514                resolvedPath = PackageHelper.getSdDir(cid);
15515                resolvedFile = new File(resolvedPath);
15516            } else if (file != null) {
15517                resolvedPath = file.getAbsolutePath();
15518                resolvedFile = file;
15519            } else {
15520                resolvedPath = null;
15521                resolvedFile = null;
15522            }
15523        }
15524    }
15525
15526    static class MoveInfo {
15527        final int moveId;
15528        final String fromUuid;
15529        final String toUuid;
15530        final String packageName;
15531        final String dataAppName;
15532        final int appId;
15533        final String seinfo;
15534        final int targetSdkVersion;
15535
15536        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15537                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15538            this.moveId = moveId;
15539            this.fromUuid = fromUuid;
15540            this.toUuid = toUuid;
15541            this.packageName = packageName;
15542            this.dataAppName = dataAppName;
15543            this.appId = appId;
15544            this.seinfo = seinfo;
15545            this.targetSdkVersion = targetSdkVersion;
15546        }
15547    }
15548
15549    static class VerificationInfo {
15550        /** A constant used to indicate that a uid value is not present. */
15551        public static final int NO_UID = -1;
15552
15553        /** URI referencing where the package was downloaded from. */
15554        final Uri originatingUri;
15555
15556        /** HTTP referrer URI associated with the originatingURI. */
15557        final Uri referrer;
15558
15559        /** UID of the application that the install request originated from. */
15560        final int originatingUid;
15561
15562        /** UID of application requesting the install */
15563        final int installerUid;
15564
15565        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15566            this.originatingUri = originatingUri;
15567            this.referrer = referrer;
15568            this.originatingUid = originatingUid;
15569            this.installerUid = installerUid;
15570        }
15571    }
15572
15573    class InstallParams extends HandlerParams {
15574        final OriginInfo origin;
15575        final MoveInfo move;
15576        final IPackageInstallObserver2 observer;
15577        int installFlags;
15578        final String installerPackageName;
15579        final String volumeUuid;
15580        private InstallArgs mArgs;
15581        private int mRet;
15582        final String packageAbiOverride;
15583        final String[] grantedRuntimePermissions;
15584        final VerificationInfo verificationInfo;
15585        final Certificate[][] certificates;
15586        final int installReason;
15587
15588        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15589                int installFlags, String installerPackageName, String volumeUuid,
15590                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15591                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15592            super(user);
15593            this.origin = origin;
15594            this.move = move;
15595            this.observer = observer;
15596            this.installFlags = installFlags;
15597            this.installerPackageName = installerPackageName;
15598            this.volumeUuid = volumeUuid;
15599            this.verificationInfo = verificationInfo;
15600            this.packageAbiOverride = packageAbiOverride;
15601            this.grantedRuntimePermissions = grantedPermissions;
15602            this.certificates = certificates;
15603            this.installReason = installReason;
15604        }
15605
15606        @Override
15607        public String toString() {
15608            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15609                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15610        }
15611
15612        private int installLocationPolicy(PackageInfoLite pkgLite) {
15613            String packageName = pkgLite.packageName;
15614            int installLocation = pkgLite.installLocation;
15615            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15616            // reader
15617            synchronized (mPackages) {
15618                // Currently installed package which the new package is attempting to replace or
15619                // null if no such package is installed.
15620                PackageParser.Package installedPkg = mPackages.get(packageName);
15621                // Package which currently owns the data which the new package will own if installed.
15622                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15623                // will be null whereas dataOwnerPkg will contain information about the package
15624                // which was uninstalled while keeping its data.
15625                PackageParser.Package dataOwnerPkg = installedPkg;
15626                if (dataOwnerPkg  == null) {
15627                    PackageSetting ps = mSettings.mPackages.get(packageName);
15628                    if (ps != null) {
15629                        dataOwnerPkg = ps.pkg;
15630                    }
15631                }
15632
15633                if (dataOwnerPkg != null) {
15634                    // If installed, the package will get access to data left on the device by its
15635                    // predecessor. As a security measure, this is permited only if this is not a
15636                    // version downgrade or if the predecessor package is marked as debuggable and
15637                    // a downgrade is explicitly requested.
15638                    //
15639                    // On debuggable platform builds, downgrades are permitted even for
15640                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15641                    // not offer security guarantees and thus it's OK to disable some security
15642                    // mechanisms to make debugging/testing easier on those builds. However, even on
15643                    // debuggable builds downgrades of packages are permitted only if requested via
15644                    // installFlags. This is because we aim to keep the behavior of debuggable
15645                    // platform builds as close as possible to the behavior of non-debuggable
15646                    // platform builds.
15647                    final boolean downgradeRequested =
15648                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15649                    final boolean packageDebuggable =
15650                                (dataOwnerPkg.applicationInfo.flags
15651                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15652                    final boolean downgradePermitted =
15653                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15654                    if (!downgradePermitted) {
15655                        try {
15656                            checkDowngrade(dataOwnerPkg, pkgLite);
15657                        } catch (PackageManagerException e) {
15658                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15659                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15660                        }
15661                    }
15662                }
15663
15664                if (installedPkg != null) {
15665                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15666                        // Check for updated system application.
15667                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15668                            if (onSd) {
15669                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15670                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15671                            }
15672                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15673                        } else {
15674                            if (onSd) {
15675                                // Install flag overrides everything.
15676                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15677                            }
15678                            // If current upgrade specifies particular preference
15679                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15680                                // Application explicitly specified internal.
15681                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15682                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15683                                // App explictly prefers external. Let policy decide
15684                            } else {
15685                                // Prefer previous location
15686                                if (isExternal(installedPkg)) {
15687                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15688                                }
15689                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15690                            }
15691                        }
15692                    } else {
15693                        // Invalid install. Return error code
15694                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15695                    }
15696                }
15697            }
15698            // All the special cases have been taken care of.
15699            // Return result based on recommended install location.
15700            if (onSd) {
15701                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15702            }
15703            return pkgLite.recommendedInstallLocation;
15704        }
15705
15706        /*
15707         * Invoke remote method to get package information and install
15708         * location values. Override install location based on default
15709         * policy if needed and then create install arguments based
15710         * on the install location.
15711         */
15712        public void handleStartCopy() throws RemoteException {
15713            int ret = PackageManager.INSTALL_SUCCEEDED;
15714
15715            // If we're already staged, we've firmly committed to an install location
15716            if (origin.staged) {
15717                if (origin.file != null) {
15718                    installFlags |= PackageManager.INSTALL_INTERNAL;
15719                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15720                } else if (origin.cid != null) {
15721                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15722                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15723                } else {
15724                    throw new IllegalStateException("Invalid stage location");
15725                }
15726            }
15727
15728            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15729            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15730            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15731            PackageInfoLite pkgLite = null;
15732
15733            if (onInt && onSd) {
15734                // Check if both bits are set.
15735                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15736                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15737            } else if (onSd && ephemeral) {
15738                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15739                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15740            } else {
15741                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15742                        packageAbiOverride);
15743
15744                if (DEBUG_EPHEMERAL && ephemeral) {
15745                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15746                }
15747
15748                /*
15749                 * If we have too little free space, try to free cache
15750                 * before giving up.
15751                 */
15752                if (!origin.staged && pkgLite.recommendedInstallLocation
15753                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15754                    // TODO: focus freeing disk space on the target device
15755                    final StorageManager storage = StorageManager.from(mContext);
15756                    final long lowThreshold = storage.getStorageLowBytes(
15757                            Environment.getDataDirectory());
15758
15759                    final long sizeBytes = mContainerService.calculateInstalledSize(
15760                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15761
15762                    try {
15763                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15764                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15765                                installFlags, packageAbiOverride);
15766                    } catch (InstallerException e) {
15767                        Slog.w(TAG, "Failed to free cache", e);
15768                    }
15769
15770                    /*
15771                     * The cache free must have deleted the file we
15772                     * downloaded to install.
15773                     *
15774                     * TODO: fix the "freeCache" call to not delete
15775                     *       the file we care about.
15776                     */
15777                    if (pkgLite.recommendedInstallLocation
15778                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15779                        pkgLite.recommendedInstallLocation
15780                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15781                    }
15782                }
15783            }
15784
15785            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15786                int loc = pkgLite.recommendedInstallLocation;
15787                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15788                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15789                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15790                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15791                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15792                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15793                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15794                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15795                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15796                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15797                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15798                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15799                } else {
15800                    // Override with defaults if needed.
15801                    loc = installLocationPolicy(pkgLite);
15802                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15803                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15804                    } else if (!onSd && !onInt) {
15805                        // Override install location with flags
15806                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15807                            // Set the flag to install on external media.
15808                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15809                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15810                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15811                            if (DEBUG_EPHEMERAL) {
15812                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15813                            }
15814                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15815                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15816                                    |PackageManager.INSTALL_INTERNAL);
15817                        } else {
15818                            // Make sure the flag for installing on external
15819                            // media is unset
15820                            installFlags |= PackageManager.INSTALL_INTERNAL;
15821                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15822                        }
15823                    }
15824                }
15825            }
15826
15827            final InstallArgs args = createInstallArgs(this);
15828            mArgs = args;
15829
15830            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15831                // TODO: http://b/22976637
15832                // Apps installed for "all" users use the device owner to verify the app
15833                UserHandle verifierUser = getUser();
15834                if (verifierUser == UserHandle.ALL) {
15835                    verifierUser = UserHandle.SYSTEM;
15836                }
15837
15838                /*
15839                 * Determine if we have any installed package verifiers. If we
15840                 * do, then we'll defer to them to verify the packages.
15841                 */
15842                final int requiredUid = mRequiredVerifierPackage == null ? -1
15843                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15844                                verifierUser.getIdentifier());
15845                final int installerUid =
15846                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15847                if (!origin.existing && requiredUid != -1
15848                        && isVerificationEnabled(
15849                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15850                    final Intent verification = new Intent(
15851                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15852                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15853                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15854                            PACKAGE_MIME_TYPE);
15855                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15856
15857                    // Query all live verifiers based on current user state
15858                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15859                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15860
15861                    if (DEBUG_VERIFY) {
15862                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15863                                + verification.toString() + " with " + pkgLite.verifiers.length
15864                                + " optional verifiers");
15865                    }
15866
15867                    final int verificationId = mPendingVerificationToken++;
15868
15869                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15870
15871                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15872                            installerPackageName);
15873
15874                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15875                            installFlags);
15876
15877                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15878                            pkgLite.packageName);
15879
15880                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15881                            pkgLite.versionCode);
15882
15883                    if (verificationInfo != null) {
15884                        if (verificationInfo.originatingUri != null) {
15885                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15886                                    verificationInfo.originatingUri);
15887                        }
15888                        if (verificationInfo.referrer != null) {
15889                            verification.putExtra(Intent.EXTRA_REFERRER,
15890                                    verificationInfo.referrer);
15891                        }
15892                        if (verificationInfo.originatingUid >= 0) {
15893                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15894                                    verificationInfo.originatingUid);
15895                        }
15896                        if (verificationInfo.installerUid >= 0) {
15897                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15898                                    verificationInfo.installerUid);
15899                        }
15900                    }
15901
15902                    final PackageVerificationState verificationState = new PackageVerificationState(
15903                            requiredUid, args);
15904
15905                    mPendingVerification.append(verificationId, verificationState);
15906
15907                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15908                            receivers, verificationState);
15909
15910                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15911                    final long idleDuration = getVerificationTimeout();
15912
15913                    /*
15914                     * If any sufficient verifiers were listed in the package
15915                     * manifest, attempt to ask them.
15916                     */
15917                    if (sufficientVerifiers != null) {
15918                        final int N = sufficientVerifiers.size();
15919                        if (N == 0) {
15920                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15921                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15922                        } else {
15923                            for (int i = 0; i < N; i++) {
15924                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15925                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15926                                        verifierComponent.getPackageName(), idleDuration,
15927                                        verifierUser.getIdentifier(), false, "package verifier");
15928
15929                                final Intent sufficientIntent = new Intent(verification);
15930                                sufficientIntent.setComponent(verifierComponent);
15931                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15932                            }
15933                        }
15934                    }
15935
15936                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15937                            mRequiredVerifierPackage, receivers);
15938                    if (ret == PackageManager.INSTALL_SUCCEEDED
15939                            && mRequiredVerifierPackage != null) {
15940                        Trace.asyncTraceBegin(
15941                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15942                        /*
15943                         * Send the intent to the required verification agent,
15944                         * but only start the verification timeout after the
15945                         * target BroadcastReceivers have run.
15946                         */
15947                        verification.setComponent(requiredVerifierComponent);
15948                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15949                                mRequiredVerifierPackage, idleDuration,
15950                                verifierUser.getIdentifier(), false, "package verifier");
15951                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15952                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15953                                new BroadcastReceiver() {
15954                                    @Override
15955                                    public void onReceive(Context context, Intent intent) {
15956                                        final Message msg = mHandler
15957                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15958                                        msg.arg1 = verificationId;
15959                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15960                                    }
15961                                }, null, 0, null, null);
15962
15963                        /*
15964                         * We don't want the copy to proceed until verification
15965                         * succeeds, so null out this field.
15966                         */
15967                        mArgs = null;
15968                    }
15969                } else {
15970                    /*
15971                     * No package verification is enabled, so immediately start
15972                     * the remote call to initiate copy using temporary file.
15973                     */
15974                    ret = args.copyApk(mContainerService, true);
15975                }
15976            }
15977
15978            mRet = ret;
15979        }
15980
15981        @Override
15982        void handleReturnCode() {
15983            // If mArgs is null, then MCS couldn't be reached. When it
15984            // reconnects, it will try again to install. At that point, this
15985            // will succeed.
15986            if (mArgs != null) {
15987                processPendingInstall(mArgs, mRet);
15988            }
15989        }
15990
15991        @Override
15992        void handleServiceError() {
15993            mArgs = createInstallArgs(this);
15994            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15995        }
15996
15997        public boolean isForwardLocked() {
15998            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15999        }
16000    }
16001
16002    /**
16003     * Used during creation of InstallArgs
16004     *
16005     * @param installFlags package installation flags
16006     * @return true if should be installed on external storage
16007     */
16008    private static boolean installOnExternalAsec(int installFlags) {
16009        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16010            return false;
16011        }
16012        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16013            return true;
16014        }
16015        return false;
16016    }
16017
16018    /**
16019     * Used during creation of InstallArgs
16020     *
16021     * @param installFlags package installation flags
16022     * @return true if should be installed as forward locked
16023     */
16024    private static boolean installForwardLocked(int installFlags) {
16025        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16026    }
16027
16028    private InstallArgs createInstallArgs(InstallParams params) {
16029        if (params.move != null) {
16030            return new MoveInstallArgs(params);
16031        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16032            return new AsecInstallArgs(params);
16033        } else {
16034            return new FileInstallArgs(params);
16035        }
16036    }
16037
16038    /**
16039     * Create args that describe an existing installed package. Typically used
16040     * when cleaning up old installs, or used as a move source.
16041     */
16042    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16043            String resourcePath, String[] instructionSets) {
16044        final boolean isInAsec;
16045        if (installOnExternalAsec(installFlags)) {
16046            /* Apps on SD card are always in ASEC containers. */
16047            isInAsec = true;
16048        } else if (installForwardLocked(installFlags)
16049                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16050            /*
16051             * Forward-locked apps are only in ASEC containers if they're the
16052             * new style
16053             */
16054            isInAsec = true;
16055        } else {
16056            isInAsec = false;
16057        }
16058
16059        if (isInAsec) {
16060            return new AsecInstallArgs(codePath, instructionSets,
16061                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16062        } else {
16063            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16064        }
16065    }
16066
16067    static abstract class InstallArgs {
16068        /** @see InstallParams#origin */
16069        final OriginInfo origin;
16070        /** @see InstallParams#move */
16071        final MoveInfo move;
16072
16073        final IPackageInstallObserver2 observer;
16074        // Always refers to PackageManager flags only
16075        final int installFlags;
16076        final String installerPackageName;
16077        final String volumeUuid;
16078        final UserHandle user;
16079        final String abiOverride;
16080        final String[] installGrantPermissions;
16081        /** If non-null, drop an async trace when the install completes */
16082        final String traceMethod;
16083        final int traceCookie;
16084        final Certificate[][] certificates;
16085        final int installReason;
16086
16087        // The list of instruction sets supported by this app. This is currently
16088        // only used during the rmdex() phase to clean up resources. We can get rid of this
16089        // if we move dex files under the common app path.
16090        /* nullable */ String[] instructionSets;
16091
16092        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16093                int installFlags, String installerPackageName, String volumeUuid,
16094                UserHandle user, String[] instructionSets,
16095                String abiOverride, String[] installGrantPermissions,
16096                String traceMethod, int traceCookie, Certificate[][] certificates,
16097                int installReason) {
16098            this.origin = origin;
16099            this.move = move;
16100            this.installFlags = installFlags;
16101            this.observer = observer;
16102            this.installerPackageName = installerPackageName;
16103            this.volumeUuid = volumeUuid;
16104            this.user = user;
16105            this.instructionSets = instructionSets;
16106            this.abiOverride = abiOverride;
16107            this.installGrantPermissions = installGrantPermissions;
16108            this.traceMethod = traceMethod;
16109            this.traceCookie = traceCookie;
16110            this.certificates = certificates;
16111            this.installReason = installReason;
16112        }
16113
16114        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16115        abstract int doPreInstall(int status);
16116
16117        /**
16118         * Rename package into final resting place. All paths on the given
16119         * scanned package should be updated to reflect the rename.
16120         */
16121        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16122        abstract int doPostInstall(int status, int uid);
16123
16124        /** @see PackageSettingBase#codePathString */
16125        abstract String getCodePath();
16126        /** @see PackageSettingBase#resourcePathString */
16127        abstract String getResourcePath();
16128
16129        // Need installer lock especially for dex file removal.
16130        abstract void cleanUpResourcesLI();
16131        abstract boolean doPostDeleteLI(boolean delete);
16132
16133        /**
16134         * Called before the source arguments are copied. This is used mostly
16135         * for MoveParams when it needs to read the source file to put it in the
16136         * destination.
16137         */
16138        int doPreCopy() {
16139            return PackageManager.INSTALL_SUCCEEDED;
16140        }
16141
16142        /**
16143         * Called after the source arguments are copied. This is used mostly for
16144         * MoveParams when it needs to read the source file to put it in the
16145         * destination.
16146         */
16147        int doPostCopy(int uid) {
16148            return PackageManager.INSTALL_SUCCEEDED;
16149        }
16150
16151        protected boolean isFwdLocked() {
16152            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16153        }
16154
16155        protected boolean isExternalAsec() {
16156            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16157        }
16158
16159        protected boolean isEphemeral() {
16160            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16161        }
16162
16163        UserHandle getUser() {
16164            return user;
16165        }
16166    }
16167
16168    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16169        if (!allCodePaths.isEmpty()) {
16170            if (instructionSets == null) {
16171                throw new IllegalStateException("instructionSet == null");
16172            }
16173            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16174            for (String codePath : allCodePaths) {
16175                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16176                    try {
16177                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16178                    } catch (InstallerException ignored) {
16179                    }
16180                }
16181            }
16182        }
16183    }
16184
16185    /**
16186     * Logic to handle installation of non-ASEC applications, including copying
16187     * and renaming logic.
16188     */
16189    class FileInstallArgs extends InstallArgs {
16190        private File codeFile;
16191        private File resourceFile;
16192
16193        // Example topology:
16194        // /data/app/com.example/base.apk
16195        // /data/app/com.example/split_foo.apk
16196        // /data/app/com.example/lib/arm/libfoo.so
16197        // /data/app/com.example/lib/arm64/libfoo.so
16198        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16199
16200        /** New install */
16201        FileInstallArgs(InstallParams params) {
16202            super(params.origin, params.move, params.observer, params.installFlags,
16203                    params.installerPackageName, params.volumeUuid,
16204                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16205                    params.grantedRuntimePermissions,
16206                    params.traceMethod, params.traceCookie, params.certificates,
16207                    params.installReason);
16208            if (isFwdLocked()) {
16209                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16210            }
16211        }
16212
16213        /** Existing install */
16214        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16215            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16216                    null, null, null, 0, null /*certificates*/,
16217                    PackageManager.INSTALL_REASON_UNKNOWN);
16218            this.codeFile = (codePath != null) ? new File(codePath) : null;
16219            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16220        }
16221
16222        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16223            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16224            try {
16225                return doCopyApk(imcs, temp);
16226            } finally {
16227                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16228            }
16229        }
16230
16231        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16232            if (origin.staged) {
16233                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16234                codeFile = origin.file;
16235                resourceFile = origin.file;
16236                return PackageManager.INSTALL_SUCCEEDED;
16237            }
16238
16239            try {
16240                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16241                final File tempDir =
16242                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16243                codeFile = tempDir;
16244                resourceFile = tempDir;
16245            } catch (IOException e) {
16246                Slog.w(TAG, "Failed to create copy file: " + e);
16247                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16248            }
16249
16250            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16251                @Override
16252                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16253                    if (!FileUtils.isValidExtFilename(name)) {
16254                        throw new IllegalArgumentException("Invalid filename: " + name);
16255                    }
16256                    try {
16257                        final File file = new File(codeFile, name);
16258                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16259                                O_RDWR | O_CREAT, 0644);
16260                        Os.chmod(file.getAbsolutePath(), 0644);
16261                        return new ParcelFileDescriptor(fd);
16262                    } catch (ErrnoException e) {
16263                        throw new RemoteException("Failed to open: " + e.getMessage());
16264                    }
16265                }
16266            };
16267
16268            int ret = PackageManager.INSTALL_SUCCEEDED;
16269            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16270            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16271                Slog.e(TAG, "Failed to copy package");
16272                return ret;
16273            }
16274
16275            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16276            NativeLibraryHelper.Handle handle = null;
16277            try {
16278                handle = NativeLibraryHelper.Handle.create(codeFile);
16279                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16280                        abiOverride);
16281            } catch (IOException e) {
16282                Slog.e(TAG, "Copying native libraries failed", e);
16283                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16284            } finally {
16285                IoUtils.closeQuietly(handle);
16286            }
16287
16288            return ret;
16289        }
16290
16291        int doPreInstall(int status) {
16292            if (status != PackageManager.INSTALL_SUCCEEDED) {
16293                cleanUp();
16294            }
16295            return status;
16296        }
16297
16298        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16299            if (status != PackageManager.INSTALL_SUCCEEDED) {
16300                cleanUp();
16301                return false;
16302            }
16303
16304            final File targetDir = codeFile.getParentFile();
16305            final File beforeCodeFile = codeFile;
16306            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16307
16308            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16309            try {
16310                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16311            } catch (ErrnoException e) {
16312                Slog.w(TAG, "Failed to rename", e);
16313                return false;
16314            }
16315
16316            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16317                Slog.w(TAG, "Failed to restorecon");
16318                return false;
16319            }
16320
16321            // Reflect the rename internally
16322            codeFile = afterCodeFile;
16323            resourceFile = afterCodeFile;
16324
16325            // Reflect the rename in scanned details
16326            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16327            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16328                    afterCodeFile, pkg.baseCodePath));
16329            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16330                    afterCodeFile, pkg.splitCodePaths));
16331
16332            // Reflect the rename in app info
16333            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16334            pkg.setApplicationInfoCodePath(pkg.codePath);
16335            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16336            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16337            pkg.setApplicationInfoResourcePath(pkg.codePath);
16338            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16339            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16340
16341            return true;
16342        }
16343
16344        int doPostInstall(int status, int uid) {
16345            if (status != PackageManager.INSTALL_SUCCEEDED) {
16346                cleanUp();
16347            }
16348            return status;
16349        }
16350
16351        @Override
16352        String getCodePath() {
16353            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16354        }
16355
16356        @Override
16357        String getResourcePath() {
16358            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16359        }
16360
16361        private boolean cleanUp() {
16362            if (codeFile == null || !codeFile.exists()) {
16363                return false;
16364            }
16365
16366            removeCodePathLI(codeFile);
16367
16368            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16369                resourceFile.delete();
16370            }
16371
16372            return true;
16373        }
16374
16375        void cleanUpResourcesLI() {
16376            // Try enumerating all code paths before deleting
16377            List<String> allCodePaths = Collections.EMPTY_LIST;
16378            if (codeFile != null && codeFile.exists()) {
16379                try {
16380                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16381                    allCodePaths = pkg.getAllCodePaths();
16382                } catch (PackageParserException e) {
16383                    // Ignored; we tried our best
16384                }
16385            }
16386
16387            cleanUp();
16388            removeDexFiles(allCodePaths, instructionSets);
16389        }
16390
16391        boolean doPostDeleteLI(boolean delete) {
16392            // XXX err, shouldn't we respect the delete flag?
16393            cleanUpResourcesLI();
16394            return true;
16395        }
16396    }
16397
16398    private boolean isAsecExternal(String cid) {
16399        final String asecPath = PackageHelper.getSdFilesystem(cid);
16400        return !asecPath.startsWith(mAsecInternalPath);
16401    }
16402
16403    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16404            PackageManagerException {
16405        if (copyRet < 0) {
16406            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16407                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16408                throw new PackageManagerException(copyRet, message);
16409            }
16410        }
16411    }
16412
16413    /**
16414     * Extract the StorageManagerService "container ID" from the full code path of an
16415     * .apk.
16416     */
16417    static String cidFromCodePath(String fullCodePath) {
16418        int eidx = fullCodePath.lastIndexOf("/");
16419        String subStr1 = fullCodePath.substring(0, eidx);
16420        int sidx = subStr1.lastIndexOf("/");
16421        return subStr1.substring(sidx+1, eidx);
16422    }
16423
16424    /**
16425     * Logic to handle installation of ASEC applications, including copying and
16426     * renaming logic.
16427     */
16428    class AsecInstallArgs extends InstallArgs {
16429        static final String RES_FILE_NAME = "pkg.apk";
16430        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16431
16432        String cid;
16433        String packagePath;
16434        String resourcePath;
16435
16436        /** New install */
16437        AsecInstallArgs(InstallParams params) {
16438            super(params.origin, params.move, params.observer, params.installFlags,
16439                    params.installerPackageName, params.volumeUuid,
16440                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16441                    params.grantedRuntimePermissions,
16442                    params.traceMethod, params.traceCookie, params.certificates,
16443                    params.installReason);
16444        }
16445
16446        /** Existing install */
16447        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16448                        boolean isExternal, boolean isForwardLocked) {
16449            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16450                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16451                    instructionSets, null, null, null, 0, null /*certificates*/,
16452                    PackageManager.INSTALL_REASON_UNKNOWN);
16453            // Hackily pretend we're still looking at a full code path
16454            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16455                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16456            }
16457
16458            // Extract cid from fullCodePath
16459            int eidx = fullCodePath.lastIndexOf("/");
16460            String subStr1 = fullCodePath.substring(0, eidx);
16461            int sidx = subStr1.lastIndexOf("/");
16462            cid = subStr1.substring(sidx+1, eidx);
16463            setMountPath(subStr1);
16464        }
16465
16466        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16467            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16468                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16469                    instructionSets, null, null, null, 0, null /*certificates*/,
16470                    PackageManager.INSTALL_REASON_UNKNOWN);
16471            this.cid = cid;
16472            setMountPath(PackageHelper.getSdDir(cid));
16473        }
16474
16475        void createCopyFile() {
16476            cid = mInstallerService.allocateExternalStageCidLegacy();
16477        }
16478
16479        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16480            if (origin.staged && origin.cid != null) {
16481                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16482                cid = origin.cid;
16483                setMountPath(PackageHelper.getSdDir(cid));
16484                return PackageManager.INSTALL_SUCCEEDED;
16485            }
16486
16487            if (temp) {
16488                createCopyFile();
16489            } else {
16490                /*
16491                 * Pre-emptively destroy the container since it's destroyed if
16492                 * copying fails due to it existing anyway.
16493                 */
16494                PackageHelper.destroySdDir(cid);
16495            }
16496
16497            final String newMountPath = imcs.copyPackageToContainer(
16498                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16499                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16500
16501            if (newMountPath != null) {
16502                setMountPath(newMountPath);
16503                return PackageManager.INSTALL_SUCCEEDED;
16504            } else {
16505                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16506            }
16507        }
16508
16509        @Override
16510        String getCodePath() {
16511            return packagePath;
16512        }
16513
16514        @Override
16515        String getResourcePath() {
16516            return resourcePath;
16517        }
16518
16519        int doPreInstall(int status) {
16520            if (status != PackageManager.INSTALL_SUCCEEDED) {
16521                // Destroy container
16522                PackageHelper.destroySdDir(cid);
16523            } else {
16524                boolean mounted = PackageHelper.isContainerMounted(cid);
16525                if (!mounted) {
16526                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16527                            Process.SYSTEM_UID);
16528                    if (newMountPath != null) {
16529                        setMountPath(newMountPath);
16530                    } else {
16531                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16532                    }
16533                }
16534            }
16535            return status;
16536        }
16537
16538        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16539            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16540            String newMountPath = null;
16541            if (PackageHelper.isContainerMounted(cid)) {
16542                // Unmount the container
16543                if (!PackageHelper.unMountSdDir(cid)) {
16544                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16545                    return false;
16546                }
16547            }
16548            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16549                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16550                        " which might be stale. Will try to clean up.");
16551                // Clean up the stale container and proceed to recreate.
16552                if (!PackageHelper.destroySdDir(newCacheId)) {
16553                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16554                    return false;
16555                }
16556                // Successfully cleaned up stale container. Try to rename again.
16557                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16558                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16559                            + " inspite of cleaning it up.");
16560                    return false;
16561                }
16562            }
16563            if (!PackageHelper.isContainerMounted(newCacheId)) {
16564                Slog.w(TAG, "Mounting container " + newCacheId);
16565                newMountPath = PackageHelper.mountSdDir(newCacheId,
16566                        getEncryptKey(), Process.SYSTEM_UID);
16567            } else {
16568                newMountPath = PackageHelper.getSdDir(newCacheId);
16569            }
16570            if (newMountPath == null) {
16571                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16572                return false;
16573            }
16574            Log.i(TAG, "Succesfully renamed " + cid +
16575                    " to " + newCacheId +
16576                    " at new path: " + newMountPath);
16577            cid = newCacheId;
16578
16579            final File beforeCodeFile = new File(packagePath);
16580            setMountPath(newMountPath);
16581            final File afterCodeFile = new File(packagePath);
16582
16583            // Reflect the rename in scanned details
16584            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16585            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16586                    afterCodeFile, pkg.baseCodePath));
16587            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16588                    afterCodeFile, pkg.splitCodePaths));
16589
16590            // Reflect the rename in app info
16591            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16592            pkg.setApplicationInfoCodePath(pkg.codePath);
16593            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16594            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16595            pkg.setApplicationInfoResourcePath(pkg.codePath);
16596            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16597            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16598
16599            return true;
16600        }
16601
16602        private void setMountPath(String mountPath) {
16603            final File mountFile = new File(mountPath);
16604
16605            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16606            if (monolithicFile.exists()) {
16607                packagePath = monolithicFile.getAbsolutePath();
16608                if (isFwdLocked()) {
16609                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16610                } else {
16611                    resourcePath = packagePath;
16612                }
16613            } else {
16614                packagePath = mountFile.getAbsolutePath();
16615                resourcePath = packagePath;
16616            }
16617        }
16618
16619        int doPostInstall(int status, int uid) {
16620            if (status != PackageManager.INSTALL_SUCCEEDED) {
16621                cleanUp();
16622            } else {
16623                final int groupOwner;
16624                final String protectedFile;
16625                if (isFwdLocked()) {
16626                    groupOwner = UserHandle.getSharedAppGid(uid);
16627                    protectedFile = RES_FILE_NAME;
16628                } else {
16629                    groupOwner = -1;
16630                    protectedFile = null;
16631                }
16632
16633                if (uid < Process.FIRST_APPLICATION_UID
16634                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16635                    Slog.e(TAG, "Failed to finalize " + cid);
16636                    PackageHelper.destroySdDir(cid);
16637                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16638                }
16639
16640                boolean mounted = PackageHelper.isContainerMounted(cid);
16641                if (!mounted) {
16642                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16643                }
16644            }
16645            return status;
16646        }
16647
16648        private void cleanUp() {
16649            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16650
16651            // Destroy secure container
16652            PackageHelper.destroySdDir(cid);
16653        }
16654
16655        private List<String> getAllCodePaths() {
16656            final File codeFile = new File(getCodePath());
16657            if (codeFile != null && codeFile.exists()) {
16658                try {
16659                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16660                    return pkg.getAllCodePaths();
16661                } catch (PackageParserException e) {
16662                    // Ignored; we tried our best
16663                }
16664            }
16665            return Collections.EMPTY_LIST;
16666        }
16667
16668        void cleanUpResourcesLI() {
16669            // Enumerate all code paths before deleting
16670            cleanUpResourcesLI(getAllCodePaths());
16671        }
16672
16673        private void cleanUpResourcesLI(List<String> allCodePaths) {
16674            cleanUp();
16675            removeDexFiles(allCodePaths, instructionSets);
16676        }
16677
16678        String getPackageName() {
16679            return getAsecPackageName(cid);
16680        }
16681
16682        boolean doPostDeleteLI(boolean delete) {
16683            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16684            final List<String> allCodePaths = getAllCodePaths();
16685            boolean mounted = PackageHelper.isContainerMounted(cid);
16686            if (mounted) {
16687                // Unmount first
16688                if (PackageHelper.unMountSdDir(cid)) {
16689                    mounted = false;
16690                }
16691            }
16692            if (!mounted && delete) {
16693                cleanUpResourcesLI(allCodePaths);
16694            }
16695            return !mounted;
16696        }
16697
16698        @Override
16699        int doPreCopy() {
16700            if (isFwdLocked()) {
16701                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16702                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16703                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16704                }
16705            }
16706
16707            return PackageManager.INSTALL_SUCCEEDED;
16708        }
16709
16710        @Override
16711        int doPostCopy(int uid) {
16712            if (isFwdLocked()) {
16713                if (uid < Process.FIRST_APPLICATION_UID
16714                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16715                                RES_FILE_NAME)) {
16716                    Slog.e(TAG, "Failed to finalize " + cid);
16717                    PackageHelper.destroySdDir(cid);
16718                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16719                }
16720            }
16721
16722            return PackageManager.INSTALL_SUCCEEDED;
16723        }
16724    }
16725
16726    /**
16727     * Logic to handle movement of existing installed applications.
16728     */
16729    class MoveInstallArgs extends InstallArgs {
16730        private File codeFile;
16731        private File resourceFile;
16732
16733        /** New install */
16734        MoveInstallArgs(InstallParams params) {
16735            super(params.origin, params.move, params.observer, params.installFlags,
16736                    params.installerPackageName, params.volumeUuid,
16737                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16738                    params.grantedRuntimePermissions,
16739                    params.traceMethod, params.traceCookie, params.certificates,
16740                    params.installReason);
16741        }
16742
16743        int copyApk(IMediaContainerService imcs, boolean temp) {
16744            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16745                    + move.fromUuid + " to " + move.toUuid);
16746            synchronized (mInstaller) {
16747                try {
16748                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16749                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16750                } catch (InstallerException e) {
16751                    Slog.w(TAG, "Failed to move app", e);
16752                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16753                }
16754            }
16755
16756            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16757            resourceFile = codeFile;
16758            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16759
16760            return PackageManager.INSTALL_SUCCEEDED;
16761        }
16762
16763        int doPreInstall(int status) {
16764            if (status != PackageManager.INSTALL_SUCCEEDED) {
16765                cleanUp(move.toUuid);
16766            }
16767            return status;
16768        }
16769
16770        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16771            if (status != PackageManager.INSTALL_SUCCEEDED) {
16772                cleanUp(move.toUuid);
16773                return false;
16774            }
16775
16776            // Reflect the move in app info
16777            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16778            pkg.setApplicationInfoCodePath(pkg.codePath);
16779            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16780            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16781            pkg.setApplicationInfoResourcePath(pkg.codePath);
16782            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16783            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16784
16785            return true;
16786        }
16787
16788        int doPostInstall(int status, int uid) {
16789            if (status == PackageManager.INSTALL_SUCCEEDED) {
16790                cleanUp(move.fromUuid);
16791            } else {
16792                cleanUp(move.toUuid);
16793            }
16794            return status;
16795        }
16796
16797        @Override
16798        String getCodePath() {
16799            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16800        }
16801
16802        @Override
16803        String getResourcePath() {
16804            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16805        }
16806
16807        private boolean cleanUp(String volumeUuid) {
16808            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16809                    move.dataAppName);
16810            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16811            final int[] userIds = sUserManager.getUserIds();
16812            synchronized (mInstallLock) {
16813                // Clean up both app data and code
16814                // All package moves are frozen until finished
16815                for (int userId : userIds) {
16816                    try {
16817                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16818                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16819                    } catch (InstallerException e) {
16820                        Slog.w(TAG, String.valueOf(e));
16821                    }
16822                }
16823                removeCodePathLI(codeFile);
16824            }
16825            return true;
16826        }
16827
16828        void cleanUpResourcesLI() {
16829            throw new UnsupportedOperationException();
16830        }
16831
16832        boolean doPostDeleteLI(boolean delete) {
16833            throw new UnsupportedOperationException();
16834        }
16835    }
16836
16837    static String getAsecPackageName(String packageCid) {
16838        int idx = packageCid.lastIndexOf("-");
16839        if (idx == -1) {
16840            return packageCid;
16841        }
16842        return packageCid.substring(0, idx);
16843    }
16844
16845    // Utility method used to create code paths based on package name and available index.
16846    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16847        String idxStr = "";
16848        int idx = 1;
16849        // Fall back to default value of idx=1 if prefix is not
16850        // part of oldCodePath
16851        if (oldCodePath != null) {
16852            String subStr = oldCodePath;
16853            // Drop the suffix right away
16854            if (suffix != null && subStr.endsWith(suffix)) {
16855                subStr = subStr.substring(0, subStr.length() - suffix.length());
16856            }
16857            // If oldCodePath already contains prefix find out the
16858            // ending index to either increment or decrement.
16859            int sidx = subStr.lastIndexOf(prefix);
16860            if (sidx != -1) {
16861                subStr = subStr.substring(sidx + prefix.length());
16862                if (subStr != null) {
16863                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16864                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16865                    }
16866                    try {
16867                        idx = Integer.parseInt(subStr);
16868                        if (idx <= 1) {
16869                            idx++;
16870                        } else {
16871                            idx--;
16872                        }
16873                    } catch(NumberFormatException e) {
16874                    }
16875                }
16876            }
16877        }
16878        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16879        return prefix + idxStr;
16880    }
16881
16882    private File getNextCodePath(File targetDir, String packageName) {
16883        File result;
16884        SecureRandom random = new SecureRandom();
16885        byte[] bytes = new byte[16];
16886        do {
16887            random.nextBytes(bytes);
16888            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16889            result = new File(targetDir, packageName + "-" + suffix);
16890        } while (result.exists());
16891        return result;
16892    }
16893
16894    // Utility method that returns the relative package path with respect
16895    // to the installation directory. Like say for /data/data/com.test-1.apk
16896    // string com.test-1 is returned.
16897    static String deriveCodePathName(String codePath) {
16898        if (codePath == null) {
16899            return null;
16900        }
16901        final File codeFile = new File(codePath);
16902        final String name = codeFile.getName();
16903        if (codeFile.isDirectory()) {
16904            return name;
16905        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16906            final int lastDot = name.lastIndexOf('.');
16907            return name.substring(0, lastDot);
16908        } else {
16909            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16910            return null;
16911        }
16912    }
16913
16914    static class PackageInstalledInfo {
16915        String name;
16916        int uid;
16917        // The set of users that originally had this package installed.
16918        int[] origUsers;
16919        // The set of users that now have this package installed.
16920        int[] newUsers;
16921        PackageParser.Package pkg;
16922        int returnCode;
16923        String returnMsg;
16924        PackageRemovedInfo removedInfo;
16925        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16926
16927        public void setError(int code, String msg) {
16928            setReturnCode(code);
16929            setReturnMessage(msg);
16930            Slog.w(TAG, msg);
16931        }
16932
16933        public void setError(String msg, PackageParserException e) {
16934            setReturnCode(e.error);
16935            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16936            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16937            for (int i = 0; i < childCount; i++) {
16938                addedChildPackages.valueAt(i).setError(msg, e);
16939            }
16940            Slog.w(TAG, msg, e);
16941        }
16942
16943        public void setError(String msg, PackageManagerException e) {
16944            returnCode = e.error;
16945            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16946            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16947            for (int i = 0; i < childCount; i++) {
16948                addedChildPackages.valueAt(i).setError(msg, e);
16949            }
16950            Slog.w(TAG, msg, e);
16951        }
16952
16953        public void setReturnCode(int returnCode) {
16954            this.returnCode = returnCode;
16955            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16956            for (int i = 0; i < childCount; i++) {
16957                addedChildPackages.valueAt(i).returnCode = returnCode;
16958            }
16959        }
16960
16961        private void setReturnMessage(String returnMsg) {
16962            this.returnMsg = returnMsg;
16963            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16964            for (int i = 0; i < childCount; i++) {
16965                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16966            }
16967        }
16968
16969        // In some error cases we want to convey more info back to the observer
16970        String origPackage;
16971        String origPermission;
16972    }
16973
16974    /*
16975     * Install a non-existing package.
16976     */
16977    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16978            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16979            PackageInstalledInfo res, int installReason) {
16980        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16981
16982        // Remember this for later, in case we need to rollback this install
16983        String pkgName = pkg.packageName;
16984
16985        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16986
16987        synchronized(mPackages) {
16988            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16989            if (renamedPackage != null) {
16990                // A package with the same name is already installed, though
16991                // it has been renamed to an older name.  The package we
16992                // are trying to install should be installed as an update to
16993                // the existing one, but that has not been requested, so bail.
16994                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16995                        + " without first uninstalling package running as "
16996                        + renamedPackage);
16997                return;
16998            }
16999            if (mPackages.containsKey(pkgName)) {
17000                // Don't allow installation over an existing package with the same name.
17001                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17002                        + " without first uninstalling.");
17003                return;
17004            }
17005        }
17006
17007        try {
17008            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17009                    System.currentTimeMillis(), user);
17010
17011            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17012
17013            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17014                prepareAppDataAfterInstallLIF(newPackage);
17015
17016            } else {
17017                // Remove package from internal structures, but keep around any
17018                // data that might have already existed
17019                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17020                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17021            }
17022        } catch (PackageManagerException e) {
17023            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17024        }
17025
17026        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17027    }
17028
17029    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17030        // Can't rotate keys during boot or if sharedUser.
17031        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17032                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17033            return false;
17034        }
17035        // app is using upgradeKeySets; make sure all are valid
17036        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17037        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17038        for (int i = 0; i < upgradeKeySets.length; i++) {
17039            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17040                Slog.wtf(TAG, "Package "
17041                         + (oldPs.name != null ? oldPs.name : "<null>")
17042                         + " contains upgrade-key-set reference to unknown key-set: "
17043                         + upgradeKeySets[i]
17044                         + " reverting to signatures check.");
17045                return false;
17046            }
17047        }
17048        return true;
17049    }
17050
17051    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17052        // Upgrade keysets are being used.  Determine if new package has a superset of the
17053        // required keys.
17054        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17055        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17056        for (int i = 0; i < upgradeKeySets.length; i++) {
17057            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17058            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17059                return true;
17060            }
17061        }
17062        return false;
17063    }
17064
17065    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17066        try (DigestInputStream digestStream =
17067                new DigestInputStream(new FileInputStream(file), digest)) {
17068            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17069        }
17070    }
17071
17072    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17073            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17074            int installReason) {
17075        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17076
17077        final PackageParser.Package oldPackage;
17078        final PackageSetting ps;
17079        final String pkgName = pkg.packageName;
17080        final int[] allUsers;
17081        final int[] installedUsers;
17082
17083        synchronized(mPackages) {
17084            oldPackage = mPackages.get(pkgName);
17085            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17086
17087            // don't allow upgrade to target a release SDK from a pre-release SDK
17088            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17089                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17090            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17091                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17092            if (oldTargetsPreRelease
17093                    && !newTargetsPreRelease
17094                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17095                Slog.w(TAG, "Can't install package targeting released sdk");
17096                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17097                return;
17098            }
17099
17100            ps = mSettings.mPackages.get(pkgName);
17101
17102            // verify signatures are valid
17103            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17104                if (!checkUpgradeKeySetLP(ps, pkg)) {
17105                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17106                            "New package not signed by keys specified by upgrade-keysets: "
17107                                    + pkgName);
17108                    return;
17109                }
17110            } else {
17111                // default to original signature matching
17112                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17113                        != PackageManager.SIGNATURE_MATCH) {
17114                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17115                            "New package has a different signature: " + pkgName);
17116                    return;
17117                }
17118            }
17119
17120            // don't allow a system upgrade unless the upgrade hash matches
17121            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17122                byte[] digestBytes = null;
17123                try {
17124                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17125                    updateDigest(digest, new File(pkg.baseCodePath));
17126                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17127                        for (String path : pkg.splitCodePaths) {
17128                            updateDigest(digest, new File(path));
17129                        }
17130                    }
17131                    digestBytes = digest.digest();
17132                } catch (NoSuchAlgorithmException | IOException e) {
17133                    res.setError(INSTALL_FAILED_INVALID_APK,
17134                            "Could not compute hash: " + pkgName);
17135                    return;
17136                }
17137                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17138                    res.setError(INSTALL_FAILED_INVALID_APK,
17139                            "New package fails restrict-update check: " + pkgName);
17140                    return;
17141                }
17142                // retain upgrade restriction
17143                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17144            }
17145
17146            // Check for shared user id changes
17147            String invalidPackageName =
17148                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17149            if (invalidPackageName != null) {
17150                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17151                        "Package " + invalidPackageName + " tried to change user "
17152                                + oldPackage.mSharedUserId);
17153                return;
17154            }
17155
17156            // In case of rollback, remember per-user/profile install state
17157            allUsers = sUserManager.getUserIds();
17158            installedUsers = ps.queryInstalledUsers(allUsers, true);
17159
17160            // don't allow an upgrade from full to ephemeral
17161            if (isInstantApp) {
17162                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17163                    for (int currentUser : allUsers) {
17164                        if (!ps.getInstantApp(currentUser)) {
17165                            // can't downgrade from full to instant
17166                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17167                                    + " for user: " + currentUser);
17168                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17169                            return;
17170                        }
17171                    }
17172                } else if (!ps.getInstantApp(user.getIdentifier())) {
17173                    // can't downgrade from full to instant
17174                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17175                            + " for user: " + user.getIdentifier());
17176                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17177                    return;
17178                }
17179            }
17180        }
17181
17182        // Update what is removed
17183        res.removedInfo = new PackageRemovedInfo(this);
17184        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17185        res.removedInfo.removedPackage = oldPackage.packageName;
17186        res.removedInfo.installerPackageName = ps.installerPackageName;
17187        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17188        res.removedInfo.isUpdate = true;
17189        res.removedInfo.origUsers = installedUsers;
17190        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17191        for (int i = 0; i < installedUsers.length; i++) {
17192            final int userId = installedUsers[i];
17193            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17194        }
17195
17196        final int childCount = (oldPackage.childPackages != null)
17197                ? oldPackage.childPackages.size() : 0;
17198        for (int i = 0; i < childCount; i++) {
17199            boolean childPackageUpdated = false;
17200            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17201            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17202            if (res.addedChildPackages != null) {
17203                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17204                if (childRes != null) {
17205                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17206                    childRes.removedInfo.removedPackage = childPkg.packageName;
17207                    if (childPs != null) {
17208                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17209                    }
17210                    childRes.removedInfo.isUpdate = true;
17211                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17212                    childPackageUpdated = true;
17213                }
17214            }
17215            if (!childPackageUpdated) {
17216                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17217                childRemovedRes.removedPackage = childPkg.packageName;
17218                if (childPs != null) {
17219                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17220                }
17221                childRemovedRes.isUpdate = false;
17222                childRemovedRes.dataRemoved = true;
17223                synchronized (mPackages) {
17224                    if (childPs != null) {
17225                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17226                    }
17227                }
17228                if (res.removedInfo.removedChildPackages == null) {
17229                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17230                }
17231                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17232            }
17233        }
17234
17235        boolean sysPkg = (isSystemApp(oldPackage));
17236        if (sysPkg) {
17237            // Set the system/privileged flags as needed
17238            final boolean privileged =
17239                    (oldPackage.applicationInfo.privateFlags
17240                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17241            final int systemPolicyFlags = policyFlags
17242                    | PackageParser.PARSE_IS_SYSTEM
17243                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17244
17245            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17246                    user, allUsers, installerPackageName, res, installReason);
17247        } else {
17248            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17249                    user, allUsers, installerPackageName, res, installReason);
17250        }
17251    }
17252
17253    @Override
17254    public List<String> getPreviousCodePaths(String packageName) {
17255        final int callingUid = Binder.getCallingUid();
17256        final List<String> result = new ArrayList<>();
17257        if (getInstantAppPackageName(callingUid) != null) {
17258            return result;
17259        }
17260        final PackageSetting ps = mSettings.mPackages.get(packageName);
17261        if (ps != null
17262                && ps.oldCodePaths != null
17263                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17264            result.addAll(ps.oldCodePaths);
17265        }
17266        return result;
17267    }
17268
17269    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17270            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17271            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17272            int installReason) {
17273        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17274                + deletedPackage);
17275
17276        String pkgName = deletedPackage.packageName;
17277        boolean deletedPkg = true;
17278        boolean addedPkg = false;
17279        boolean updatedSettings = false;
17280        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17281        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17282                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17283
17284        final long origUpdateTime = (pkg.mExtras != null)
17285                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17286
17287        // First delete the existing package while retaining the data directory
17288        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17289                res.removedInfo, true, pkg)) {
17290            // If the existing package wasn't successfully deleted
17291            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17292            deletedPkg = false;
17293        } else {
17294            // Successfully deleted the old package; proceed with replace.
17295
17296            // If deleted package lived in a container, give users a chance to
17297            // relinquish resources before killing.
17298            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17299                if (DEBUG_INSTALL) {
17300                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17301                }
17302                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17303                final ArrayList<String> pkgList = new ArrayList<String>(1);
17304                pkgList.add(deletedPackage.applicationInfo.packageName);
17305                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17306            }
17307
17308            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17309                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17310            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17311
17312            try {
17313                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17314                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17315                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17316                        installReason);
17317
17318                // Update the in-memory copy of the previous code paths.
17319                PackageSetting ps = mSettings.mPackages.get(pkgName);
17320                if (!killApp) {
17321                    if (ps.oldCodePaths == null) {
17322                        ps.oldCodePaths = new ArraySet<>();
17323                    }
17324                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17325                    if (deletedPackage.splitCodePaths != null) {
17326                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17327                    }
17328                } else {
17329                    ps.oldCodePaths = null;
17330                }
17331                if (ps.childPackageNames != null) {
17332                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17333                        final String childPkgName = ps.childPackageNames.get(i);
17334                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17335                        childPs.oldCodePaths = ps.oldCodePaths;
17336                    }
17337                }
17338                // set instant app status, but, only if it's explicitly specified
17339                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17340                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17341                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17342                prepareAppDataAfterInstallLIF(newPackage);
17343                addedPkg = true;
17344                mDexManager.notifyPackageUpdated(newPackage.packageName,
17345                        newPackage.baseCodePath, newPackage.splitCodePaths);
17346            } catch (PackageManagerException e) {
17347                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17348            }
17349        }
17350
17351        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17352            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17353
17354            // Revert all internal state mutations and added folders for the failed install
17355            if (addedPkg) {
17356                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17357                        res.removedInfo, true, null);
17358            }
17359
17360            // Restore the old package
17361            if (deletedPkg) {
17362                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17363                File restoreFile = new File(deletedPackage.codePath);
17364                // Parse old package
17365                boolean oldExternal = isExternal(deletedPackage);
17366                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17367                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17368                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17369                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17370                try {
17371                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17372                            null);
17373                } catch (PackageManagerException e) {
17374                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17375                            + e.getMessage());
17376                    return;
17377                }
17378
17379                synchronized (mPackages) {
17380                    // Ensure the installer package name up to date
17381                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17382
17383                    // Update permissions for restored package
17384                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17385
17386                    mSettings.writeLPr();
17387                }
17388
17389                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17390            }
17391        } else {
17392            synchronized (mPackages) {
17393                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17394                if (ps != null) {
17395                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17396                    if (res.removedInfo.removedChildPackages != null) {
17397                        final int childCount = res.removedInfo.removedChildPackages.size();
17398                        // Iterate in reverse as we may modify the collection
17399                        for (int i = childCount - 1; i >= 0; i--) {
17400                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17401                            if (res.addedChildPackages.containsKey(childPackageName)) {
17402                                res.removedInfo.removedChildPackages.removeAt(i);
17403                            } else {
17404                                PackageRemovedInfo childInfo = res.removedInfo
17405                                        .removedChildPackages.valueAt(i);
17406                                childInfo.removedForAllUsers = mPackages.get(
17407                                        childInfo.removedPackage) == null;
17408                            }
17409                        }
17410                    }
17411                }
17412            }
17413        }
17414    }
17415
17416    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17417            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17418            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17419            int installReason) {
17420        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17421                + ", old=" + deletedPackage);
17422
17423        final boolean disabledSystem;
17424
17425        // Remove existing system package
17426        removePackageLI(deletedPackage, true);
17427
17428        synchronized (mPackages) {
17429            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17430        }
17431        if (!disabledSystem) {
17432            // We didn't need to disable the .apk as a current system package,
17433            // which means we are replacing another update that is already
17434            // installed.  We need to make sure to delete the older one's .apk.
17435            res.removedInfo.args = createInstallArgsForExisting(0,
17436                    deletedPackage.applicationInfo.getCodePath(),
17437                    deletedPackage.applicationInfo.getResourcePath(),
17438                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17439        } else {
17440            res.removedInfo.args = null;
17441        }
17442
17443        // Successfully disabled the old package. Now proceed with re-installation
17444        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17445                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17446        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17447
17448        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17449        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17450                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17451
17452        PackageParser.Package newPackage = null;
17453        try {
17454            // Add the package to the internal data structures
17455            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17456
17457            // Set the update and install times
17458            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17459            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17460                    System.currentTimeMillis());
17461
17462            // Update the package dynamic state if succeeded
17463            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17464                // Now that the install succeeded make sure we remove data
17465                // directories for any child package the update removed.
17466                final int deletedChildCount = (deletedPackage.childPackages != null)
17467                        ? deletedPackage.childPackages.size() : 0;
17468                final int newChildCount = (newPackage.childPackages != null)
17469                        ? newPackage.childPackages.size() : 0;
17470                for (int i = 0; i < deletedChildCount; i++) {
17471                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17472                    boolean childPackageDeleted = true;
17473                    for (int j = 0; j < newChildCount; j++) {
17474                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17475                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17476                            childPackageDeleted = false;
17477                            break;
17478                        }
17479                    }
17480                    if (childPackageDeleted) {
17481                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17482                                deletedChildPkg.packageName);
17483                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17484                            PackageRemovedInfo removedChildRes = res.removedInfo
17485                                    .removedChildPackages.get(deletedChildPkg.packageName);
17486                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17487                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17488                        }
17489                    }
17490                }
17491
17492                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17493                        installReason);
17494                prepareAppDataAfterInstallLIF(newPackage);
17495
17496                mDexManager.notifyPackageUpdated(newPackage.packageName,
17497                            newPackage.baseCodePath, newPackage.splitCodePaths);
17498            }
17499        } catch (PackageManagerException e) {
17500            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17501            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17502        }
17503
17504        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17505            // Re installation failed. Restore old information
17506            // Remove new pkg information
17507            if (newPackage != null) {
17508                removeInstalledPackageLI(newPackage, true);
17509            }
17510            // Add back the old system package
17511            try {
17512                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17513            } catch (PackageManagerException e) {
17514                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17515            }
17516
17517            synchronized (mPackages) {
17518                if (disabledSystem) {
17519                    enableSystemPackageLPw(deletedPackage);
17520                }
17521
17522                // Ensure the installer package name up to date
17523                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17524
17525                // Update permissions for restored package
17526                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17527
17528                mSettings.writeLPr();
17529            }
17530
17531            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17532                    + " after failed upgrade");
17533        }
17534    }
17535
17536    /**
17537     * Checks whether the parent or any of the child packages have a change shared
17538     * user. For a package to be a valid update the shred users of the parent and
17539     * the children should match. We may later support changing child shared users.
17540     * @param oldPkg The updated package.
17541     * @param newPkg The update package.
17542     * @return The shared user that change between the versions.
17543     */
17544    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17545            PackageParser.Package newPkg) {
17546        // Check parent shared user
17547        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17548            return newPkg.packageName;
17549        }
17550        // Check child shared users
17551        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17552        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17553        for (int i = 0; i < newChildCount; i++) {
17554            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17555            // If this child was present, did it have the same shared user?
17556            for (int j = 0; j < oldChildCount; j++) {
17557                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17558                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17559                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17560                    return newChildPkg.packageName;
17561                }
17562            }
17563        }
17564        return null;
17565    }
17566
17567    private void removeNativeBinariesLI(PackageSetting ps) {
17568        // Remove the lib path for the parent package
17569        if (ps != null) {
17570            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17571            // Remove the lib path for the child packages
17572            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17573            for (int i = 0; i < childCount; i++) {
17574                PackageSetting childPs = null;
17575                synchronized (mPackages) {
17576                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17577                }
17578                if (childPs != null) {
17579                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17580                            .legacyNativeLibraryPathString);
17581                }
17582            }
17583        }
17584    }
17585
17586    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17587        // Enable the parent package
17588        mSettings.enableSystemPackageLPw(pkg.packageName);
17589        // Enable the child packages
17590        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17591        for (int i = 0; i < childCount; i++) {
17592            PackageParser.Package childPkg = pkg.childPackages.get(i);
17593            mSettings.enableSystemPackageLPw(childPkg.packageName);
17594        }
17595    }
17596
17597    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17598            PackageParser.Package newPkg) {
17599        // Disable the parent package (parent always replaced)
17600        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17601        // Disable the child packages
17602        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17603        for (int i = 0; i < childCount; i++) {
17604            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17605            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17606            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17607        }
17608        return disabled;
17609    }
17610
17611    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17612            String installerPackageName) {
17613        // Enable the parent package
17614        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17615        // Enable the child packages
17616        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17617        for (int i = 0; i < childCount; i++) {
17618            PackageParser.Package childPkg = pkg.childPackages.get(i);
17619            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17620        }
17621    }
17622
17623    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17624        // Collect all used permissions in the UID
17625        ArraySet<String> usedPermissions = new ArraySet<>();
17626        final int packageCount = su.packages.size();
17627        for (int i = 0; i < packageCount; i++) {
17628            PackageSetting ps = su.packages.valueAt(i);
17629            if (ps.pkg == null) {
17630                continue;
17631            }
17632            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17633            for (int j = 0; j < requestedPermCount; j++) {
17634                String permission = ps.pkg.requestedPermissions.get(j);
17635                BasePermission bp = mSettings.mPermissions.get(permission);
17636                if (bp != null) {
17637                    usedPermissions.add(permission);
17638                }
17639            }
17640        }
17641
17642        PermissionsState permissionsState = su.getPermissionsState();
17643        // Prune install permissions
17644        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17645        final int installPermCount = installPermStates.size();
17646        for (int i = installPermCount - 1; i >= 0;  i--) {
17647            PermissionState permissionState = installPermStates.get(i);
17648            if (!usedPermissions.contains(permissionState.getName())) {
17649                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17650                if (bp != null) {
17651                    permissionsState.revokeInstallPermission(bp);
17652                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17653                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17654                }
17655            }
17656        }
17657
17658        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17659
17660        // Prune runtime permissions
17661        for (int userId : allUserIds) {
17662            List<PermissionState> runtimePermStates = permissionsState
17663                    .getRuntimePermissionStates(userId);
17664            final int runtimePermCount = runtimePermStates.size();
17665            for (int i = runtimePermCount - 1; i >= 0; i--) {
17666                PermissionState permissionState = runtimePermStates.get(i);
17667                if (!usedPermissions.contains(permissionState.getName())) {
17668                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17669                    if (bp != null) {
17670                        permissionsState.revokeRuntimePermission(bp, userId);
17671                        permissionsState.updatePermissionFlags(bp, userId,
17672                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17673                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17674                                runtimePermissionChangedUserIds, userId);
17675                    }
17676                }
17677            }
17678        }
17679
17680        return runtimePermissionChangedUserIds;
17681    }
17682
17683    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17684            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17685        // Update the parent package setting
17686        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17687                res, user, installReason);
17688        // Update the child packages setting
17689        final int childCount = (newPackage.childPackages != null)
17690                ? newPackage.childPackages.size() : 0;
17691        for (int i = 0; i < childCount; i++) {
17692            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17693            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17694            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17695                    childRes.origUsers, childRes, user, installReason);
17696        }
17697    }
17698
17699    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17700            String installerPackageName, int[] allUsers, int[] installedForUsers,
17701            PackageInstalledInfo res, UserHandle user, int installReason) {
17702        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17703
17704        String pkgName = newPackage.packageName;
17705        synchronized (mPackages) {
17706            //write settings. the installStatus will be incomplete at this stage.
17707            //note that the new package setting would have already been
17708            //added to mPackages. It hasn't been persisted yet.
17709            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17710            // TODO: Remove this write? It's also written at the end of this method
17711            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17712            mSettings.writeLPr();
17713            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17714        }
17715
17716        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17717        synchronized (mPackages) {
17718            updatePermissionsLPw(newPackage.packageName, newPackage,
17719                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17720                            ? UPDATE_PERMISSIONS_ALL : 0));
17721            // For system-bundled packages, we assume that installing an upgraded version
17722            // of the package implies that the user actually wants to run that new code,
17723            // so we enable the package.
17724            PackageSetting ps = mSettings.mPackages.get(pkgName);
17725            final int userId = user.getIdentifier();
17726            if (ps != null) {
17727                if (isSystemApp(newPackage)) {
17728                    if (DEBUG_INSTALL) {
17729                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17730                    }
17731                    // Enable system package for requested users
17732                    if (res.origUsers != null) {
17733                        for (int origUserId : res.origUsers) {
17734                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17735                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17736                                        origUserId, installerPackageName);
17737                            }
17738                        }
17739                    }
17740                    // Also convey the prior install/uninstall state
17741                    if (allUsers != null && installedForUsers != null) {
17742                        for (int currentUserId : allUsers) {
17743                            final boolean installed = ArrayUtils.contains(
17744                                    installedForUsers, currentUserId);
17745                            if (DEBUG_INSTALL) {
17746                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17747                            }
17748                            ps.setInstalled(installed, currentUserId);
17749                        }
17750                        // these install state changes will be persisted in the
17751                        // upcoming call to mSettings.writeLPr().
17752                    }
17753                }
17754                // It's implied that when a user requests installation, they want the app to be
17755                // installed and enabled.
17756                if (userId != UserHandle.USER_ALL) {
17757                    ps.setInstalled(true, userId);
17758                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17759                }
17760
17761                // When replacing an existing package, preserve the original install reason for all
17762                // users that had the package installed before.
17763                final Set<Integer> previousUserIds = new ArraySet<>();
17764                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17765                    final int installReasonCount = res.removedInfo.installReasons.size();
17766                    for (int i = 0; i < installReasonCount; i++) {
17767                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17768                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17769                        ps.setInstallReason(previousInstallReason, previousUserId);
17770                        previousUserIds.add(previousUserId);
17771                    }
17772                }
17773
17774                // Set install reason for users that are having the package newly installed.
17775                if (userId == UserHandle.USER_ALL) {
17776                    for (int currentUserId : sUserManager.getUserIds()) {
17777                        if (!previousUserIds.contains(currentUserId)) {
17778                            ps.setInstallReason(installReason, currentUserId);
17779                        }
17780                    }
17781                } else if (!previousUserIds.contains(userId)) {
17782                    ps.setInstallReason(installReason, userId);
17783                }
17784                mSettings.writeKernelMappingLPr(ps);
17785            }
17786            res.name = pkgName;
17787            res.uid = newPackage.applicationInfo.uid;
17788            res.pkg = newPackage;
17789            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17790            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17791            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17792            //to update install status
17793            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17794            mSettings.writeLPr();
17795            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17796        }
17797
17798        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17799    }
17800
17801    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17802        try {
17803            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17804            installPackageLI(args, res);
17805        } finally {
17806            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17807        }
17808    }
17809
17810    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17811        final int installFlags = args.installFlags;
17812        final String installerPackageName = args.installerPackageName;
17813        final String volumeUuid = args.volumeUuid;
17814        final File tmpPackageFile = new File(args.getCodePath());
17815        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17816        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17817                || (args.volumeUuid != null));
17818        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17819        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17820        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17821        boolean replace = false;
17822        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17823        if (args.move != null) {
17824            // moving a complete application; perform an initial scan on the new install location
17825            scanFlags |= SCAN_INITIAL;
17826        }
17827        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17828            scanFlags |= SCAN_DONT_KILL_APP;
17829        }
17830        if (instantApp) {
17831            scanFlags |= SCAN_AS_INSTANT_APP;
17832        }
17833        if (fullApp) {
17834            scanFlags |= SCAN_AS_FULL_APP;
17835        }
17836
17837        // Result object to be returned
17838        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17839
17840        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17841
17842        // Sanity check
17843        if (instantApp && (forwardLocked || onExternal)) {
17844            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17845                    + " external=" + onExternal);
17846            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17847            return;
17848        }
17849
17850        // Retrieve PackageSettings and parse package
17851        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17852                | PackageParser.PARSE_ENFORCE_CODE
17853                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17854                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17855                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17856                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17857        PackageParser pp = new PackageParser();
17858        pp.setSeparateProcesses(mSeparateProcesses);
17859        pp.setDisplayMetrics(mMetrics);
17860        pp.setCallback(mPackageParserCallback);
17861
17862        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17863        final PackageParser.Package pkg;
17864        try {
17865            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17866        } catch (PackageParserException e) {
17867            res.setError("Failed parse during installPackageLI", e);
17868            return;
17869        } finally {
17870            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17871        }
17872
17873        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17874        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17875            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17876            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17877                    "Instant app package must target O");
17878            return;
17879        }
17880        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17881            Slog.w(TAG, "Instant app package " + pkg.packageName
17882                    + " does not target targetSandboxVersion 2");
17883            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17884                    "Instant app package must use targetSanboxVersion 2");
17885            return;
17886        }
17887
17888        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17889            // Static shared libraries have synthetic package names
17890            renameStaticSharedLibraryPackage(pkg);
17891
17892            // No static shared libs on external storage
17893            if (onExternal) {
17894                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17895                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17896                        "Packages declaring static-shared libs cannot be updated");
17897                return;
17898            }
17899        }
17900
17901        // If we are installing a clustered package add results for the children
17902        if (pkg.childPackages != null) {
17903            synchronized (mPackages) {
17904                final int childCount = pkg.childPackages.size();
17905                for (int i = 0; i < childCount; i++) {
17906                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17907                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17908                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17909                    childRes.pkg = childPkg;
17910                    childRes.name = childPkg.packageName;
17911                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17912                    if (childPs != null) {
17913                        childRes.origUsers = childPs.queryInstalledUsers(
17914                                sUserManager.getUserIds(), true);
17915                    }
17916                    if ((mPackages.containsKey(childPkg.packageName))) {
17917                        childRes.removedInfo = new PackageRemovedInfo(this);
17918                        childRes.removedInfo.removedPackage = childPkg.packageName;
17919                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17920                    }
17921                    if (res.addedChildPackages == null) {
17922                        res.addedChildPackages = new ArrayMap<>();
17923                    }
17924                    res.addedChildPackages.put(childPkg.packageName, childRes);
17925                }
17926            }
17927        }
17928
17929        // If package doesn't declare API override, mark that we have an install
17930        // time CPU ABI override.
17931        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17932            pkg.cpuAbiOverride = args.abiOverride;
17933        }
17934
17935        String pkgName = res.name = pkg.packageName;
17936        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17937            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17938                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17939                return;
17940            }
17941        }
17942
17943        try {
17944            // either use what we've been given or parse directly from the APK
17945            if (args.certificates != null) {
17946                try {
17947                    PackageParser.populateCertificates(pkg, args.certificates);
17948                } catch (PackageParserException e) {
17949                    // there was something wrong with the certificates we were given;
17950                    // try to pull them from the APK
17951                    PackageParser.collectCertificates(pkg, parseFlags);
17952                }
17953            } else {
17954                PackageParser.collectCertificates(pkg, parseFlags);
17955            }
17956        } catch (PackageParserException e) {
17957            res.setError("Failed collect during installPackageLI", e);
17958            return;
17959        }
17960
17961        // Get rid of all references to package scan path via parser.
17962        pp = null;
17963        String oldCodePath = null;
17964        boolean systemApp = false;
17965        synchronized (mPackages) {
17966            // Check if installing already existing package
17967            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17968                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17969                if (pkg.mOriginalPackages != null
17970                        && pkg.mOriginalPackages.contains(oldName)
17971                        && mPackages.containsKey(oldName)) {
17972                    // This package is derived from an original package,
17973                    // and this device has been updating from that original
17974                    // name.  We must continue using the original name, so
17975                    // rename the new package here.
17976                    pkg.setPackageName(oldName);
17977                    pkgName = pkg.packageName;
17978                    replace = true;
17979                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17980                            + oldName + " pkgName=" + pkgName);
17981                } else if (mPackages.containsKey(pkgName)) {
17982                    // This package, under its official name, already exists
17983                    // on the device; we should replace it.
17984                    replace = true;
17985                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17986                }
17987
17988                // Child packages are installed through the parent package
17989                if (pkg.parentPackage != null) {
17990                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17991                            "Package " + pkg.packageName + " is child of package "
17992                                    + pkg.parentPackage.parentPackage + ". Child packages "
17993                                    + "can be updated only through the parent package.");
17994                    return;
17995                }
17996
17997                if (replace) {
17998                    // Prevent apps opting out from runtime permissions
17999                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18000                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18001                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18002                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18003                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18004                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18005                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18006                                        + " doesn't support runtime permissions but the old"
18007                                        + " target SDK " + oldTargetSdk + " does.");
18008                        return;
18009                    }
18010                    // Prevent apps from downgrading their targetSandbox.
18011                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18012                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18013                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18014                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18015                                "Package " + pkg.packageName + " new target sandbox "
18016                                + newTargetSandbox + " is incompatible with the previous value of"
18017                                + oldTargetSandbox + ".");
18018                        return;
18019                    }
18020
18021                    // Prevent installing of child packages
18022                    if (oldPackage.parentPackage != null) {
18023                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18024                                "Package " + pkg.packageName + " is child of package "
18025                                        + oldPackage.parentPackage + ". Child packages "
18026                                        + "can be updated only through the parent package.");
18027                        return;
18028                    }
18029                }
18030            }
18031
18032            PackageSetting ps = mSettings.mPackages.get(pkgName);
18033            if (ps != null) {
18034                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18035
18036                // Static shared libs have same package with different versions where
18037                // we internally use a synthetic package name to allow multiple versions
18038                // of the same package, therefore we need to compare signatures against
18039                // the package setting for the latest library version.
18040                PackageSetting signatureCheckPs = ps;
18041                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18042                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18043                    if (libraryEntry != null) {
18044                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18045                    }
18046                }
18047
18048                // Quick sanity check that we're signed correctly if updating;
18049                // we'll check this again later when scanning, but we want to
18050                // bail early here before tripping over redefined permissions.
18051                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18052                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18053                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18054                                + pkg.packageName + " upgrade keys do not match the "
18055                                + "previously installed version");
18056                        return;
18057                    }
18058                } else {
18059                    try {
18060                        verifySignaturesLP(signatureCheckPs, pkg);
18061                    } catch (PackageManagerException e) {
18062                        res.setError(e.error, e.getMessage());
18063                        return;
18064                    }
18065                }
18066
18067                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18068                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18069                    systemApp = (ps.pkg.applicationInfo.flags &
18070                            ApplicationInfo.FLAG_SYSTEM) != 0;
18071                }
18072                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18073            }
18074
18075            int N = pkg.permissions.size();
18076            for (int i = N-1; i >= 0; i--) {
18077                PackageParser.Permission perm = pkg.permissions.get(i);
18078                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18079
18080                // Don't allow anyone but the system to define ephemeral permissions.
18081                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18082                        && !systemApp) {
18083                    Slog.w(TAG, "Non-System package " + pkg.packageName
18084                            + " attempting to delcare ephemeral permission "
18085                            + perm.info.name + "; Removing ephemeral.");
18086                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18087                }
18088                // Check whether the newly-scanned package wants to define an already-defined perm
18089                if (bp != null) {
18090                    // If the defining package is signed with our cert, it's okay.  This
18091                    // also includes the "updating the same package" case, of course.
18092                    // "updating same package" could also involve key-rotation.
18093                    final boolean sigsOk;
18094                    if (bp.sourcePackage.equals(pkg.packageName)
18095                            && (bp.packageSetting instanceof PackageSetting)
18096                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18097                                    scanFlags))) {
18098                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18099                    } else {
18100                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18101                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18102                    }
18103                    if (!sigsOk) {
18104                        // If the owning package is the system itself, we log but allow
18105                        // install to proceed; we fail the install on all other permission
18106                        // redefinitions.
18107                        if (!bp.sourcePackage.equals("android")) {
18108                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18109                                    + pkg.packageName + " attempting to redeclare permission "
18110                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18111                            res.origPermission = perm.info.name;
18112                            res.origPackage = bp.sourcePackage;
18113                            return;
18114                        } else {
18115                            Slog.w(TAG, "Package " + pkg.packageName
18116                                    + " attempting to redeclare system permission "
18117                                    + perm.info.name + "; ignoring new declaration");
18118                            pkg.permissions.remove(i);
18119                        }
18120                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18121                        // Prevent apps to change protection level to dangerous from any other
18122                        // type as this would allow a privilege escalation where an app adds a
18123                        // normal/signature permission in other app's group and later redefines
18124                        // it as dangerous leading to the group auto-grant.
18125                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18126                                == PermissionInfo.PROTECTION_DANGEROUS) {
18127                            if (bp != null && !bp.isRuntime()) {
18128                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18129                                        + "non-runtime permission " + perm.info.name
18130                                        + " to runtime; keeping old protection level");
18131                                perm.info.protectionLevel = bp.protectionLevel;
18132                            }
18133                        }
18134                    }
18135                }
18136            }
18137        }
18138
18139        if (systemApp) {
18140            if (onExternal) {
18141                // Abort update; system app can't be replaced with app on sdcard
18142                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18143                        "Cannot install updates to system apps on sdcard");
18144                return;
18145            } else if (instantApp) {
18146                // Abort update; system app can't be replaced with an instant app
18147                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18148                        "Cannot update a system app with an instant app");
18149                return;
18150            }
18151        }
18152
18153        if (args.move != null) {
18154            // We did an in-place move, so dex is ready to roll
18155            scanFlags |= SCAN_NO_DEX;
18156            scanFlags |= SCAN_MOVE;
18157
18158            synchronized (mPackages) {
18159                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18160                if (ps == null) {
18161                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18162                            "Missing settings for moved package " + pkgName);
18163                }
18164
18165                // We moved the entire application as-is, so bring over the
18166                // previously derived ABI information.
18167                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18168                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18169            }
18170
18171        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18172            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18173            scanFlags |= SCAN_NO_DEX;
18174
18175            try {
18176                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18177                    args.abiOverride : pkg.cpuAbiOverride);
18178                final boolean extractNativeLibs = !pkg.isLibrary();
18179                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18180                        extractNativeLibs, mAppLib32InstallDir);
18181            } catch (PackageManagerException pme) {
18182                Slog.e(TAG, "Error deriving application ABI", pme);
18183                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18184                return;
18185            }
18186
18187            // Shared libraries for the package need to be updated.
18188            synchronized (mPackages) {
18189                try {
18190                    updateSharedLibrariesLPr(pkg, null);
18191                } catch (PackageManagerException e) {
18192                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18193                }
18194            }
18195
18196            // dexopt can take some time to complete, so, for instant apps, we skip this
18197            // step during installation. Instead, we'll take extra time the first time the
18198            // instant app starts. It's preferred to do it this way to provide continuous
18199            // progress to the user instead of mysteriously blocking somewhere in the
18200            // middle of running an instant app. The default behaviour can be overridden
18201            // via gservices.
18202            if (!instantApp || Global.getInt(
18203                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18204                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18205                // Do not run PackageDexOptimizer through the local performDexOpt
18206                // method because `pkg` may not be in `mPackages` yet.
18207                //
18208                // Also, don't fail application installs if the dexopt step fails.
18209                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18210                        null /* instructionSets */, false /* checkProfiles */,
18211                        getCompilerFilterForReason(REASON_INSTALL),
18212                        getOrCreateCompilerPackageStats(pkg),
18213                        mDexManager.isUsedByOtherApps(pkg.packageName),
18214                        true /* bootComplete */);
18215                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18216            }
18217
18218            // Notify BackgroundDexOptService that the package has been changed.
18219            // If this is an update of a package which used to fail to compile,
18220            // BDOS will remove it from its blacklist.
18221            // TODO: Layering violation
18222            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18223        }
18224
18225        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18226            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18227            return;
18228        }
18229
18230        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18231
18232        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18233                "installPackageLI")) {
18234            if (replace) {
18235                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18236                    // Static libs have a synthetic package name containing the version
18237                    // and cannot be updated as an update would get a new package name,
18238                    // unless this is the exact same version code which is useful for
18239                    // development.
18240                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18241                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18242                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18243                                + "static-shared libs cannot be updated");
18244                        return;
18245                    }
18246                }
18247                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18248                        installerPackageName, res, args.installReason);
18249            } else {
18250                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18251                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18252            }
18253        }
18254
18255        synchronized (mPackages) {
18256            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18257            if (ps != null) {
18258                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18259                ps.setUpdateAvailable(false /*updateAvailable*/);
18260            }
18261
18262            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18263            for (int i = 0; i < childCount; i++) {
18264                PackageParser.Package childPkg = pkg.childPackages.get(i);
18265                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18266                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18267                if (childPs != null) {
18268                    childRes.newUsers = childPs.queryInstalledUsers(
18269                            sUserManager.getUserIds(), true);
18270                }
18271            }
18272
18273            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18274                updateSequenceNumberLP(ps, res.newUsers);
18275                updateInstantAppInstallerLocked(pkgName);
18276            }
18277        }
18278    }
18279
18280    private void startIntentFilterVerifications(int userId, boolean replacing,
18281            PackageParser.Package pkg) {
18282        if (mIntentFilterVerifierComponent == null) {
18283            Slog.w(TAG, "No IntentFilter verification will not be done as "
18284                    + "there is no IntentFilterVerifier available!");
18285            return;
18286        }
18287
18288        final int verifierUid = getPackageUid(
18289                mIntentFilterVerifierComponent.getPackageName(),
18290                MATCH_DEBUG_TRIAGED_MISSING,
18291                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18292
18293        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18294        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18295        mHandler.sendMessage(msg);
18296
18297        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18298        for (int i = 0; i < childCount; i++) {
18299            PackageParser.Package childPkg = pkg.childPackages.get(i);
18300            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18301            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18302            mHandler.sendMessage(msg);
18303        }
18304    }
18305
18306    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18307            PackageParser.Package pkg) {
18308        int size = pkg.activities.size();
18309        if (size == 0) {
18310            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18311                    "No activity, so no need to verify any IntentFilter!");
18312            return;
18313        }
18314
18315        final boolean hasDomainURLs = hasDomainURLs(pkg);
18316        if (!hasDomainURLs) {
18317            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18318                    "No domain URLs, so no need to verify any IntentFilter!");
18319            return;
18320        }
18321
18322        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18323                + " if any IntentFilter from the " + size
18324                + " Activities needs verification ...");
18325
18326        int count = 0;
18327        final String packageName = pkg.packageName;
18328
18329        synchronized (mPackages) {
18330            // If this is a new install and we see that we've already run verification for this
18331            // package, we have nothing to do: it means the state was restored from backup.
18332            if (!replacing) {
18333                IntentFilterVerificationInfo ivi =
18334                        mSettings.getIntentFilterVerificationLPr(packageName);
18335                if (ivi != null) {
18336                    if (DEBUG_DOMAIN_VERIFICATION) {
18337                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18338                                + ivi.getStatusString());
18339                    }
18340                    return;
18341                }
18342            }
18343
18344            // If any filters need to be verified, then all need to be.
18345            boolean needToVerify = false;
18346            for (PackageParser.Activity a : pkg.activities) {
18347                for (ActivityIntentInfo filter : a.intents) {
18348                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18349                        if (DEBUG_DOMAIN_VERIFICATION) {
18350                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18351                        }
18352                        needToVerify = true;
18353                        break;
18354                    }
18355                }
18356            }
18357
18358            if (needToVerify) {
18359                final int verificationId = mIntentFilterVerificationToken++;
18360                for (PackageParser.Activity a : pkg.activities) {
18361                    for (ActivityIntentInfo filter : a.intents) {
18362                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18363                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18364                                    "Verification needed for IntentFilter:" + filter.toString());
18365                            mIntentFilterVerifier.addOneIntentFilterVerification(
18366                                    verifierUid, userId, verificationId, filter, packageName);
18367                            count++;
18368                        }
18369                    }
18370                }
18371            }
18372        }
18373
18374        if (count > 0) {
18375            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18376                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18377                    +  " for userId:" + userId);
18378            mIntentFilterVerifier.startVerifications(userId);
18379        } else {
18380            if (DEBUG_DOMAIN_VERIFICATION) {
18381                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18382            }
18383        }
18384    }
18385
18386    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18387        final ComponentName cn  = filter.activity.getComponentName();
18388        final String packageName = cn.getPackageName();
18389
18390        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18391                packageName);
18392        if (ivi == null) {
18393            return true;
18394        }
18395        int status = ivi.getStatus();
18396        switch (status) {
18397            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18398            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18399                return true;
18400
18401            default:
18402                // Nothing to do
18403                return false;
18404        }
18405    }
18406
18407    private static boolean isMultiArch(ApplicationInfo info) {
18408        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18409    }
18410
18411    private static boolean isExternal(PackageParser.Package pkg) {
18412        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18413    }
18414
18415    private static boolean isExternal(PackageSetting ps) {
18416        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18417    }
18418
18419    private static boolean isSystemApp(PackageParser.Package pkg) {
18420        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18421    }
18422
18423    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18424        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18425    }
18426
18427    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18428        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18429    }
18430
18431    private static boolean isSystemApp(PackageSetting ps) {
18432        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18433    }
18434
18435    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18436        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18437    }
18438
18439    private int packageFlagsToInstallFlags(PackageSetting ps) {
18440        int installFlags = 0;
18441        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18442            // This existing package was an external ASEC install when we have
18443            // the external flag without a UUID
18444            installFlags |= PackageManager.INSTALL_EXTERNAL;
18445        }
18446        if (ps.isForwardLocked()) {
18447            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18448        }
18449        return installFlags;
18450    }
18451
18452    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18453        if (isExternal(pkg)) {
18454            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18455                return StorageManager.UUID_PRIMARY_PHYSICAL;
18456            } else {
18457                return pkg.volumeUuid;
18458            }
18459        } else {
18460            return StorageManager.UUID_PRIVATE_INTERNAL;
18461        }
18462    }
18463
18464    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18465        if (isExternal(pkg)) {
18466            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18467                return mSettings.getExternalVersion();
18468            } else {
18469                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18470            }
18471        } else {
18472            return mSettings.getInternalVersion();
18473        }
18474    }
18475
18476    private void deleteTempPackageFiles() {
18477        final FilenameFilter filter = new FilenameFilter() {
18478            public boolean accept(File dir, String name) {
18479                return name.startsWith("vmdl") && name.endsWith(".tmp");
18480            }
18481        };
18482        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18483            file.delete();
18484        }
18485    }
18486
18487    @Override
18488    public void deletePackageAsUser(String packageName, int versionCode,
18489            IPackageDeleteObserver observer, int userId, int flags) {
18490        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18491                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18492    }
18493
18494    @Override
18495    public void deletePackageVersioned(VersionedPackage versionedPackage,
18496            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18497        final int callingUid = Binder.getCallingUid();
18498        mContext.enforceCallingOrSelfPermission(
18499                android.Manifest.permission.DELETE_PACKAGES, null);
18500        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18501        Preconditions.checkNotNull(versionedPackage);
18502        Preconditions.checkNotNull(observer);
18503        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18504                PackageManager.VERSION_CODE_HIGHEST,
18505                Integer.MAX_VALUE, "versionCode must be >= -1");
18506
18507        final String packageName = versionedPackage.getPackageName();
18508        final int versionCode = versionedPackage.getVersionCode();
18509        final String internalPackageName;
18510        synchronized (mPackages) {
18511            // Normalize package name to handle renamed packages and static libs
18512            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18513                    versionedPackage.getVersionCode());
18514        }
18515
18516        final int uid = Binder.getCallingUid();
18517        if (!isOrphaned(internalPackageName)
18518                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18519            try {
18520                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18521                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18522                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18523                observer.onUserActionRequired(intent);
18524            } catch (RemoteException re) {
18525            }
18526            return;
18527        }
18528        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18529        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18530        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18531            mContext.enforceCallingOrSelfPermission(
18532                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18533                    "deletePackage for user " + userId);
18534        }
18535
18536        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18537            try {
18538                observer.onPackageDeleted(packageName,
18539                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18540            } catch (RemoteException re) {
18541            }
18542            return;
18543        }
18544
18545        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18546            try {
18547                observer.onPackageDeleted(packageName,
18548                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18549            } catch (RemoteException re) {
18550            }
18551            return;
18552        }
18553
18554        if (DEBUG_REMOVE) {
18555            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18556                    + " deleteAllUsers: " + deleteAllUsers + " version="
18557                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18558                    ? "VERSION_CODE_HIGHEST" : versionCode));
18559        }
18560        // Queue up an async operation since the package deletion may take a little while.
18561        mHandler.post(new Runnable() {
18562            public void run() {
18563                mHandler.removeCallbacks(this);
18564                int returnCode;
18565                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18566                boolean doDeletePackage = true;
18567                if (ps != null) {
18568                    final boolean targetIsInstantApp =
18569                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18570                    doDeletePackage = !targetIsInstantApp
18571                            || canViewInstantApps;
18572                }
18573                if (doDeletePackage) {
18574                    if (!deleteAllUsers) {
18575                        returnCode = deletePackageX(internalPackageName, versionCode,
18576                                userId, deleteFlags);
18577                    } else {
18578                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18579                                internalPackageName, users);
18580                        // If nobody is blocking uninstall, proceed with delete for all users
18581                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18582                            returnCode = deletePackageX(internalPackageName, versionCode,
18583                                    userId, deleteFlags);
18584                        } else {
18585                            // Otherwise uninstall individually for users with blockUninstalls=false
18586                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18587                            for (int userId : users) {
18588                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18589                                    returnCode = deletePackageX(internalPackageName, versionCode,
18590                                            userId, userFlags);
18591                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18592                                        Slog.w(TAG, "Package delete failed for user " + userId
18593                                                + ", returnCode " + returnCode);
18594                                    }
18595                                }
18596                            }
18597                            // The app has only been marked uninstalled for certain users.
18598                            // We still need to report that delete was blocked
18599                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18600                        }
18601                    }
18602                } else {
18603                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18604                }
18605                try {
18606                    observer.onPackageDeleted(packageName, returnCode, null);
18607                } catch (RemoteException e) {
18608                    Log.i(TAG, "Observer no longer exists.");
18609                } //end catch
18610            } //end run
18611        });
18612    }
18613
18614    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18615        if (pkg.staticSharedLibName != null) {
18616            return pkg.manifestPackageName;
18617        }
18618        return pkg.packageName;
18619    }
18620
18621    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18622        // Handle renamed packages
18623        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18624        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18625
18626        // Is this a static library?
18627        SparseArray<SharedLibraryEntry> versionedLib =
18628                mStaticLibsByDeclaringPackage.get(packageName);
18629        if (versionedLib == null || versionedLib.size() <= 0) {
18630            return packageName;
18631        }
18632
18633        // Figure out which lib versions the caller can see
18634        SparseIntArray versionsCallerCanSee = null;
18635        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18636        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18637                && callingAppId != Process.ROOT_UID) {
18638            versionsCallerCanSee = new SparseIntArray();
18639            String libName = versionedLib.valueAt(0).info.getName();
18640            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18641            if (uidPackages != null) {
18642                for (String uidPackage : uidPackages) {
18643                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18644                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18645                    if (libIdx >= 0) {
18646                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18647                        versionsCallerCanSee.append(libVersion, libVersion);
18648                    }
18649                }
18650            }
18651        }
18652
18653        // Caller can see nothing - done
18654        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18655            return packageName;
18656        }
18657
18658        // Find the version the caller can see and the app version code
18659        SharedLibraryEntry highestVersion = null;
18660        final int versionCount = versionedLib.size();
18661        for (int i = 0; i < versionCount; i++) {
18662            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18663            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18664                    libEntry.info.getVersion()) < 0) {
18665                continue;
18666            }
18667            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18668            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18669                if (libVersionCode == versionCode) {
18670                    return libEntry.apk;
18671                }
18672            } else if (highestVersion == null) {
18673                highestVersion = libEntry;
18674            } else if (libVersionCode  > highestVersion.info
18675                    .getDeclaringPackage().getVersionCode()) {
18676                highestVersion = libEntry;
18677            }
18678        }
18679
18680        if (highestVersion != null) {
18681            return highestVersion.apk;
18682        }
18683
18684        return packageName;
18685    }
18686
18687    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18688        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18689              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18690            return true;
18691        }
18692        final int callingUserId = UserHandle.getUserId(callingUid);
18693        // If the caller installed the pkgName, then allow it to silently uninstall.
18694        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18695            return true;
18696        }
18697
18698        // Allow package verifier to silently uninstall.
18699        if (mRequiredVerifierPackage != null &&
18700                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18701            return true;
18702        }
18703
18704        // Allow package uninstaller to silently uninstall.
18705        if (mRequiredUninstallerPackage != null &&
18706                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18707            return true;
18708        }
18709
18710        // Allow storage manager to silently uninstall.
18711        if (mStorageManagerPackage != null &&
18712                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18713            return true;
18714        }
18715
18716        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18717        // uninstall for device owner provisioning.
18718        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18719                == PERMISSION_GRANTED) {
18720            return true;
18721        }
18722
18723        return false;
18724    }
18725
18726    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18727        int[] result = EMPTY_INT_ARRAY;
18728        for (int userId : userIds) {
18729            if (getBlockUninstallForUser(packageName, userId)) {
18730                result = ArrayUtils.appendInt(result, userId);
18731            }
18732        }
18733        return result;
18734    }
18735
18736    @Override
18737    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18738        final int callingUid = Binder.getCallingUid();
18739        if (getInstantAppPackageName(callingUid) != null
18740                && !isCallerSameApp(packageName, callingUid)) {
18741            return false;
18742        }
18743        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18744    }
18745
18746    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18747        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18748                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18749        try {
18750            if (dpm != null) {
18751                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18752                        /* callingUserOnly =*/ false);
18753                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18754                        : deviceOwnerComponentName.getPackageName();
18755                // Does the package contains the device owner?
18756                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18757                // this check is probably not needed, since DO should be registered as a device
18758                // admin on some user too. (Original bug for this: b/17657954)
18759                if (packageName.equals(deviceOwnerPackageName)) {
18760                    return true;
18761                }
18762                // Does it contain a device admin for any user?
18763                int[] users;
18764                if (userId == UserHandle.USER_ALL) {
18765                    users = sUserManager.getUserIds();
18766                } else {
18767                    users = new int[]{userId};
18768                }
18769                for (int i = 0; i < users.length; ++i) {
18770                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18771                        return true;
18772                    }
18773                }
18774            }
18775        } catch (RemoteException e) {
18776        }
18777        return false;
18778    }
18779
18780    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18781        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18782    }
18783
18784    /**
18785     *  This method is an internal method that could be get invoked either
18786     *  to delete an installed package or to clean up a failed installation.
18787     *  After deleting an installed package, a broadcast is sent to notify any
18788     *  listeners that the package has been removed. For cleaning up a failed
18789     *  installation, the broadcast is not necessary since the package's
18790     *  installation wouldn't have sent the initial broadcast either
18791     *  The key steps in deleting a package are
18792     *  deleting the package information in internal structures like mPackages,
18793     *  deleting the packages base directories through installd
18794     *  updating mSettings to reflect current status
18795     *  persisting settings for later use
18796     *  sending a broadcast if necessary
18797     */
18798    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18799        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18800        final boolean res;
18801
18802        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18803                ? UserHandle.USER_ALL : userId;
18804
18805        if (isPackageDeviceAdmin(packageName, removeUser)) {
18806            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18807            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18808        }
18809
18810        PackageSetting uninstalledPs = null;
18811        PackageParser.Package pkg = null;
18812
18813        // for the uninstall-updates case and restricted profiles, remember the per-
18814        // user handle installed state
18815        int[] allUsers;
18816        synchronized (mPackages) {
18817            uninstalledPs = mSettings.mPackages.get(packageName);
18818            if (uninstalledPs == null) {
18819                Slog.w(TAG, "Not removing non-existent package " + packageName);
18820                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18821            }
18822
18823            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18824                    && uninstalledPs.versionCode != versionCode) {
18825                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18826                        + uninstalledPs.versionCode + " != " + versionCode);
18827                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18828            }
18829
18830            // Static shared libs can be declared by any package, so let us not
18831            // allow removing a package if it provides a lib others depend on.
18832            pkg = mPackages.get(packageName);
18833
18834            allUsers = sUserManager.getUserIds();
18835
18836            if (pkg != null && pkg.staticSharedLibName != null) {
18837                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18838                        pkg.staticSharedLibVersion);
18839                if (libEntry != null) {
18840                    for (int currUserId : allUsers) {
18841                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18842                            continue;
18843                        }
18844                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18845                                libEntry.info, 0, currUserId);
18846                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18847                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18848                                    + " hosting lib " + libEntry.info.getName() + " version "
18849                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18850                                    + " for user " + currUserId);
18851                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18852                        }
18853                    }
18854                }
18855            }
18856
18857            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18858        }
18859
18860        final int freezeUser;
18861        if (isUpdatedSystemApp(uninstalledPs)
18862                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18863            // We're downgrading a system app, which will apply to all users, so
18864            // freeze them all during the downgrade
18865            freezeUser = UserHandle.USER_ALL;
18866        } else {
18867            freezeUser = removeUser;
18868        }
18869
18870        synchronized (mInstallLock) {
18871            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18872            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18873                    deleteFlags, "deletePackageX")) {
18874                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18875                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18876            }
18877            synchronized (mPackages) {
18878                if (res) {
18879                    if (pkg != null) {
18880                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18881                    }
18882                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18883                    updateInstantAppInstallerLocked(packageName);
18884                }
18885            }
18886        }
18887
18888        if (res) {
18889            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18890            info.sendPackageRemovedBroadcasts(killApp);
18891            info.sendSystemPackageUpdatedBroadcasts();
18892            info.sendSystemPackageAppearedBroadcasts();
18893        }
18894        // Force a gc here.
18895        Runtime.getRuntime().gc();
18896        // Delete the resources here after sending the broadcast to let
18897        // other processes clean up before deleting resources.
18898        if (info.args != null) {
18899            synchronized (mInstallLock) {
18900                info.args.doPostDeleteLI(true);
18901            }
18902        }
18903
18904        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18905    }
18906
18907    static class PackageRemovedInfo {
18908        final PackageSender packageSender;
18909        String removedPackage;
18910        String installerPackageName;
18911        int uid = -1;
18912        int removedAppId = -1;
18913        int[] origUsers;
18914        int[] removedUsers = null;
18915        int[] broadcastUsers = null;
18916        SparseArray<Integer> installReasons;
18917        boolean isRemovedPackageSystemUpdate = false;
18918        boolean isUpdate;
18919        boolean dataRemoved;
18920        boolean removedForAllUsers;
18921        boolean isStaticSharedLib;
18922        // Clean up resources deleted packages.
18923        InstallArgs args = null;
18924        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18925        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18926
18927        PackageRemovedInfo(PackageSender packageSender) {
18928            this.packageSender = packageSender;
18929        }
18930
18931        void sendPackageRemovedBroadcasts(boolean killApp) {
18932            sendPackageRemovedBroadcastInternal(killApp);
18933            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18934            for (int i = 0; i < childCount; i++) {
18935                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18936                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18937            }
18938        }
18939
18940        void sendSystemPackageUpdatedBroadcasts() {
18941            if (isRemovedPackageSystemUpdate) {
18942                sendSystemPackageUpdatedBroadcastsInternal();
18943                final int childCount = (removedChildPackages != null)
18944                        ? removedChildPackages.size() : 0;
18945                for (int i = 0; i < childCount; i++) {
18946                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18947                    if (childInfo.isRemovedPackageSystemUpdate) {
18948                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18949                    }
18950                }
18951            }
18952        }
18953
18954        void sendSystemPackageAppearedBroadcasts() {
18955            final int packageCount = (appearedChildPackages != null)
18956                    ? appearedChildPackages.size() : 0;
18957            for (int i = 0; i < packageCount; i++) {
18958                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18959                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18960                    true, UserHandle.getAppId(installedInfo.uid),
18961                    installedInfo.newUsers);
18962            }
18963        }
18964
18965        private void sendSystemPackageUpdatedBroadcastsInternal() {
18966            Bundle extras = new Bundle(2);
18967            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18968            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18969            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18970                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18971            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18972                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18973            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18974                null, null, 0, removedPackage, null, null);
18975            if (installerPackageName != null) {
18976                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18977                        removedPackage, extras, 0 /*flags*/,
18978                        installerPackageName, null, null);
18979                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18980                        removedPackage, extras, 0 /*flags*/,
18981                        installerPackageName, null, null);
18982            }
18983        }
18984
18985        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18986            // Don't send static shared library removal broadcasts as these
18987            // libs are visible only the the apps that depend on them an one
18988            // cannot remove the library if it has a dependency.
18989            if (isStaticSharedLib) {
18990                return;
18991            }
18992            Bundle extras = new Bundle(2);
18993            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18994            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18995            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18996            if (isUpdate || isRemovedPackageSystemUpdate) {
18997                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18998            }
18999            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19000            if (removedPackage != null) {
19001                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19002                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19003                if (installerPackageName != null) {
19004                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19005                            removedPackage, extras, 0 /*flags*/,
19006                            installerPackageName, null, broadcastUsers);
19007                }
19008                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19009                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19010                        removedPackage, extras,
19011                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19012                        null, null, broadcastUsers);
19013                }
19014            }
19015            if (removedAppId >= 0) {
19016                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19017                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19018                    null, null, broadcastUsers);
19019            }
19020        }
19021
19022        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19023            removedUsers = userIds;
19024            if (removedUsers == null) {
19025                broadcastUsers = null;
19026                return;
19027            }
19028
19029            broadcastUsers = EMPTY_INT_ARRAY;
19030            for (int i = userIds.length - 1; i >= 0; --i) {
19031                final int userId = userIds[i];
19032                if (deletedPackageSetting.getInstantApp(userId)) {
19033                    continue;
19034                }
19035                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19036            }
19037        }
19038    }
19039
19040    /*
19041     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19042     * flag is not set, the data directory is removed as well.
19043     * make sure this flag is set for partially installed apps. If not its meaningless to
19044     * delete a partially installed application.
19045     */
19046    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19047            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19048        String packageName = ps.name;
19049        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19050        // Retrieve object to delete permissions for shared user later on
19051        final PackageParser.Package deletedPkg;
19052        final PackageSetting deletedPs;
19053        // reader
19054        synchronized (mPackages) {
19055            deletedPkg = mPackages.get(packageName);
19056            deletedPs = mSettings.mPackages.get(packageName);
19057            if (outInfo != null) {
19058                outInfo.removedPackage = packageName;
19059                outInfo.installerPackageName = ps.installerPackageName;
19060                outInfo.isStaticSharedLib = deletedPkg != null
19061                        && deletedPkg.staticSharedLibName != null;
19062                outInfo.populateUsers(deletedPs == null ? null
19063                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19064            }
19065        }
19066
19067        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19068
19069        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19070            final PackageParser.Package resolvedPkg;
19071            if (deletedPkg != null) {
19072                resolvedPkg = deletedPkg;
19073            } else {
19074                // We don't have a parsed package when it lives on an ejected
19075                // adopted storage device, so fake something together
19076                resolvedPkg = new PackageParser.Package(ps.name);
19077                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19078            }
19079            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19080                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19081            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19082            if (outInfo != null) {
19083                outInfo.dataRemoved = true;
19084            }
19085            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19086        }
19087
19088        int removedAppId = -1;
19089
19090        // writer
19091        synchronized (mPackages) {
19092            boolean installedStateChanged = false;
19093            if (deletedPs != null) {
19094                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19095                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19096                    clearDefaultBrowserIfNeeded(packageName);
19097                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19098                    removedAppId = mSettings.removePackageLPw(packageName);
19099                    if (outInfo != null) {
19100                        outInfo.removedAppId = removedAppId;
19101                    }
19102                    updatePermissionsLPw(deletedPs.name, null, 0);
19103                    if (deletedPs.sharedUser != null) {
19104                        // Remove permissions associated with package. Since runtime
19105                        // permissions are per user we have to kill the removed package
19106                        // or packages running under the shared user of the removed
19107                        // package if revoking the permissions requested only by the removed
19108                        // package is successful and this causes a change in gids.
19109                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19110                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19111                                    userId);
19112                            if (userIdToKill == UserHandle.USER_ALL
19113                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19114                                // If gids changed for this user, kill all affected packages.
19115                                mHandler.post(new Runnable() {
19116                                    @Override
19117                                    public void run() {
19118                                        // This has to happen with no lock held.
19119                                        killApplication(deletedPs.name, deletedPs.appId,
19120                                                KILL_APP_REASON_GIDS_CHANGED);
19121                                    }
19122                                });
19123                                break;
19124                            }
19125                        }
19126                    }
19127                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19128                }
19129                // make sure to preserve per-user disabled state if this removal was just
19130                // a downgrade of a system app to the factory package
19131                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19132                    if (DEBUG_REMOVE) {
19133                        Slog.d(TAG, "Propagating install state across downgrade");
19134                    }
19135                    for (int userId : allUserHandles) {
19136                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19137                        if (DEBUG_REMOVE) {
19138                            Slog.d(TAG, "    user " + userId + " => " + installed);
19139                        }
19140                        if (installed != ps.getInstalled(userId)) {
19141                            installedStateChanged = true;
19142                        }
19143                        ps.setInstalled(installed, userId);
19144                    }
19145                }
19146            }
19147            // can downgrade to reader
19148            if (writeSettings) {
19149                // Save settings now
19150                mSettings.writeLPr();
19151            }
19152            if (installedStateChanged) {
19153                mSettings.writeKernelMappingLPr(ps);
19154            }
19155        }
19156        if (removedAppId != -1) {
19157            // A user ID was deleted here. Go through all users and remove it
19158            // from KeyStore.
19159            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19160        }
19161    }
19162
19163    static boolean locationIsPrivileged(File path) {
19164        try {
19165            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19166                    .getCanonicalPath();
19167            return path.getCanonicalPath().startsWith(privilegedAppDir);
19168        } catch (IOException e) {
19169            Slog.e(TAG, "Unable to access code path " + path);
19170        }
19171        return false;
19172    }
19173
19174    /*
19175     * Tries to delete system package.
19176     */
19177    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19178            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19179            boolean writeSettings) {
19180        if (deletedPs.parentPackageName != null) {
19181            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19182            return false;
19183        }
19184
19185        final boolean applyUserRestrictions
19186                = (allUserHandles != null) && (outInfo.origUsers != null);
19187        final PackageSetting disabledPs;
19188        // Confirm if the system package has been updated
19189        // An updated system app can be deleted. This will also have to restore
19190        // the system pkg from system partition
19191        // reader
19192        synchronized (mPackages) {
19193            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19194        }
19195
19196        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19197                + " disabledPs=" + disabledPs);
19198
19199        if (disabledPs == null) {
19200            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19201            return false;
19202        } else if (DEBUG_REMOVE) {
19203            Slog.d(TAG, "Deleting system pkg from data partition");
19204        }
19205
19206        if (DEBUG_REMOVE) {
19207            if (applyUserRestrictions) {
19208                Slog.d(TAG, "Remembering install states:");
19209                for (int userId : allUserHandles) {
19210                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19211                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19212                }
19213            }
19214        }
19215
19216        // Delete the updated package
19217        outInfo.isRemovedPackageSystemUpdate = true;
19218        if (outInfo.removedChildPackages != null) {
19219            final int childCount = (deletedPs.childPackageNames != null)
19220                    ? deletedPs.childPackageNames.size() : 0;
19221            for (int i = 0; i < childCount; i++) {
19222                String childPackageName = deletedPs.childPackageNames.get(i);
19223                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19224                        .contains(childPackageName)) {
19225                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19226                            childPackageName);
19227                    if (childInfo != null) {
19228                        childInfo.isRemovedPackageSystemUpdate = true;
19229                    }
19230                }
19231            }
19232        }
19233
19234        if (disabledPs.versionCode < deletedPs.versionCode) {
19235            // Delete data for downgrades
19236            flags &= ~PackageManager.DELETE_KEEP_DATA;
19237        } else {
19238            // Preserve data by setting flag
19239            flags |= PackageManager.DELETE_KEEP_DATA;
19240        }
19241
19242        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19243                outInfo, writeSettings, disabledPs.pkg);
19244        if (!ret) {
19245            return false;
19246        }
19247
19248        // writer
19249        synchronized (mPackages) {
19250            // Reinstate the old system package
19251            enableSystemPackageLPw(disabledPs.pkg);
19252            // Remove any native libraries from the upgraded package.
19253            removeNativeBinariesLI(deletedPs);
19254        }
19255
19256        // Install the system package
19257        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19258        int parseFlags = mDefParseFlags
19259                | PackageParser.PARSE_MUST_BE_APK
19260                | PackageParser.PARSE_IS_SYSTEM
19261                | PackageParser.PARSE_IS_SYSTEM_DIR;
19262        if (locationIsPrivileged(disabledPs.codePath)) {
19263            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19264        }
19265
19266        final PackageParser.Package newPkg;
19267        try {
19268            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19269                0 /* currentTime */, null);
19270        } catch (PackageManagerException e) {
19271            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19272                    + e.getMessage());
19273            return false;
19274        }
19275
19276        try {
19277            // update shared libraries for the newly re-installed system package
19278            updateSharedLibrariesLPr(newPkg, null);
19279        } catch (PackageManagerException e) {
19280            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19281        }
19282
19283        prepareAppDataAfterInstallLIF(newPkg);
19284
19285        // writer
19286        synchronized (mPackages) {
19287            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19288
19289            // Propagate the permissions state as we do not want to drop on the floor
19290            // runtime permissions. The update permissions method below will take
19291            // care of removing obsolete permissions and grant install permissions.
19292            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19293            updatePermissionsLPw(newPkg.packageName, newPkg,
19294                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19295
19296            if (applyUserRestrictions) {
19297                boolean installedStateChanged = false;
19298                if (DEBUG_REMOVE) {
19299                    Slog.d(TAG, "Propagating install state across reinstall");
19300                }
19301                for (int userId : allUserHandles) {
19302                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19303                    if (DEBUG_REMOVE) {
19304                        Slog.d(TAG, "    user " + userId + " => " + installed);
19305                    }
19306                    if (installed != ps.getInstalled(userId)) {
19307                        installedStateChanged = true;
19308                    }
19309                    ps.setInstalled(installed, userId);
19310
19311                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19312                }
19313                // Regardless of writeSettings we need to ensure that this restriction
19314                // state propagation is persisted
19315                mSettings.writeAllUsersPackageRestrictionsLPr();
19316                if (installedStateChanged) {
19317                    mSettings.writeKernelMappingLPr(ps);
19318                }
19319            }
19320            // can downgrade to reader here
19321            if (writeSettings) {
19322                mSettings.writeLPr();
19323            }
19324        }
19325        return true;
19326    }
19327
19328    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19329            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19330            PackageRemovedInfo outInfo, boolean writeSettings,
19331            PackageParser.Package replacingPackage) {
19332        synchronized (mPackages) {
19333            if (outInfo != null) {
19334                outInfo.uid = ps.appId;
19335            }
19336
19337            if (outInfo != null && outInfo.removedChildPackages != null) {
19338                final int childCount = (ps.childPackageNames != null)
19339                        ? ps.childPackageNames.size() : 0;
19340                for (int i = 0; i < childCount; i++) {
19341                    String childPackageName = ps.childPackageNames.get(i);
19342                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19343                    if (childPs == null) {
19344                        return false;
19345                    }
19346                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19347                            childPackageName);
19348                    if (childInfo != null) {
19349                        childInfo.uid = childPs.appId;
19350                    }
19351                }
19352            }
19353        }
19354
19355        // Delete package data from internal structures and also remove data if flag is set
19356        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19357
19358        // Delete the child packages data
19359        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19360        for (int i = 0; i < childCount; i++) {
19361            PackageSetting childPs;
19362            synchronized (mPackages) {
19363                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19364            }
19365            if (childPs != null) {
19366                PackageRemovedInfo childOutInfo = (outInfo != null
19367                        && outInfo.removedChildPackages != null)
19368                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19369                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19370                        && (replacingPackage != null
19371                        && !replacingPackage.hasChildPackage(childPs.name))
19372                        ? flags & ~DELETE_KEEP_DATA : flags;
19373                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19374                        deleteFlags, writeSettings);
19375            }
19376        }
19377
19378        // Delete application code and resources only for parent packages
19379        if (ps.parentPackageName == null) {
19380            if (deleteCodeAndResources && (outInfo != null)) {
19381                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19382                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19383                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19384            }
19385        }
19386
19387        return true;
19388    }
19389
19390    @Override
19391    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19392            int userId) {
19393        mContext.enforceCallingOrSelfPermission(
19394                android.Manifest.permission.DELETE_PACKAGES, null);
19395        synchronized (mPackages) {
19396            // Cannot block uninstall of static shared libs as they are
19397            // considered a part of the using app (emulating static linking).
19398            // Also static libs are installed always on internal storage.
19399            PackageParser.Package pkg = mPackages.get(packageName);
19400            if (pkg != null && pkg.staticSharedLibName != null) {
19401                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19402                        + " providing static shared library: " + pkg.staticSharedLibName);
19403                return false;
19404            }
19405            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19406            mSettings.writePackageRestrictionsLPr(userId);
19407        }
19408        return true;
19409    }
19410
19411    @Override
19412    public boolean getBlockUninstallForUser(String packageName, int userId) {
19413        synchronized (mPackages) {
19414            final PackageSetting ps = mSettings.mPackages.get(packageName);
19415            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19416                return false;
19417            }
19418            return mSettings.getBlockUninstallLPr(userId, packageName);
19419        }
19420    }
19421
19422    @Override
19423    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19424        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19425        synchronized (mPackages) {
19426            PackageSetting ps = mSettings.mPackages.get(packageName);
19427            if (ps == null) {
19428                Log.w(TAG, "Package doesn't exist: " + packageName);
19429                return false;
19430            }
19431            if (systemUserApp) {
19432                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19433            } else {
19434                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19435            }
19436            mSettings.writeLPr();
19437        }
19438        return true;
19439    }
19440
19441    /*
19442     * This method handles package deletion in general
19443     */
19444    private boolean deletePackageLIF(String packageName, UserHandle user,
19445            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19446            PackageRemovedInfo outInfo, boolean writeSettings,
19447            PackageParser.Package replacingPackage) {
19448        if (packageName == null) {
19449            Slog.w(TAG, "Attempt to delete null packageName.");
19450            return false;
19451        }
19452
19453        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19454
19455        PackageSetting ps;
19456        synchronized (mPackages) {
19457            ps = mSettings.mPackages.get(packageName);
19458            if (ps == null) {
19459                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19460                return false;
19461            }
19462
19463            if (ps.parentPackageName != null && (!isSystemApp(ps)
19464                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19465                if (DEBUG_REMOVE) {
19466                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19467                            + ((user == null) ? UserHandle.USER_ALL : user));
19468                }
19469                final int removedUserId = (user != null) ? user.getIdentifier()
19470                        : UserHandle.USER_ALL;
19471                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19472                    return false;
19473                }
19474                markPackageUninstalledForUserLPw(ps, user);
19475                scheduleWritePackageRestrictionsLocked(user);
19476                return true;
19477            }
19478        }
19479
19480        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19481                && user.getIdentifier() != UserHandle.USER_ALL)) {
19482            // The caller is asking that the package only be deleted for a single
19483            // user.  To do this, we just mark its uninstalled state and delete
19484            // its data. If this is a system app, we only allow this to happen if
19485            // they have set the special DELETE_SYSTEM_APP which requests different
19486            // semantics than normal for uninstalling system apps.
19487            markPackageUninstalledForUserLPw(ps, user);
19488
19489            if (!isSystemApp(ps)) {
19490                // Do not uninstall the APK if an app should be cached
19491                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19492                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19493                    // Other user still have this package installed, so all
19494                    // we need to do is clear this user's data and save that
19495                    // it is uninstalled.
19496                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19497                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19498                        return false;
19499                    }
19500                    scheduleWritePackageRestrictionsLocked(user);
19501                    return true;
19502                } else {
19503                    // We need to set it back to 'installed' so the uninstall
19504                    // broadcasts will be sent correctly.
19505                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19506                    ps.setInstalled(true, user.getIdentifier());
19507                    mSettings.writeKernelMappingLPr(ps);
19508                }
19509            } else {
19510                // This is a system app, so we assume that the
19511                // other users still have this package installed, so all
19512                // we need to do is clear this user's data and save that
19513                // it is uninstalled.
19514                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19515                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19516                    return false;
19517                }
19518                scheduleWritePackageRestrictionsLocked(user);
19519                return true;
19520            }
19521        }
19522
19523        // If we are deleting a composite package for all users, keep track
19524        // of result for each child.
19525        if (ps.childPackageNames != null && outInfo != null) {
19526            synchronized (mPackages) {
19527                final int childCount = ps.childPackageNames.size();
19528                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19529                for (int i = 0; i < childCount; i++) {
19530                    String childPackageName = ps.childPackageNames.get(i);
19531                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19532                    childInfo.removedPackage = childPackageName;
19533                    childInfo.installerPackageName = ps.installerPackageName;
19534                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19535                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19536                    if (childPs != null) {
19537                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19538                    }
19539                }
19540            }
19541        }
19542
19543        boolean ret = false;
19544        if (isSystemApp(ps)) {
19545            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19546            // When an updated system application is deleted we delete the existing resources
19547            // as well and fall back to existing code in system partition
19548            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19549        } else {
19550            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19551            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19552                    outInfo, writeSettings, replacingPackage);
19553        }
19554
19555        // Take a note whether we deleted the package for all users
19556        if (outInfo != null) {
19557            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19558            if (outInfo.removedChildPackages != null) {
19559                synchronized (mPackages) {
19560                    final int childCount = outInfo.removedChildPackages.size();
19561                    for (int i = 0; i < childCount; i++) {
19562                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19563                        if (childInfo != null) {
19564                            childInfo.removedForAllUsers = mPackages.get(
19565                                    childInfo.removedPackage) == null;
19566                        }
19567                    }
19568                }
19569            }
19570            // If we uninstalled an update to a system app there may be some
19571            // child packages that appeared as they are declared in the system
19572            // app but were not declared in the update.
19573            if (isSystemApp(ps)) {
19574                synchronized (mPackages) {
19575                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19576                    final int childCount = (updatedPs.childPackageNames != null)
19577                            ? updatedPs.childPackageNames.size() : 0;
19578                    for (int i = 0; i < childCount; i++) {
19579                        String childPackageName = updatedPs.childPackageNames.get(i);
19580                        if (outInfo.removedChildPackages == null
19581                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19582                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19583                            if (childPs == null) {
19584                                continue;
19585                            }
19586                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19587                            installRes.name = childPackageName;
19588                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19589                            installRes.pkg = mPackages.get(childPackageName);
19590                            installRes.uid = childPs.pkg.applicationInfo.uid;
19591                            if (outInfo.appearedChildPackages == null) {
19592                                outInfo.appearedChildPackages = new ArrayMap<>();
19593                            }
19594                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19595                        }
19596                    }
19597                }
19598            }
19599        }
19600
19601        return ret;
19602    }
19603
19604    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19605        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19606                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19607        for (int nextUserId : userIds) {
19608            if (DEBUG_REMOVE) {
19609                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19610            }
19611            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19612                    false /*installed*/,
19613                    true /*stopped*/,
19614                    true /*notLaunched*/,
19615                    false /*hidden*/,
19616                    false /*suspended*/,
19617                    false /*instantApp*/,
19618                    null /*lastDisableAppCaller*/,
19619                    null /*enabledComponents*/,
19620                    null /*disabledComponents*/,
19621                    ps.readUserState(nextUserId).domainVerificationStatus,
19622                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19623        }
19624        mSettings.writeKernelMappingLPr(ps);
19625    }
19626
19627    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19628            PackageRemovedInfo outInfo) {
19629        final PackageParser.Package pkg;
19630        synchronized (mPackages) {
19631            pkg = mPackages.get(ps.name);
19632        }
19633
19634        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19635                : new int[] {userId};
19636        for (int nextUserId : userIds) {
19637            if (DEBUG_REMOVE) {
19638                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19639                        + nextUserId);
19640            }
19641
19642            destroyAppDataLIF(pkg, userId,
19643                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19644            destroyAppProfilesLIF(pkg, userId);
19645            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19646            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19647            schedulePackageCleaning(ps.name, nextUserId, false);
19648            synchronized (mPackages) {
19649                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19650                    scheduleWritePackageRestrictionsLocked(nextUserId);
19651                }
19652                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19653            }
19654        }
19655
19656        if (outInfo != null) {
19657            outInfo.removedPackage = ps.name;
19658            outInfo.installerPackageName = ps.installerPackageName;
19659            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19660            outInfo.removedAppId = ps.appId;
19661            outInfo.removedUsers = userIds;
19662            outInfo.broadcastUsers = userIds;
19663        }
19664
19665        return true;
19666    }
19667
19668    private final class ClearStorageConnection implements ServiceConnection {
19669        IMediaContainerService mContainerService;
19670
19671        @Override
19672        public void onServiceConnected(ComponentName name, IBinder service) {
19673            synchronized (this) {
19674                mContainerService = IMediaContainerService.Stub
19675                        .asInterface(Binder.allowBlocking(service));
19676                notifyAll();
19677            }
19678        }
19679
19680        @Override
19681        public void onServiceDisconnected(ComponentName name) {
19682        }
19683    }
19684
19685    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19686        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19687
19688        final boolean mounted;
19689        if (Environment.isExternalStorageEmulated()) {
19690            mounted = true;
19691        } else {
19692            final String status = Environment.getExternalStorageState();
19693
19694            mounted = status.equals(Environment.MEDIA_MOUNTED)
19695                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19696        }
19697
19698        if (!mounted) {
19699            return;
19700        }
19701
19702        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19703        int[] users;
19704        if (userId == UserHandle.USER_ALL) {
19705            users = sUserManager.getUserIds();
19706        } else {
19707            users = new int[] { userId };
19708        }
19709        final ClearStorageConnection conn = new ClearStorageConnection();
19710        if (mContext.bindServiceAsUser(
19711                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19712            try {
19713                for (int curUser : users) {
19714                    long timeout = SystemClock.uptimeMillis() + 5000;
19715                    synchronized (conn) {
19716                        long now;
19717                        while (conn.mContainerService == null &&
19718                                (now = SystemClock.uptimeMillis()) < timeout) {
19719                            try {
19720                                conn.wait(timeout - now);
19721                            } catch (InterruptedException e) {
19722                            }
19723                        }
19724                    }
19725                    if (conn.mContainerService == null) {
19726                        return;
19727                    }
19728
19729                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19730                    clearDirectory(conn.mContainerService,
19731                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19732                    if (allData) {
19733                        clearDirectory(conn.mContainerService,
19734                                userEnv.buildExternalStorageAppDataDirs(packageName));
19735                        clearDirectory(conn.mContainerService,
19736                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19737                    }
19738                }
19739            } finally {
19740                mContext.unbindService(conn);
19741            }
19742        }
19743    }
19744
19745    @Override
19746    public void clearApplicationProfileData(String packageName) {
19747        enforceSystemOrRoot("Only the system can clear all profile data");
19748
19749        final PackageParser.Package pkg;
19750        synchronized (mPackages) {
19751            pkg = mPackages.get(packageName);
19752        }
19753
19754        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19755            synchronized (mInstallLock) {
19756                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19757            }
19758        }
19759    }
19760
19761    @Override
19762    public void clearApplicationUserData(final String packageName,
19763            final IPackageDataObserver observer, final int userId) {
19764        mContext.enforceCallingOrSelfPermission(
19765                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19766
19767        final int callingUid = Binder.getCallingUid();
19768        enforceCrossUserPermission(callingUid, userId,
19769                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19770
19771        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19772        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19773            return;
19774        }
19775        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19776            throw new SecurityException("Cannot clear data for a protected package: "
19777                    + packageName);
19778        }
19779        // Queue up an async operation since the package deletion may take a little while.
19780        mHandler.post(new Runnable() {
19781            public void run() {
19782                mHandler.removeCallbacks(this);
19783                final boolean succeeded;
19784                try (PackageFreezer freezer = freezePackage(packageName,
19785                        "clearApplicationUserData")) {
19786                    synchronized (mInstallLock) {
19787                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19788                    }
19789                    clearExternalStorageDataSync(packageName, userId, true);
19790                    synchronized (mPackages) {
19791                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19792                                packageName, userId);
19793                    }
19794                }
19795                if (succeeded) {
19796                    // invoke DeviceStorageMonitor's update method to clear any notifications
19797                    DeviceStorageMonitorInternal dsm = LocalServices
19798                            .getService(DeviceStorageMonitorInternal.class);
19799                    if (dsm != null) {
19800                        dsm.checkMemory();
19801                    }
19802                }
19803                if(observer != null) {
19804                    try {
19805                        observer.onRemoveCompleted(packageName, succeeded);
19806                    } catch (RemoteException e) {
19807                        Log.i(TAG, "Observer no longer exists.");
19808                    }
19809                } //end if observer
19810            } //end run
19811        });
19812    }
19813
19814    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19815        if (packageName == null) {
19816            Slog.w(TAG, "Attempt to delete null packageName.");
19817            return false;
19818        }
19819
19820        // Try finding details about the requested package
19821        PackageParser.Package pkg;
19822        synchronized (mPackages) {
19823            pkg = mPackages.get(packageName);
19824            if (pkg == null) {
19825                final PackageSetting ps = mSettings.mPackages.get(packageName);
19826                if (ps != null) {
19827                    pkg = ps.pkg;
19828                }
19829            }
19830
19831            if (pkg == null) {
19832                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19833                return false;
19834            }
19835
19836            PackageSetting ps = (PackageSetting) pkg.mExtras;
19837            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19838        }
19839
19840        clearAppDataLIF(pkg, userId,
19841                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19842
19843        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19844        removeKeystoreDataIfNeeded(userId, appId);
19845
19846        UserManagerInternal umInternal = getUserManagerInternal();
19847        final int flags;
19848        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19849            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19850        } else if (umInternal.isUserRunning(userId)) {
19851            flags = StorageManager.FLAG_STORAGE_DE;
19852        } else {
19853            flags = 0;
19854        }
19855        prepareAppDataContentsLIF(pkg, userId, flags);
19856
19857        return true;
19858    }
19859
19860    /**
19861     * Reverts user permission state changes (permissions and flags) in
19862     * all packages for a given user.
19863     *
19864     * @param userId The device user for which to do a reset.
19865     */
19866    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19867        final int packageCount = mPackages.size();
19868        for (int i = 0; i < packageCount; i++) {
19869            PackageParser.Package pkg = mPackages.valueAt(i);
19870            PackageSetting ps = (PackageSetting) pkg.mExtras;
19871            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19872        }
19873    }
19874
19875    private void resetNetworkPolicies(int userId) {
19876        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19877    }
19878
19879    /**
19880     * Reverts user permission state changes (permissions and flags).
19881     *
19882     * @param ps The package for which to reset.
19883     * @param userId The device user for which to do a reset.
19884     */
19885    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19886            final PackageSetting ps, final int userId) {
19887        if (ps.pkg == null) {
19888            return;
19889        }
19890
19891        // These are flags that can change base on user actions.
19892        final int userSettableMask = FLAG_PERMISSION_USER_SET
19893                | FLAG_PERMISSION_USER_FIXED
19894                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19895                | FLAG_PERMISSION_REVIEW_REQUIRED;
19896
19897        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19898                | FLAG_PERMISSION_POLICY_FIXED;
19899
19900        boolean writeInstallPermissions = false;
19901        boolean writeRuntimePermissions = false;
19902
19903        final int permissionCount = ps.pkg.requestedPermissions.size();
19904        for (int i = 0; i < permissionCount; i++) {
19905            String permission = ps.pkg.requestedPermissions.get(i);
19906
19907            BasePermission bp = mSettings.mPermissions.get(permission);
19908            if (bp == null) {
19909                continue;
19910            }
19911
19912            // If shared user we just reset the state to which only this app contributed.
19913            if (ps.sharedUser != null) {
19914                boolean used = false;
19915                final int packageCount = ps.sharedUser.packages.size();
19916                for (int j = 0; j < packageCount; j++) {
19917                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19918                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19919                            && pkg.pkg.requestedPermissions.contains(permission)) {
19920                        used = true;
19921                        break;
19922                    }
19923                }
19924                if (used) {
19925                    continue;
19926                }
19927            }
19928
19929            PermissionsState permissionsState = ps.getPermissionsState();
19930
19931            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19932
19933            // Always clear the user settable flags.
19934            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19935                    bp.name) != null;
19936            // If permission review is enabled and this is a legacy app, mark the
19937            // permission as requiring a review as this is the initial state.
19938            int flags = 0;
19939            if (mPermissionReviewRequired
19940                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19941                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19942            }
19943            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19944                if (hasInstallState) {
19945                    writeInstallPermissions = true;
19946                } else {
19947                    writeRuntimePermissions = true;
19948                }
19949            }
19950
19951            // Below is only runtime permission handling.
19952            if (!bp.isRuntime()) {
19953                continue;
19954            }
19955
19956            // Never clobber system or policy.
19957            if ((oldFlags & policyOrSystemFlags) != 0) {
19958                continue;
19959            }
19960
19961            // If this permission was granted by default, make sure it is.
19962            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19963                if (permissionsState.grantRuntimePermission(bp, userId)
19964                        != PERMISSION_OPERATION_FAILURE) {
19965                    writeRuntimePermissions = true;
19966                }
19967            // If permission review is enabled the permissions for a legacy apps
19968            // are represented as constantly granted runtime ones, so don't revoke.
19969            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19970                // Otherwise, reset the permission.
19971                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19972                switch (revokeResult) {
19973                    case PERMISSION_OPERATION_SUCCESS:
19974                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19975                        writeRuntimePermissions = true;
19976                        final int appId = ps.appId;
19977                        mHandler.post(new Runnable() {
19978                            @Override
19979                            public void run() {
19980                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19981                            }
19982                        });
19983                    } break;
19984                }
19985            }
19986        }
19987
19988        // Synchronously write as we are taking permissions away.
19989        if (writeRuntimePermissions) {
19990            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19991        }
19992
19993        // Synchronously write as we are taking permissions away.
19994        if (writeInstallPermissions) {
19995            mSettings.writeLPr();
19996        }
19997    }
19998
19999    /**
20000     * Remove entries from the keystore daemon. Will only remove it if the
20001     * {@code appId} is valid.
20002     */
20003    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20004        if (appId < 0) {
20005            return;
20006        }
20007
20008        final KeyStore keyStore = KeyStore.getInstance();
20009        if (keyStore != null) {
20010            if (userId == UserHandle.USER_ALL) {
20011                for (final int individual : sUserManager.getUserIds()) {
20012                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20013                }
20014            } else {
20015                keyStore.clearUid(UserHandle.getUid(userId, appId));
20016            }
20017        } else {
20018            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20019        }
20020    }
20021
20022    @Override
20023    public void deleteApplicationCacheFiles(final String packageName,
20024            final IPackageDataObserver observer) {
20025        final int userId = UserHandle.getCallingUserId();
20026        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20027    }
20028
20029    @Override
20030    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20031            final IPackageDataObserver observer) {
20032        final int callingUid = Binder.getCallingUid();
20033        mContext.enforceCallingOrSelfPermission(
20034                android.Manifest.permission.DELETE_CACHE_FILES, null);
20035        enforceCrossUserPermission(callingUid, userId,
20036                /* requireFullPermission= */ true, /* checkShell= */ false,
20037                "delete application cache files");
20038        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20039                android.Manifest.permission.ACCESS_INSTANT_APPS);
20040
20041        final PackageParser.Package pkg;
20042        synchronized (mPackages) {
20043            pkg = mPackages.get(packageName);
20044        }
20045
20046        // Queue up an async operation since the package deletion may take a little while.
20047        mHandler.post(new Runnable() {
20048            public void run() {
20049                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20050                boolean doClearData = true;
20051                if (ps != null) {
20052                    final boolean targetIsInstantApp =
20053                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20054                    doClearData = !targetIsInstantApp
20055                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20056                }
20057                if (doClearData) {
20058                    synchronized (mInstallLock) {
20059                        final int flags = StorageManager.FLAG_STORAGE_DE
20060                                | StorageManager.FLAG_STORAGE_CE;
20061                        // We're only clearing cache files, so we don't care if the
20062                        // app is unfrozen and still able to run
20063                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20064                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20065                    }
20066                    clearExternalStorageDataSync(packageName, userId, false);
20067                }
20068                if (observer != null) {
20069                    try {
20070                        observer.onRemoveCompleted(packageName, true);
20071                    } catch (RemoteException e) {
20072                        Log.i(TAG, "Observer no longer exists.");
20073                    }
20074                }
20075            }
20076        });
20077    }
20078
20079    @Override
20080    public void getPackageSizeInfo(final String packageName, int userHandle,
20081            final IPackageStatsObserver observer) {
20082        throw new UnsupportedOperationException(
20083                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20084    }
20085
20086    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20087        final PackageSetting ps;
20088        synchronized (mPackages) {
20089            ps = mSettings.mPackages.get(packageName);
20090            if (ps == null) {
20091                Slog.w(TAG, "Failed to find settings for " + packageName);
20092                return false;
20093            }
20094        }
20095
20096        final String[] packageNames = { packageName };
20097        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20098        final String[] codePaths = { ps.codePathString };
20099
20100        try {
20101            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20102                    ps.appId, ceDataInodes, codePaths, stats);
20103
20104            // For now, ignore code size of packages on system partition
20105            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20106                stats.codeSize = 0;
20107            }
20108
20109            // External clients expect these to be tracked separately
20110            stats.dataSize -= stats.cacheSize;
20111
20112        } catch (InstallerException e) {
20113            Slog.w(TAG, String.valueOf(e));
20114            return false;
20115        }
20116
20117        return true;
20118    }
20119
20120    private int getUidTargetSdkVersionLockedLPr(int uid) {
20121        Object obj = mSettings.getUserIdLPr(uid);
20122        if (obj instanceof SharedUserSetting) {
20123            final SharedUserSetting sus = (SharedUserSetting) obj;
20124            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20125            final Iterator<PackageSetting> it = sus.packages.iterator();
20126            while (it.hasNext()) {
20127                final PackageSetting ps = it.next();
20128                if (ps.pkg != null) {
20129                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20130                    if (v < vers) vers = v;
20131                }
20132            }
20133            return vers;
20134        } else if (obj instanceof PackageSetting) {
20135            final PackageSetting ps = (PackageSetting) obj;
20136            if (ps.pkg != null) {
20137                return ps.pkg.applicationInfo.targetSdkVersion;
20138            }
20139        }
20140        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20141    }
20142
20143    @Override
20144    public void addPreferredActivity(IntentFilter filter, int match,
20145            ComponentName[] set, ComponentName activity, int userId) {
20146        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20147                "Adding preferred");
20148    }
20149
20150    private void addPreferredActivityInternal(IntentFilter filter, int match,
20151            ComponentName[] set, ComponentName activity, boolean always, int userId,
20152            String opname) {
20153        // writer
20154        int callingUid = Binder.getCallingUid();
20155        enforceCrossUserPermission(callingUid, userId,
20156                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20157        if (filter.countActions() == 0) {
20158            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20159            return;
20160        }
20161        synchronized (mPackages) {
20162            if (mContext.checkCallingOrSelfPermission(
20163                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20164                    != PackageManager.PERMISSION_GRANTED) {
20165                if (getUidTargetSdkVersionLockedLPr(callingUid)
20166                        < Build.VERSION_CODES.FROYO) {
20167                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20168                            + callingUid);
20169                    return;
20170                }
20171                mContext.enforceCallingOrSelfPermission(
20172                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20173            }
20174
20175            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20176            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20177                    + userId + ":");
20178            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20179            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20180            scheduleWritePackageRestrictionsLocked(userId);
20181            postPreferredActivityChangedBroadcast(userId);
20182        }
20183    }
20184
20185    private void postPreferredActivityChangedBroadcast(int userId) {
20186        mHandler.post(() -> {
20187            final IActivityManager am = ActivityManager.getService();
20188            if (am == null) {
20189                return;
20190            }
20191
20192            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20193            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20194            try {
20195                am.broadcastIntent(null, intent, null, null,
20196                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20197                        null, false, false, userId);
20198            } catch (RemoteException e) {
20199            }
20200        });
20201    }
20202
20203    @Override
20204    public void replacePreferredActivity(IntentFilter filter, int match,
20205            ComponentName[] set, ComponentName activity, int userId) {
20206        if (filter.countActions() != 1) {
20207            throw new IllegalArgumentException(
20208                    "replacePreferredActivity expects filter to have only 1 action.");
20209        }
20210        if (filter.countDataAuthorities() != 0
20211                || filter.countDataPaths() != 0
20212                || filter.countDataSchemes() > 1
20213                || filter.countDataTypes() != 0) {
20214            throw new IllegalArgumentException(
20215                    "replacePreferredActivity expects filter to have no data authorities, " +
20216                    "paths, or types; and at most one scheme.");
20217        }
20218
20219        final int callingUid = Binder.getCallingUid();
20220        enforceCrossUserPermission(callingUid, userId,
20221                true /* requireFullPermission */, false /* checkShell */,
20222                "replace preferred activity");
20223        synchronized (mPackages) {
20224            if (mContext.checkCallingOrSelfPermission(
20225                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20226                    != PackageManager.PERMISSION_GRANTED) {
20227                if (getUidTargetSdkVersionLockedLPr(callingUid)
20228                        < Build.VERSION_CODES.FROYO) {
20229                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20230                            + Binder.getCallingUid());
20231                    return;
20232                }
20233                mContext.enforceCallingOrSelfPermission(
20234                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20235            }
20236
20237            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20238            if (pir != null) {
20239                // Get all of the existing entries that exactly match this filter.
20240                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20241                if (existing != null && existing.size() == 1) {
20242                    PreferredActivity cur = existing.get(0);
20243                    if (DEBUG_PREFERRED) {
20244                        Slog.i(TAG, "Checking replace of preferred:");
20245                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20246                        if (!cur.mPref.mAlways) {
20247                            Slog.i(TAG, "  -- CUR; not mAlways!");
20248                        } else {
20249                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20250                            Slog.i(TAG, "  -- CUR: mSet="
20251                                    + Arrays.toString(cur.mPref.mSetComponents));
20252                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20253                            Slog.i(TAG, "  -- NEW: mMatch="
20254                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20255                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20256                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20257                        }
20258                    }
20259                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20260                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20261                            && cur.mPref.sameSet(set)) {
20262                        // Setting the preferred activity to what it happens to be already
20263                        if (DEBUG_PREFERRED) {
20264                            Slog.i(TAG, "Replacing with same preferred activity "
20265                                    + cur.mPref.mShortComponent + " for user "
20266                                    + userId + ":");
20267                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20268                        }
20269                        return;
20270                    }
20271                }
20272
20273                if (existing != null) {
20274                    if (DEBUG_PREFERRED) {
20275                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20276                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20277                    }
20278                    for (int i = 0; i < existing.size(); i++) {
20279                        PreferredActivity pa = existing.get(i);
20280                        if (DEBUG_PREFERRED) {
20281                            Slog.i(TAG, "Removing existing preferred activity "
20282                                    + pa.mPref.mComponent + ":");
20283                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20284                        }
20285                        pir.removeFilter(pa);
20286                    }
20287                }
20288            }
20289            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20290                    "Replacing preferred");
20291        }
20292    }
20293
20294    @Override
20295    public void clearPackagePreferredActivities(String packageName) {
20296        final int callingUid = Binder.getCallingUid();
20297        if (getInstantAppPackageName(callingUid) != null) {
20298            return;
20299        }
20300        // writer
20301        synchronized (mPackages) {
20302            PackageParser.Package pkg = mPackages.get(packageName);
20303            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20304                if (mContext.checkCallingOrSelfPermission(
20305                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20306                        != PackageManager.PERMISSION_GRANTED) {
20307                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20308                            < Build.VERSION_CODES.FROYO) {
20309                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20310                                + callingUid);
20311                        return;
20312                    }
20313                    mContext.enforceCallingOrSelfPermission(
20314                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20315                }
20316            }
20317            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20318            if (ps != null
20319                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20320                return;
20321            }
20322            int user = UserHandle.getCallingUserId();
20323            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20324                scheduleWritePackageRestrictionsLocked(user);
20325            }
20326        }
20327    }
20328
20329    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20330    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20331        ArrayList<PreferredActivity> removed = null;
20332        boolean changed = false;
20333        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20334            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20335            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20336            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20337                continue;
20338            }
20339            Iterator<PreferredActivity> it = pir.filterIterator();
20340            while (it.hasNext()) {
20341                PreferredActivity pa = it.next();
20342                // Mark entry for removal only if it matches the package name
20343                // and the entry is of type "always".
20344                if (packageName == null ||
20345                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20346                                && pa.mPref.mAlways)) {
20347                    if (removed == null) {
20348                        removed = new ArrayList<PreferredActivity>();
20349                    }
20350                    removed.add(pa);
20351                }
20352            }
20353            if (removed != null) {
20354                for (int j=0; j<removed.size(); j++) {
20355                    PreferredActivity pa = removed.get(j);
20356                    pir.removeFilter(pa);
20357                }
20358                changed = true;
20359            }
20360        }
20361        if (changed) {
20362            postPreferredActivityChangedBroadcast(userId);
20363        }
20364        return changed;
20365    }
20366
20367    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20368    private void clearIntentFilterVerificationsLPw(int userId) {
20369        final int packageCount = mPackages.size();
20370        for (int i = 0; i < packageCount; i++) {
20371            PackageParser.Package pkg = mPackages.valueAt(i);
20372            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20373        }
20374    }
20375
20376    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20377    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20378        if (userId == UserHandle.USER_ALL) {
20379            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20380                    sUserManager.getUserIds())) {
20381                for (int oneUserId : sUserManager.getUserIds()) {
20382                    scheduleWritePackageRestrictionsLocked(oneUserId);
20383                }
20384            }
20385        } else {
20386            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20387                scheduleWritePackageRestrictionsLocked(userId);
20388            }
20389        }
20390    }
20391
20392    /** Clears state for all users, and touches intent filter verification policy */
20393    void clearDefaultBrowserIfNeeded(String packageName) {
20394        for (int oneUserId : sUserManager.getUserIds()) {
20395            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20396        }
20397    }
20398
20399    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20400        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20401        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20402            if (packageName.equals(defaultBrowserPackageName)) {
20403                setDefaultBrowserPackageName(null, userId);
20404            }
20405        }
20406    }
20407
20408    @Override
20409    public void resetApplicationPreferences(int userId) {
20410        mContext.enforceCallingOrSelfPermission(
20411                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20412        final long identity = Binder.clearCallingIdentity();
20413        // writer
20414        try {
20415            synchronized (mPackages) {
20416                clearPackagePreferredActivitiesLPw(null, userId);
20417                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20418                // TODO: We have to reset the default SMS and Phone. This requires
20419                // significant refactoring to keep all default apps in the package
20420                // manager (cleaner but more work) or have the services provide
20421                // callbacks to the package manager to request a default app reset.
20422                applyFactoryDefaultBrowserLPw(userId);
20423                clearIntentFilterVerificationsLPw(userId);
20424                primeDomainVerificationsLPw(userId);
20425                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20426                scheduleWritePackageRestrictionsLocked(userId);
20427            }
20428            resetNetworkPolicies(userId);
20429        } finally {
20430            Binder.restoreCallingIdentity(identity);
20431        }
20432    }
20433
20434    @Override
20435    public int getPreferredActivities(List<IntentFilter> outFilters,
20436            List<ComponentName> outActivities, String packageName) {
20437        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20438            return 0;
20439        }
20440        int num = 0;
20441        final int userId = UserHandle.getCallingUserId();
20442        // reader
20443        synchronized (mPackages) {
20444            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20445            if (pir != null) {
20446                final Iterator<PreferredActivity> it = pir.filterIterator();
20447                while (it.hasNext()) {
20448                    final PreferredActivity pa = it.next();
20449                    if (packageName == null
20450                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20451                                    && pa.mPref.mAlways)) {
20452                        if (outFilters != null) {
20453                            outFilters.add(new IntentFilter(pa));
20454                        }
20455                        if (outActivities != null) {
20456                            outActivities.add(pa.mPref.mComponent);
20457                        }
20458                    }
20459                }
20460            }
20461        }
20462
20463        return num;
20464    }
20465
20466    @Override
20467    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20468            int userId) {
20469        int callingUid = Binder.getCallingUid();
20470        if (callingUid != Process.SYSTEM_UID) {
20471            throw new SecurityException(
20472                    "addPersistentPreferredActivity can only be run by the system");
20473        }
20474        if (filter.countActions() == 0) {
20475            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20476            return;
20477        }
20478        synchronized (mPackages) {
20479            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20480                    ":");
20481            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20482            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20483                    new PersistentPreferredActivity(filter, activity));
20484            scheduleWritePackageRestrictionsLocked(userId);
20485            postPreferredActivityChangedBroadcast(userId);
20486        }
20487    }
20488
20489    @Override
20490    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20491        int callingUid = Binder.getCallingUid();
20492        if (callingUid != Process.SYSTEM_UID) {
20493            throw new SecurityException(
20494                    "clearPackagePersistentPreferredActivities can only be run by the system");
20495        }
20496        ArrayList<PersistentPreferredActivity> removed = null;
20497        boolean changed = false;
20498        synchronized (mPackages) {
20499            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20500                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20501                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20502                        .valueAt(i);
20503                if (userId != thisUserId) {
20504                    continue;
20505                }
20506                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20507                while (it.hasNext()) {
20508                    PersistentPreferredActivity ppa = it.next();
20509                    // Mark entry for removal only if it matches the package name.
20510                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20511                        if (removed == null) {
20512                            removed = new ArrayList<PersistentPreferredActivity>();
20513                        }
20514                        removed.add(ppa);
20515                    }
20516                }
20517                if (removed != null) {
20518                    for (int j=0; j<removed.size(); j++) {
20519                        PersistentPreferredActivity ppa = removed.get(j);
20520                        ppir.removeFilter(ppa);
20521                    }
20522                    changed = true;
20523                }
20524            }
20525
20526            if (changed) {
20527                scheduleWritePackageRestrictionsLocked(userId);
20528                postPreferredActivityChangedBroadcast(userId);
20529            }
20530        }
20531    }
20532
20533    /**
20534     * Common machinery for picking apart a restored XML blob and passing
20535     * it to a caller-supplied functor to be applied to the running system.
20536     */
20537    private void restoreFromXml(XmlPullParser parser, int userId,
20538            String expectedStartTag, BlobXmlRestorer functor)
20539            throws IOException, XmlPullParserException {
20540        int type;
20541        while ((type = parser.next()) != XmlPullParser.START_TAG
20542                && type != XmlPullParser.END_DOCUMENT) {
20543        }
20544        if (type != XmlPullParser.START_TAG) {
20545            // oops didn't find a start tag?!
20546            if (DEBUG_BACKUP) {
20547                Slog.e(TAG, "Didn't find start tag during restore");
20548            }
20549            return;
20550        }
20551Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20552        // this is supposed to be TAG_PREFERRED_BACKUP
20553        if (!expectedStartTag.equals(parser.getName())) {
20554            if (DEBUG_BACKUP) {
20555                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20556            }
20557            return;
20558        }
20559
20560        // skip interfering stuff, then we're aligned with the backing implementation
20561        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20562Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20563        functor.apply(parser, userId);
20564    }
20565
20566    private interface BlobXmlRestorer {
20567        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20568    }
20569
20570    /**
20571     * Non-Binder method, support for the backup/restore mechanism: write the
20572     * full set of preferred activities in its canonical XML format.  Returns the
20573     * XML output as a byte array, or null if there is none.
20574     */
20575    @Override
20576    public byte[] getPreferredActivityBackup(int userId) {
20577        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20578            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20579        }
20580
20581        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20582        try {
20583            final XmlSerializer serializer = new FastXmlSerializer();
20584            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20585            serializer.startDocument(null, true);
20586            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20587
20588            synchronized (mPackages) {
20589                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20590            }
20591
20592            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20593            serializer.endDocument();
20594            serializer.flush();
20595        } catch (Exception e) {
20596            if (DEBUG_BACKUP) {
20597                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20598            }
20599            return null;
20600        }
20601
20602        return dataStream.toByteArray();
20603    }
20604
20605    @Override
20606    public void restorePreferredActivities(byte[] backup, int userId) {
20607        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20608            throw new SecurityException("Only the system may call restorePreferredActivities()");
20609        }
20610
20611        try {
20612            final XmlPullParser parser = Xml.newPullParser();
20613            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20614            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20615                    new BlobXmlRestorer() {
20616                        @Override
20617                        public void apply(XmlPullParser parser, int userId)
20618                                throws XmlPullParserException, IOException {
20619                            synchronized (mPackages) {
20620                                mSettings.readPreferredActivitiesLPw(parser, userId);
20621                            }
20622                        }
20623                    } );
20624        } catch (Exception e) {
20625            if (DEBUG_BACKUP) {
20626                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20627            }
20628        }
20629    }
20630
20631    /**
20632     * Non-Binder method, support for the backup/restore mechanism: write the
20633     * default browser (etc) settings in its canonical XML format.  Returns the default
20634     * browser XML representation as a byte array, or null if there is none.
20635     */
20636    @Override
20637    public byte[] getDefaultAppsBackup(int userId) {
20638        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20639            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20640        }
20641
20642        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20643        try {
20644            final XmlSerializer serializer = new FastXmlSerializer();
20645            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20646            serializer.startDocument(null, true);
20647            serializer.startTag(null, TAG_DEFAULT_APPS);
20648
20649            synchronized (mPackages) {
20650                mSettings.writeDefaultAppsLPr(serializer, userId);
20651            }
20652
20653            serializer.endTag(null, TAG_DEFAULT_APPS);
20654            serializer.endDocument();
20655            serializer.flush();
20656        } catch (Exception e) {
20657            if (DEBUG_BACKUP) {
20658                Slog.e(TAG, "Unable to write default apps for backup", e);
20659            }
20660            return null;
20661        }
20662
20663        return dataStream.toByteArray();
20664    }
20665
20666    @Override
20667    public void restoreDefaultApps(byte[] backup, int userId) {
20668        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20669            throw new SecurityException("Only the system may call restoreDefaultApps()");
20670        }
20671
20672        try {
20673            final XmlPullParser parser = Xml.newPullParser();
20674            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20675            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20676                    new BlobXmlRestorer() {
20677                        @Override
20678                        public void apply(XmlPullParser parser, int userId)
20679                                throws XmlPullParserException, IOException {
20680                            synchronized (mPackages) {
20681                                mSettings.readDefaultAppsLPw(parser, userId);
20682                            }
20683                        }
20684                    } );
20685        } catch (Exception e) {
20686            if (DEBUG_BACKUP) {
20687                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20688            }
20689        }
20690    }
20691
20692    @Override
20693    public byte[] getIntentFilterVerificationBackup(int userId) {
20694        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20695            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20696        }
20697
20698        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20699        try {
20700            final XmlSerializer serializer = new FastXmlSerializer();
20701            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20702            serializer.startDocument(null, true);
20703            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20704
20705            synchronized (mPackages) {
20706                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20707            }
20708
20709            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20710            serializer.endDocument();
20711            serializer.flush();
20712        } catch (Exception e) {
20713            if (DEBUG_BACKUP) {
20714                Slog.e(TAG, "Unable to write default apps for backup", e);
20715            }
20716            return null;
20717        }
20718
20719        return dataStream.toByteArray();
20720    }
20721
20722    @Override
20723    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20724        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20725            throw new SecurityException("Only the system may call restorePreferredActivities()");
20726        }
20727
20728        try {
20729            final XmlPullParser parser = Xml.newPullParser();
20730            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20731            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20732                    new BlobXmlRestorer() {
20733                        @Override
20734                        public void apply(XmlPullParser parser, int userId)
20735                                throws XmlPullParserException, IOException {
20736                            synchronized (mPackages) {
20737                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20738                                mSettings.writeLPr();
20739                            }
20740                        }
20741                    } );
20742        } catch (Exception e) {
20743            if (DEBUG_BACKUP) {
20744                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20745            }
20746        }
20747    }
20748
20749    @Override
20750    public byte[] getPermissionGrantBackup(int userId) {
20751        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20752            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20753        }
20754
20755        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20756        try {
20757            final XmlSerializer serializer = new FastXmlSerializer();
20758            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20759            serializer.startDocument(null, true);
20760            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20761
20762            synchronized (mPackages) {
20763                serializeRuntimePermissionGrantsLPr(serializer, userId);
20764            }
20765
20766            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20767            serializer.endDocument();
20768            serializer.flush();
20769        } catch (Exception e) {
20770            if (DEBUG_BACKUP) {
20771                Slog.e(TAG, "Unable to write default apps for backup", e);
20772            }
20773            return null;
20774        }
20775
20776        return dataStream.toByteArray();
20777    }
20778
20779    @Override
20780    public void restorePermissionGrants(byte[] backup, int userId) {
20781        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20782            throw new SecurityException("Only the system may call restorePermissionGrants()");
20783        }
20784
20785        try {
20786            final XmlPullParser parser = Xml.newPullParser();
20787            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20788            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20789                    new BlobXmlRestorer() {
20790                        @Override
20791                        public void apply(XmlPullParser parser, int userId)
20792                                throws XmlPullParserException, IOException {
20793                            synchronized (mPackages) {
20794                                processRestoredPermissionGrantsLPr(parser, userId);
20795                            }
20796                        }
20797                    } );
20798        } catch (Exception e) {
20799            if (DEBUG_BACKUP) {
20800                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20801            }
20802        }
20803    }
20804
20805    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20806            throws IOException {
20807        serializer.startTag(null, TAG_ALL_GRANTS);
20808
20809        final int N = mSettings.mPackages.size();
20810        for (int i = 0; i < N; i++) {
20811            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20812            boolean pkgGrantsKnown = false;
20813
20814            PermissionsState packagePerms = ps.getPermissionsState();
20815
20816            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20817                final int grantFlags = state.getFlags();
20818                // only look at grants that are not system/policy fixed
20819                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20820                    final boolean isGranted = state.isGranted();
20821                    // And only back up the user-twiddled state bits
20822                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20823                        final String packageName = mSettings.mPackages.keyAt(i);
20824                        if (!pkgGrantsKnown) {
20825                            serializer.startTag(null, TAG_GRANT);
20826                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20827                            pkgGrantsKnown = true;
20828                        }
20829
20830                        final boolean userSet =
20831                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20832                        final boolean userFixed =
20833                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20834                        final boolean revoke =
20835                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20836
20837                        serializer.startTag(null, TAG_PERMISSION);
20838                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20839                        if (isGranted) {
20840                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20841                        }
20842                        if (userSet) {
20843                            serializer.attribute(null, ATTR_USER_SET, "true");
20844                        }
20845                        if (userFixed) {
20846                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20847                        }
20848                        if (revoke) {
20849                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20850                        }
20851                        serializer.endTag(null, TAG_PERMISSION);
20852                    }
20853                }
20854            }
20855
20856            if (pkgGrantsKnown) {
20857                serializer.endTag(null, TAG_GRANT);
20858            }
20859        }
20860
20861        serializer.endTag(null, TAG_ALL_GRANTS);
20862    }
20863
20864    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20865            throws XmlPullParserException, IOException {
20866        String pkgName = null;
20867        int outerDepth = parser.getDepth();
20868        int type;
20869        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20870                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20871            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20872                continue;
20873            }
20874
20875            final String tagName = parser.getName();
20876            if (tagName.equals(TAG_GRANT)) {
20877                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20878                if (DEBUG_BACKUP) {
20879                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20880                }
20881            } else if (tagName.equals(TAG_PERMISSION)) {
20882
20883                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20884                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20885
20886                int newFlagSet = 0;
20887                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20888                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20889                }
20890                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20891                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20892                }
20893                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20894                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20895                }
20896                if (DEBUG_BACKUP) {
20897                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20898                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20899                }
20900                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20901                if (ps != null) {
20902                    // Already installed so we apply the grant immediately
20903                    if (DEBUG_BACKUP) {
20904                        Slog.v(TAG, "        + already installed; applying");
20905                    }
20906                    PermissionsState perms = ps.getPermissionsState();
20907                    BasePermission bp = mSettings.mPermissions.get(permName);
20908                    if (bp != null) {
20909                        if (isGranted) {
20910                            perms.grantRuntimePermission(bp, userId);
20911                        }
20912                        if (newFlagSet != 0) {
20913                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20914                        }
20915                    }
20916                } else {
20917                    // Need to wait for post-restore install to apply the grant
20918                    if (DEBUG_BACKUP) {
20919                        Slog.v(TAG, "        - not yet installed; saving for later");
20920                    }
20921                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20922                            isGranted, newFlagSet, userId);
20923                }
20924            } else {
20925                PackageManagerService.reportSettingsProblem(Log.WARN,
20926                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20927                XmlUtils.skipCurrentTag(parser);
20928            }
20929        }
20930
20931        scheduleWriteSettingsLocked();
20932        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20933    }
20934
20935    @Override
20936    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20937            int sourceUserId, int targetUserId, int flags) {
20938        mContext.enforceCallingOrSelfPermission(
20939                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20940        int callingUid = Binder.getCallingUid();
20941        enforceOwnerRights(ownerPackage, callingUid);
20942        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20943        if (intentFilter.countActions() == 0) {
20944            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20945            return;
20946        }
20947        synchronized (mPackages) {
20948            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20949                    ownerPackage, targetUserId, flags);
20950            CrossProfileIntentResolver resolver =
20951                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20952            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20953            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20954            if (existing != null) {
20955                int size = existing.size();
20956                for (int i = 0; i < size; i++) {
20957                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20958                        return;
20959                    }
20960                }
20961            }
20962            resolver.addFilter(newFilter);
20963            scheduleWritePackageRestrictionsLocked(sourceUserId);
20964        }
20965    }
20966
20967    @Override
20968    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20969        mContext.enforceCallingOrSelfPermission(
20970                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20971        final int callingUid = Binder.getCallingUid();
20972        enforceOwnerRights(ownerPackage, callingUid);
20973        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20974        synchronized (mPackages) {
20975            CrossProfileIntentResolver resolver =
20976                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20977            ArraySet<CrossProfileIntentFilter> set =
20978                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20979            for (CrossProfileIntentFilter filter : set) {
20980                if (filter.getOwnerPackage().equals(ownerPackage)) {
20981                    resolver.removeFilter(filter);
20982                }
20983            }
20984            scheduleWritePackageRestrictionsLocked(sourceUserId);
20985        }
20986    }
20987
20988    // Enforcing that callingUid is owning pkg on userId
20989    private void enforceOwnerRights(String pkg, int callingUid) {
20990        // The system owns everything.
20991        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20992            return;
20993        }
20994        final int callingUserId = UserHandle.getUserId(callingUid);
20995        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20996        if (pi == null) {
20997            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20998                    + callingUserId);
20999        }
21000        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21001            throw new SecurityException("Calling uid " + callingUid
21002                    + " does not own package " + pkg);
21003        }
21004    }
21005
21006    @Override
21007    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21008        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21009            return null;
21010        }
21011        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21012    }
21013
21014    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21015        UserManagerService ums = UserManagerService.getInstance();
21016        if (ums != null) {
21017            final UserInfo parent = ums.getProfileParent(userId);
21018            final int launcherUid = (parent != null) ? parent.id : userId;
21019            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21020            if (launcherComponent != null) {
21021                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21022                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21023                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21024                        .setPackage(launcherComponent.getPackageName());
21025                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21026            }
21027        }
21028    }
21029
21030    /**
21031     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21032     * then reports the most likely home activity or null if there are more than one.
21033     */
21034    private ComponentName getDefaultHomeActivity(int userId) {
21035        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21036        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21037        if (cn != null) {
21038            return cn;
21039        }
21040
21041        // Find the launcher with the highest priority and return that component if there are no
21042        // other home activity with the same priority.
21043        int lastPriority = Integer.MIN_VALUE;
21044        ComponentName lastComponent = null;
21045        final int size = allHomeCandidates.size();
21046        for (int i = 0; i < size; i++) {
21047            final ResolveInfo ri = allHomeCandidates.get(i);
21048            if (ri.priority > lastPriority) {
21049                lastComponent = ri.activityInfo.getComponentName();
21050                lastPriority = ri.priority;
21051            } else if (ri.priority == lastPriority) {
21052                // Two components found with same priority.
21053                lastComponent = null;
21054            }
21055        }
21056        return lastComponent;
21057    }
21058
21059    private Intent getHomeIntent() {
21060        Intent intent = new Intent(Intent.ACTION_MAIN);
21061        intent.addCategory(Intent.CATEGORY_HOME);
21062        intent.addCategory(Intent.CATEGORY_DEFAULT);
21063        return intent;
21064    }
21065
21066    private IntentFilter getHomeFilter() {
21067        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21068        filter.addCategory(Intent.CATEGORY_HOME);
21069        filter.addCategory(Intent.CATEGORY_DEFAULT);
21070        return filter;
21071    }
21072
21073    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21074            int userId) {
21075        Intent intent  = getHomeIntent();
21076        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21077                PackageManager.GET_META_DATA, userId);
21078        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21079                true, false, false, userId);
21080
21081        allHomeCandidates.clear();
21082        if (list != null) {
21083            for (ResolveInfo ri : list) {
21084                allHomeCandidates.add(ri);
21085            }
21086        }
21087        return (preferred == null || preferred.activityInfo == null)
21088                ? null
21089                : new ComponentName(preferred.activityInfo.packageName,
21090                        preferred.activityInfo.name);
21091    }
21092
21093    @Override
21094    public void setHomeActivity(ComponentName comp, int userId) {
21095        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21096            return;
21097        }
21098        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21099        getHomeActivitiesAsUser(homeActivities, userId);
21100
21101        boolean found = false;
21102
21103        final int size = homeActivities.size();
21104        final ComponentName[] set = new ComponentName[size];
21105        for (int i = 0; i < size; i++) {
21106            final ResolveInfo candidate = homeActivities.get(i);
21107            final ActivityInfo info = candidate.activityInfo;
21108            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21109            set[i] = activityName;
21110            if (!found && activityName.equals(comp)) {
21111                found = true;
21112            }
21113        }
21114        if (!found) {
21115            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21116                    + userId);
21117        }
21118        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21119                set, comp, userId);
21120    }
21121
21122    private @Nullable String getSetupWizardPackageName() {
21123        final Intent intent = new Intent(Intent.ACTION_MAIN);
21124        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21125
21126        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21127                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21128                        | MATCH_DISABLED_COMPONENTS,
21129                UserHandle.myUserId());
21130        if (matches.size() == 1) {
21131            return matches.get(0).getComponentInfo().packageName;
21132        } else {
21133            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21134                    + ": matches=" + matches);
21135            return null;
21136        }
21137    }
21138
21139    private @Nullable String getStorageManagerPackageName() {
21140        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21141
21142        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21143                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21144                        | MATCH_DISABLED_COMPONENTS,
21145                UserHandle.myUserId());
21146        if (matches.size() == 1) {
21147            return matches.get(0).getComponentInfo().packageName;
21148        } else {
21149            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21150                    + matches.size() + ": matches=" + matches);
21151            return null;
21152        }
21153    }
21154
21155    @Override
21156    public void setApplicationEnabledSetting(String appPackageName,
21157            int newState, int flags, int userId, String callingPackage) {
21158        if (!sUserManager.exists(userId)) return;
21159        if (callingPackage == null) {
21160            callingPackage = Integer.toString(Binder.getCallingUid());
21161        }
21162        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21163    }
21164
21165    @Override
21166    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21167        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21168        synchronized (mPackages) {
21169            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21170            if (pkgSetting != null) {
21171                pkgSetting.setUpdateAvailable(updateAvailable);
21172            }
21173        }
21174    }
21175
21176    @Override
21177    public void setComponentEnabledSetting(ComponentName componentName,
21178            int newState, int flags, int userId) {
21179        if (!sUserManager.exists(userId)) return;
21180        setEnabledSetting(componentName.getPackageName(),
21181                componentName.getClassName(), newState, flags, userId, null);
21182    }
21183
21184    private void setEnabledSetting(final String packageName, String className, int newState,
21185            final int flags, int userId, String callingPackage) {
21186        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21187              || newState == COMPONENT_ENABLED_STATE_ENABLED
21188              || newState == COMPONENT_ENABLED_STATE_DISABLED
21189              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21190              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21191            throw new IllegalArgumentException("Invalid new component state: "
21192                    + newState);
21193        }
21194        PackageSetting pkgSetting;
21195        final int callingUid = Binder.getCallingUid();
21196        final int permission;
21197        if (callingUid == Process.SYSTEM_UID) {
21198            permission = PackageManager.PERMISSION_GRANTED;
21199        } else {
21200            permission = mContext.checkCallingOrSelfPermission(
21201                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21202        }
21203        enforceCrossUserPermission(callingUid, userId,
21204                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21205        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21206        boolean sendNow = false;
21207        boolean isApp = (className == null);
21208        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21209        String componentName = isApp ? packageName : className;
21210        int packageUid = -1;
21211        ArrayList<String> components;
21212
21213        // reader
21214        synchronized (mPackages) {
21215            pkgSetting = mSettings.mPackages.get(packageName);
21216            if (pkgSetting == null) {
21217                if (!isCallerInstantApp) {
21218                    if (className == null) {
21219                        throw new IllegalArgumentException("Unknown package: " + packageName);
21220                    }
21221                    throw new IllegalArgumentException(
21222                            "Unknown component: " + packageName + "/" + className);
21223                } else {
21224                    // throw SecurityException to prevent leaking package information
21225                    throw new SecurityException(
21226                            "Attempt to change component state; "
21227                            + "pid=" + Binder.getCallingPid()
21228                            + ", uid=" + callingUid
21229                            + (className == null
21230                                    ? ", package=" + packageName
21231                                    : ", component=" + packageName + "/" + className));
21232                }
21233            }
21234        }
21235
21236        // Limit who can change which apps
21237        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21238            // Don't allow apps that don't have permission to modify other apps
21239            if (!allowedByPermission
21240                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21241                throw new SecurityException(
21242                        "Attempt to change component state; "
21243                        + "pid=" + Binder.getCallingPid()
21244                        + ", uid=" + callingUid
21245                        + (className == null
21246                                ? ", package=" + packageName
21247                                : ", component=" + packageName + "/" + className));
21248            }
21249            // Don't allow changing protected packages.
21250            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21251                throw new SecurityException("Cannot disable a protected package: " + packageName);
21252            }
21253        }
21254
21255        synchronized (mPackages) {
21256            if (callingUid == Process.SHELL_UID
21257                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21258                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21259                // unless it is a test package.
21260                int oldState = pkgSetting.getEnabled(userId);
21261                if (className == null
21262                    &&
21263                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21264                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21265                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21266                    &&
21267                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21268                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21269                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21270                    // ok
21271                } else {
21272                    throw new SecurityException(
21273                            "Shell cannot change component state for " + packageName + "/"
21274                            + className + " to " + newState);
21275                }
21276            }
21277            if (className == null) {
21278                // We're dealing with an application/package level state change
21279                if (pkgSetting.getEnabled(userId) == newState) {
21280                    // Nothing to do
21281                    return;
21282                }
21283                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21284                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21285                    // Don't care about who enables an app.
21286                    callingPackage = null;
21287                }
21288                pkgSetting.setEnabled(newState, userId, callingPackage);
21289                // pkgSetting.pkg.mSetEnabled = newState;
21290            } else {
21291                // We're dealing with a component level state change
21292                // First, verify that this is a valid class name.
21293                PackageParser.Package pkg = pkgSetting.pkg;
21294                if (pkg == null || !pkg.hasComponentClassName(className)) {
21295                    if (pkg != null &&
21296                            pkg.applicationInfo.targetSdkVersion >=
21297                                    Build.VERSION_CODES.JELLY_BEAN) {
21298                        throw new IllegalArgumentException("Component class " + className
21299                                + " does not exist in " + packageName);
21300                    } else {
21301                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21302                                + className + " does not exist in " + packageName);
21303                    }
21304                }
21305                switch (newState) {
21306                case COMPONENT_ENABLED_STATE_ENABLED:
21307                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21308                        return;
21309                    }
21310                    break;
21311                case COMPONENT_ENABLED_STATE_DISABLED:
21312                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21313                        return;
21314                    }
21315                    break;
21316                case COMPONENT_ENABLED_STATE_DEFAULT:
21317                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21318                        return;
21319                    }
21320                    break;
21321                default:
21322                    Slog.e(TAG, "Invalid new component state: " + newState);
21323                    return;
21324                }
21325            }
21326            scheduleWritePackageRestrictionsLocked(userId);
21327            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21328            final long callingId = Binder.clearCallingIdentity();
21329            try {
21330                updateInstantAppInstallerLocked(packageName);
21331            } finally {
21332                Binder.restoreCallingIdentity(callingId);
21333            }
21334            components = mPendingBroadcasts.get(userId, packageName);
21335            final boolean newPackage = components == null;
21336            if (newPackage) {
21337                components = new ArrayList<String>();
21338            }
21339            if (!components.contains(componentName)) {
21340                components.add(componentName);
21341            }
21342            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21343                sendNow = true;
21344                // Purge entry from pending broadcast list if another one exists already
21345                // since we are sending one right away.
21346                mPendingBroadcasts.remove(userId, packageName);
21347            } else {
21348                if (newPackage) {
21349                    mPendingBroadcasts.put(userId, packageName, components);
21350                }
21351                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21352                    // Schedule a message
21353                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21354                }
21355            }
21356        }
21357
21358        long callingId = Binder.clearCallingIdentity();
21359        try {
21360            if (sendNow) {
21361                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21362                sendPackageChangedBroadcast(packageName,
21363                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21364            }
21365        } finally {
21366            Binder.restoreCallingIdentity(callingId);
21367        }
21368    }
21369
21370    @Override
21371    public void flushPackageRestrictionsAsUser(int userId) {
21372        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21373            return;
21374        }
21375        if (!sUserManager.exists(userId)) {
21376            return;
21377        }
21378        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21379                false /* checkShell */, "flushPackageRestrictions");
21380        synchronized (mPackages) {
21381            mSettings.writePackageRestrictionsLPr(userId);
21382            mDirtyUsers.remove(userId);
21383            if (mDirtyUsers.isEmpty()) {
21384                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21385            }
21386        }
21387    }
21388
21389    private void sendPackageChangedBroadcast(String packageName,
21390            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21391        if (DEBUG_INSTALL)
21392            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21393                    + componentNames);
21394        Bundle extras = new Bundle(4);
21395        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21396        String nameList[] = new String[componentNames.size()];
21397        componentNames.toArray(nameList);
21398        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21399        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21400        extras.putInt(Intent.EXTRA_UID, packageUid);
21401        // If this is not reporting a change of the overall package, then only send it
21402        // to registered receivers.  We don't want to launch a swath of apps for every
21403        // little component state change.
21404        final int flags = !componentNames.contains(packageName)
21405                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21406        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21407                new int[] {UserHandle.getUserId(packageUid)});
21408    }
21409
21410    @Override
21411    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21412        if (!sUserManager.exists(userId)) return;
21413        final int callingUid = Binder.getCallingUid();
21414        if (getInstantAppPackageName(callingUid) != null) {
21415            return;
21416        }
21417        final int permission = mContext.checkCallingOrSelfPermission(
21418                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21419        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21420        enforceCrossUserPermission(callingUid, userId,
21421                true /* requireFullPermission */, true /* checkShell */, "stop package");
21422        // writer
21423        synchronized (mPackages) {
21424            final PackageSetting ps = mSettings.mPackages.get(packageName);
21425            if (!filterAppAccessLPr(ps, callingUid, userId)
21426                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21427                            allowedByPermission, callingUid, userId)) {
21428                scheduleWritePackageRestrictionsLocked(userId);
21429            }
21430        }
21431    }
21432
21433    @Override
21434    public String getInstallerPackageName(String packageName) {
21435        final int callingUid = Binder.getCallingUid();
21436        if (getInstantAppPackageName(callingUid) != null) {
21437            return null;
21438        }
21439        // reader
21440        synchronized (mPackages) {
21441            final PackageSetting ps = mSettings.mPackages.get(packageName);
21442            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21443                return null;
21444            }
21445            return mSettings.getInstallerPackageNameLPr(packageName);
21446        }
21447    }
21448
21449    public boolean isOrphaned(String packageName) {
21450        // reader
21451        synchronized (mPackages) {
21452            return mSettings.isOrphaned(packageName);
21453        }
21454    }
21455
21456    @Override
21457    public int getApplicationEnabledSetting(String packageName, int userId) {
21458        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21459        int callingUid = Binder.getCallingUid();
21460        enforceCrossUserPermission(callingUid, userId,
21461                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21462        // reader
21463        synchronized (mPackages) {
21464            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21465                return COMPONENT_ENABLED_STATE_DISABLED;
21466            }
21467            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21468        }
21469    }
21470
21471    @Override
21472    public int getComponentEnabledSetting(ComponentName component, int userId) {
21473        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21474        int callingUid = Binder.getCallingUid();
21475        enforceCrossUserPermission(callingUid, userId,
21476                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21477        synchronized (mPackages) {
21478            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21479                    component, TYPE_UNKNOWN, userId)) {
21480                return COMPONENT_ENABLED_STATE_DISABLED;
21481            }
21482            return mSettings.getComponentEnabledSettingLPr(component, userId);
21483        }
21484    }
21485
21486    @Override
21487    public void enterSafeMode() {
21488        enforceSystemOrRoot("Only the system can request entering safe mode");
21489
21490        if (!mSystemReady) {
21491            mSafeMode = true;
21492        }
21493    }
21494
21495    @Override
21496    public void systemReady() {
21497        enforceSystemOrRoot("Only the system can claim the system is ready");
21498
21499        mSystemReady = true;
21500        final ContentResolver resolver = mContext.getContentResolver();
21501        ContentObserver co = new ContentObserver(mHandler) {
21502            @Override
21503            public void onChange(boolean selfChange) {
21504                mEphemeralAppsDisabled =
21505                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21506                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21507            }
21508        };
21509        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21510                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21511                false, co, UserHandle.USER_SYSTEM);
21512        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21513                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21514        co.onChange(true);
21515
21516        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21517        // disabled after already being started.
21518        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21519                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21520
21521        // Read the compatibilty setting when the system is ready.
21522        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21523                mContext.getContentResolver(),
21524                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21525        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21526        if (DEBUG_SETTINGS) {
21527            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21528        }
21529
21530        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21531
21532        synchronized (mPackages) {
21533            // Verify that all of the preferred activity components actually
21534            // exist.  It is possible for applications to be updated and at
21535            // that point remove a previously declared activity component that
21536            // had been set as a preferred activity.  We try to clean this up
21537            // the next time we encounter that preferred activity, but it is
21538            // possible for the user flow to never be able to return to that
21539            // situation so here we do a sanity check to make sure we haven't
21540            // left any junk around.
21541            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21542            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21543                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21544                removed.clear();
21545                for (PreferredActivity pa : pir.filterSet()) {
21546                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21547                        removed.add(pa);
21548                    }
21549                }
21550                if (removed.size() > 0) {
21551                    for (int r=0; r<removed.size(); r++) {
21552                        PreferredActivity pa = removed.get(r);
21553                        Slog.w(TAG, "Removing dangling preferred activity: "
21554                                + pa.mPref.mComponent);
21555                        pir.removeFilter(pa);
21556                    }
21557                    mSettings.writePackageRestrictionsLPr(
21558                            mSettings.mPreferredActivities.keyAt(i));
21559                }
21560            }
21561
21562            for (int userId : UserManagerService.getInstance().getUserIds()) {
21563                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21564                    grantPermissionsUserIds = ArrayUtils.appendInt(
21565                            grantPermissionsUserIds, userId);
21566                }
21567            }
21568        }
21569        sUserManager.systemReady();
21570
21571        // If we upgraded grant all default permissions before kicking off.
21572        for (int userId : grantPermissionsUserIds) {
21573            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21574        }
21575
21576        // If we did not grant default permissions, we preload from this the
21577        // default permission exceptions lazily to ensure we don't hit the
21578        // disk on a new user creation.
21579        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21580            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21581        }
21582
21583        // Kick off any messages waiting for system ready
21584        if (mPostSystemReadyMessages != null) {
21585            for (Message msg : mPostSystemReadyMessages) {
21586                msg.sendToTarget();
21587            }
21588            mPostSystemReadyMessages = null;
21589        }
21590
21591        // Watch for external volumes that come and go over time
21592        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21593        storage.registerListener(mStorageListener);
21594
21595        mInstallerService.systemReady();
21596        mPackageDexOptimizer.systemReady();
21597
21598        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21599                StorageManagerInternal.class);
21600        StorageManagerInternal.addExternalStoragePolicy(
21601                new StorageManagerInternal.ExternalStorageMountPolicy() {
21602            @Override
21603            public int getMountMode(int uid, String packageName) {
21604                if (Process.isIsolated(uid)) {
21605                    return Zygote.MOUNT_EXTERNAL_NONE;
21606                }
21607                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21608                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21609                }
21610                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21611                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21612                }
21613                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21614                    return Zygote.MOUNT_EXTERNAL_READ;
21615                }
21616                return Zygote.MOUNT_EXTERNAL_WRITE;
21617            }
21618
21619            @Override
21620            public boolean hasExternalStorage(int uid, String packageName) {
21621                return true;
21622            }
21623        });
21624
21625        // Now that we're mostly running, clean up stale users and apps
21626        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21627        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21628
21629        if (mPrivappPermissionsViolations != null) {
21630            Slog.wtf(TAG,"Signature|privileged permissions not in "
21631                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21632            mPrivappPermissionsViolations = null;
21633        }
21634    }
21635
21636    public void waitForAppDataPrepared() {
21637        if (mPrepareAppDataFuture == null) {
21638            return;
21639        }
21640        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21641        mPrepareAppDataFuture = null;
21642    }
21643
21644    @Override
21645    public boolean isSafeMode() {
21646        // allow instant applications
21647        return mSafeMode;
21648    }
21649
21650    @Override
21651    public boolean hasSystemUidErrors() {
21652        // allow instant applications
21653        return mHasSystemUidErrors;
21654    }
21655
21656    static String arrayToString(int[] array) {
21657        StringBuffer buf = new StringBuffer(128);
21658        buf.append('[');
21659        if (array != null) {
21660            for (int i=0; i<array.length; i++) {
21661                if (i > 0) buf.append(", ");
21662                buf.append(array[i]);
21663            }
21664        }
21665        buf.append(']');
21666        return buf.toString();
21667    }
21668
21669    static class DumpState {
21670        public static final int DUMP_LIBS = 1 << 0;
21671        public static final int DUMP_FEATURES = 1 << 1;
21672        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21673        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21674        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21675        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21676        public static final int DUMP_PERMISSIONS = 1 << 6;
21677        public static final int DUMP_PACKAGES = 1 << 7;
21678        public static final int DUMP_SHARED_USERS = 1 << 8;
21679        public static final int DUMP_MESSAGES = 1 << 9;
21680        public static final int DUMP_PROVIDERS = 1 << 10;
21681        public static final int DUMP_VERIFIERS = 1 << 11;
21682        public static final int DUMP_PREFERRED = 1 << 12;
21683        public static final int DUMP_PREFERRED_XML = 1 << 13;
21684        public static final int DUMP_KEYSETS = 1 << 14;
21685        public static final int DUMP_VERSION = 1 << 15;
21686        public static final int DUMP_INSTALLS = 1 << 16;
21687        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21688        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21689        public static final int DUMP_FROZEN = 1 << 19;
21690        public static final int DUMP_DEXOPT = 1 << 20;
21691        public static final int DUMP_COMPILER_STATS = 1 << 21;
21692        public static final int DUMP_CHANGES = 1 << 22;
21693        public static final int DUMP_VOLUMES = 1 << 23;
21694
21695        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21696
21697        private int mTypes;
21698
21699        private int mOptions;
21700
21701        private boolean mTitlePrinted;
21702
21703        private SharedUserSetting mSharedUser;
21704
21705        public boolean isDumping(int type) {
21706            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21707                return true;
21708            }
21709
21710            return (mTypes & type) != 0;
21711        }
21712
21713        public void setDump(int type) {
21714            mTypes |= type;
21715        }
21716
21717        public boolean isOptionEnabled(int option) {
21718            return (mOptions & option) != 0;
21719        }
21720
21721        public void setOptionEnabled(int option) {
21722            mOptions |= option;
21723        }
21724
21725        public boolean onTitlePrinted() {
21726            final boolean printed = mTitlePrinted;
21727            mTitlePrinted = true;
21728            return printed;
21729        }
21730
21731        public boolean getTitlePrinted() {
21732            return mTitlePrinted;
21733        }
21734
21735        public void setTitlePrinted(boolean enabled) {
21736            mTitlePrinted = enabled;
21737        }
21738
21739        public SharedUserSetting getSharedUser() {
21740            return mSharedUser;
21741        }
21742
21743        public void setSharedUser(SharedUserSetting user) {
21744            mSharedUser = user;
21745        }
21746    }
21747
21748    @Override
21749    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21750            FileDescriptor err, String[] args, ShellCallback callback,
21751            ResultReceiver resultReceiver) {
21752        (new PackageManagerShellCommand(this)).exec(
21753                this, in, out, err, args, callback, resultReceiver);
21754    }
21755
21756    @Override
21757    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21758        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21759
21760        DumpState dumpState = new DumpState();
21761        boolean fullPreferred = false;
21762        boolean checkin = false;
21763
21764        String packageName = null;
21765        ArraySet<String> permissionNames = null;
21766
21767        int opti = 0;
21768        while (opti < args.length) {
21769            String opt = args[opti];
21770            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21771                break;
21772            }
21773            opti++;
21774
21775            if ("-a".equals(opt)) {
21776                // Right now we only know how to print all.
21777            } else if ("-h".equals(opt)) {
21778                pw.println("Package manager dump options:");
21779                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21780                pw.println("    --checkin: dump for a checkin");
21781                pw.println("    -f: print details of intent filters");
21782                pw.println("    -h: print this help");
21783                pw.println("  cmd may be one of:");
21784                pw.println("    l[ibraries]: list known shared libraries");
21785                pw.println("    f[eatures]: list device features");
21786                pw.println("    k[eysets]: print known keysets");
21787                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21788                pw.println("    perm[issions]: dump permissions");
21789                pw.println("    permission [name ...]: dump declaration and use of given permission");
21790                pw.println("    pref[erred]: print preferred package settings");
21791                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21792                pw.println("    prov[iders]: dump content providers");
21793                pw.println("    p[ackages]: dump installed packages");
21794                pw.println("    s[hared-users]: dump shared user IDs");
21795                pw.println("    m[essages]: print collected runtime messages");
21796                pw.println("    v[erifiers]: print package verifier info");
21797                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21798                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21799                pw.println("    version: print database version info");
21800                pw.println("    write: write current settings now");
21801                pw.println("    installs: details about install sessions");
21802                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21803                pw.println("    dexopt: dump dexopt state");
21804                pw.println("    compiler-stats: dump compiler statistics");
21805                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21806                pw.println("    <package.name>: info about given package");
21807                return;
21808            } else if ("--checkin".equals(opt)) {
21809                checkin = true;
21810            } else if ("-f".equals(opt)) {
21811                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21812            } else if ("--proto".equals(opt)) {
21813                dumpProto(fd);
21814                return;
21815            } else {
21816                pw.println("Unknown argument: " + opt + "; use -h for help");
21817            }
21818        }
21819
21820        // Is the caller requesting to dump a particular piece of data?
21821        if (opti < args.length) {
21822            String cmd = args[opti];
21823            opti++;
21824            // Is this a package name?
21825            if ("android".equals(cmd) || cmd.contains(".")) {
21826                packageName = cmd;
21827                // When dumping a single package, we always dump all of its
21828                // filter information since the amount of data will be reasonable.
21829                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21830            } else if ("check-permission".equals(cmd)) {
21831                if (opti >= args.length) {
21832                    pw.println("Error: check-permission missing permission argument");
21833                    return;
21834                }
21835                String perm = args[opti];
21836                opti++;
21837                if (opti >= args.length) {
21838                    pw.println("Error: check-permission missing package argument");
21839                    return;
21840                }
21841
21842                String pkg = args[opti];
21843                opti++;
21844                int user = UserHandle.getUserId(Binder.getCallingUid());
21845                if (opti < args.length) {
21846                    try {
21847                        user = Integer.parseInt(args[opti]);
21848                    } catch (NumberFormatException e) {
21849                        pw.println("Error: check-permission user argument is not a number: "
21850                                + args[opti]);
21851                        return;
21852                    }
21853                }
21854
21855                // Normalize package name to handle renamed packages and static libs
21856                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21857
21858                pw.println(checkPermission(perm, pkg, user));
21859                return;
21860            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21861                dumpState.setDump(DumpState.DUMP_LIBS);
21862            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21863                dumpState.setDump(DumpState.DUMP_FEATURES);
21864            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21865                if (opti >= args.length) {
21866                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21867                            | DumpState.DUMP_SERVICE_RESOLVERS
21868                            | DumpState.DUMP_RECEIVER_RESOLVERS
21869                            | DumpState.DUMP_CONTENT_RESOLVERS);
21870                } else {
21871                    while (opti < args.length) {
21872                        String name = args[opti];
21873                        if ("a".equals(name) || "activity".equals(name)) {
21874                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21875                        } else if ("s".equals(name) || "service".equals(name)) {
21876                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21877                        } else if ("r".equals(name) || "receiver".equals(name)) {
21878                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21879                        } else if ("c".equals(name) || "content".equals(name)) {
21880                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21881                        } else {
21882                            pw.println("Error: unknown resolver table type: " + name);
21883                            return;
21884                        }
21885                        opti++;
21886                    }
21887                }
21888            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21889                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21890            } else if ("permission".equals(cmd)) {
21891                if (opti >= args.length) {
21892                    pw.println("Error: permission requires permission name");
21893                    return;
21894                }
21895                permissionNames = new ArraySet<>();
21896                while (opti < args.length) {
21897                    permissionNames.add(args[opti]);
21898                    opti++;
21899                }
21900                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21901                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21902            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21903                dumpState.setDump(DumpState.DUMP_PREFERRED);
21904            } else if ("preferred-xml".equals(cmd)) {
21905                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21906                if (opti < args.length && "--full".equals(args[opti])) {
21907                    fullPreferred = true;
21908                    opti++;
21909                }
21910            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21911                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21912            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21913                dumpState.setDump(DumpState.DUMP_PACKAGES);
21914            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21915                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21916            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21917                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21918            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21919                dumpState.setDump(DumpState.DUMP_MESSAGES);
21920            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21921                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21922            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21923                    || "intent-filter-verifiers".equals(cmd)) {
21924                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21925            } else if ("version".equals(cmd)) {
21926                dumpState.setDump(DumpState.DUMP_VERSION);
21927            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21928                dumpState.setDump(DumpState.DUMP_KEYSETS);
21929            } else if ("installs".equals(cmd)) {
21930                dumpState.setDump(DumpState.DUMP_INSTALLS);
21931            } else if ("frozen".equals(cmd)) {
21932                dumpState.setDump(DumpState.DUMP_FROZEN);
21933            } else if ("volumes".equals(cmd)) {
21934                dumpState.setDump(DumpState.DUMP_VOLUMES);
21935            } else if ("dexopt".equals(cmd)) {
21936                dumpState.setDump(DumpState.DUMP_DEXOPT);
21937            } else if ("compiler-stats".equals(cmd)) {
21938                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21939            } else if ("changes".equals(cmd)) {
21940                dumpState.setDump(DumpState.DUMP_CHANGES);
21941            } else if ("write".equals(cmd)) {
21942                synchronized (mPackages) {
21943                    mSettings.writeLPr();
21944                    pw.println("Settings written.");
21945                    return;
21946                }
21947            }
21948        }
21949
21950        if (checkin) {
21951            pw.println("vers,1");
21952        }
21953
21954        // reader
21955        synchronized (mPackages) {
21956            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21957                if (!checkin) {
21958                    if (dumpState.onTitlePrinted())
21959                        pw.println();
21960                    pw.println("Database versions:");
21961                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21962                }
21963            }
21964
21965            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21966                if (!checkin) {
21967                    if (dumpState.onTitlePrinted())
21968                        pw.println();
21969                    pw.println("Verifiers:");
21970                    pw.print("  Required: ");
21971                    pw.print(mRequiredVerifierPackage);
21972                    pw.print(" (uid=");
21973                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21974                            UserHandle.USER_SYSTEM));
21975                    pw.println(")");
21976                } else if (mRequiredVerifierPackage != null) {
21977                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21978                    pw.print(",");
21979                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21980                            UserHandle.USER_SYSTEM));
21981                }
21982            }
21983
21984            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21985                    packageName == null) {
21986                if (mIntentFilterVerifierComponent != null) {
21987                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21988                    if (!checkin) {
21989                        if (dumpState.onTitlePrinted())
21990                            pw.println();
21991                        pw.println("Intent Filter Verifier:");
21992                        pw.print("  Using: ");
21993                        pw.print(verifierPackageName);
21994                        pw.print(" (uid=");
21995                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21996                                UserHandle.USER_SYSTEM));
21997                        pw.println(")");
21998                    } else if (verifierPackageName != null) {
21999                        pw.print("ifv,"); pw.print(verifierPackageName);
22000                        pw.print(",");
22001                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22002                                UserHandle.USER_SYSTEM));
22003                    }
22004                } else {
22005                    pw.println();
22006                    pw.println("No Intent Filter Verifier available!");
22007                }
22008            }
22009
22010            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22011                boolean printedHeader = false;
22012                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22013                while (it.hasNext()) {
22014                    String libName = it.next();
22015                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22016                    if (versionedLib == null) {
22017                        continue;
22018                    }
22019                    final int versionCount = versionedLib.size();
22020                    for (int i = 0; i < versionCount; i++) {
22021                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22022                        if (!checkin) {
22023                            if (!printedHeader) {
22024                                if (dumpState.onTitlePrinted())
22025                                    pw.println();
22026                                pw.println("Libraries:");
22027                                printedHeader = true;
22028                            }
22029                            pw.print("  ");
22030                        } else {
22031                            pw.print("lib,");
22032                        }
22033                        pw.print(libEntry.info.getName());
22034                        if (libEntry.info.isStatic()) {
22035                            pw.print(" version=" + libEntry.info.getVersion());
22036                        }
22037                        if (!checkin) {
22038                            pw.print(" -> ");
22039                        }
22040                        if (libEntry.path != null) {
22041                            pw.print(" (jar) ");
22042                            pw.print(libEntry.path);
22043                        } else {
22044                            pw.print(" (apk) ");
22045                            pw.print(libEntry.apk);
22046                        }
22047                        pw.println();
22048                    }
22049                }
22050            }
22051
22052            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22053                if (dumpState.onTitlePrinted())
22054                    pw.println();
22055                if (!checkin) {
22056                    pw.println("Features:");
22057                }
22058
22059                synchronized (mAvailableFeatures) {
22060                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22061                        if (checkin) {
22062                            pw.print("feat,");
22063                            pw.print(feat.name);
22064                            pw.print(",");
22065                            pw.println(feat.version);
22066                        } else {
22067                            pw.print("  ");
22068                            pw.print(feat.name);
22069                            if (feat.version > 0) {
22070                                pw.print(" version=");
22071                                pw.print(feat.version);
22072                            }
22073                            pw.println();
22074                        }
22075                    }
22076                }
22077            }
22078
22079            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22080                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22081                        : "Activity Resolver Table:", "  ", packageName,
22082                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22083                    dumpState.setTitlePrinted(true);
22084                }
22085            }
22086            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22087                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22088                        : "Receiver Resolver Table:", "  ", packageName,
22089                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22090                    dumpState.setTitlePrinted(true);
22091                }
22092            }
22093            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22094                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22095                        : "Service Resolver Table:", "  ", packageName,
22096                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22097                    dumpState.setTitlePrinted(true);
22098                }
22099            }
22100            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22101                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22102                        : "Provider Resolver Table:", "  ", packageName,
22103                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22104                    dumpState.setTitlePrinted(true);
22105                }
22106            }
22107
22108            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22109                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22110                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22111                    int user = mSettings.mPreferredActivities.keyAt(i);
22112                    if (pir.dump(pw,
22113                            dumpState.getTitlePrinted()
22114                                ? "\nPreferred Activities User " + user + ":"
22115                                : "Preferred Activities User " + user + ":", "  ",
22116                            packageName, true, false)) {
22117                        dumpState.setTitlePrinted(true);
22118                    }
22119                }
22120            }
22121
22122            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22123                pw.flush();
22124                FileOutputStream fout = new FileOutputStream(fd);
22125                BufferedOutputStream str = new BufferedOutputStream(fout);
22126                XmlSerializer serializer = new FastXmlSerializer();
22127                try {
22128                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22129                    serializer.startDocument(null, true);
22130                    serializer.setFeature(
22131                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22132                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22133                    serializer.endDocument();
22134                    serializer.flush();
22135                } catch (IllegalArgumentException e) {
22136                    pw.println("Failed writing: " + e);
22137                } catch (IllegalStateException e) {
22138                    pw.println("Failed writing: " + e);
22139                } catch (IOException e) {
22140                    pw.println("Failed writing: " + e);
22141                }
22142            }
22143
22144            if (!checkin
22145                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22146                    && packageName == null) {
22147                pw.println();
22148                int count = mSettings.mPackages.size();
22149                if (count == 0) {
22150                    pw.println("No applications!");
22151                    pw.println();
22152                } else {
22153                    final String prefix = "  ";
22154                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22155                    if (allPackageSettings.size() == 0) {
22156                        pw.println("No domain preferred apps!");
22157                        pw.println();
22158                    } else {
22159                        pw.println("App verification status:");
22160                        pw.println();
22161                        count = 0;
22162                        for (PackageSetting ps : allPackageSettings) {
22163                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22164                            if (ivi == null || ivi.getPackageName() == null) continue;
22165                            pw.println(prefix + "Package: " + ivi.getPackageName());
22166                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22167                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22168                            pw.println();
22169                            count++;
22170                        }
22171                        if (count == 0) {
22172                            pw.println(prefix + "No app verification established.");
22173                            pw.println();
22174                        }
22175                        for (int userId : sUserManager.getUserIds()) {
22176                            pw.println("App linkages for user " + userId + ":");
22177                            pw.println();
22178                            count = 0;
22179                            for (PackageSetting ps : allPackageSettings) {
22180                                final long status = ps.getDomainVerificationStatusForUser(userId);
22181                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22182                                        && !DEBUG_DOMAIN_VERIFICATION) {
22183                                    continue;
22184                                }
22185                                pw.println(prefix + "Package: " + ps.name);
22186                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22187                                String statusStr = IntentFilterVerificationInfo.
22188                                        getStatusStringFromValue(status);
22189                                pw.println(prefix + "Status:  " + statusStr);
22190                                pw.println();
22191                                count++;
22192                            }
22193                            if (count == 0) {
22194                                pw.println(prefix + "No configured app linkages.");
22195                                pw.println();
22196                            }
22197                        }
22198                    }
22199                }
22200            }
22201
22202            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22203                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22204                if (packageName == null && permissionNames == null) {
22205                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22206                        if (iperm == 0) {
22207                            if (dumpState.onTitlePrinted())
22208                                pw.println();
22209                            pw.println("AppOp Permissions:");
22210                        }
22211                        pw.print("  AppOp Permission ");
22212                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22213                        pw.println(":");
22214                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22215                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22216                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22217                        }
22218                    }
22219                }
22220            }
22221
22222            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22223                boolean printedSomething = false;
22224                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22225                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22226                        continue;
22227                    }
22228                    if (!printedSomething) {
22229                        if (dumpState.onTitlePrinted())
22230                            pw.println();
22231                        pw.println("Registered ContentProviders:");
22232                        printedSomething = true;
22233                    }
22234                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22235                    pw.print("    "); pw.println(p.toString());
22236                }
22237                printedSomething = false;
22238                for (Map.Entry<String, PackageParser.Provider> entry :
22239                        mProvidersByAuthority.entrySet()) {
22240                    PackageParser.Provider p = entry.getValue();
22241                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22242                        continue;
22243                    }
22244                    if (!printedSomething) {
22245                        if (dumpState.onTitlePrinted())
22246                            pw.println();
22247                        pw.println("ContentProvider Authorities:");
22248                        printedSomething = true;
22249                    }
22250                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22251                    pw.print("    "); pw.println(p.toString());
22252                    if (p.info != null && p.info.applicationInfo != null) {
22253                        final String appInfo = p.info.applicationInfo.toString();
22254                        pw.print("      applicationInfo="); pw.println(appInfo);
22255                    }
22256                }
22257            }
22258
22259            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22260                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22261            }
22262
22263            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22264                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22265            }
22266
22267            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22268                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22269            }
22270
22271            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22272                if (dumpState.onTitlePrinted()) pw.println();
22273                pw.println("Package Changes:");
22274                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22275                final int K = mChangedPackages.size();
22276                for (int i = 0; i < K; i++) {
22277                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22278                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22279                    final int N = changes.size();
22280                    if (N == 0) {
22281                        pw.print("    "); pw.println("No packages changed");
22282                    } else {
22283                        for (int j = 0; j < N; j++) {
22284                            final String pkgName = changes.valueAt(j);
22285                            final int sequenceNumber = changes.keyAt(j);
22286                            pw.print("    ");
22287                            pw.print("seq=");
22288                            pw.print(sequenceNumber);
22289                            pw.print(", package=");
22290                            pw.println(pkgName);
22291                        }
22292                    }
22293                }
22294            }
22295
22296            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22297                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22298            }
22299
22300            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22301                // XXX should handle packageName != null by dumping only install data that
22302                // the given package is involved with.
22303                if (dumpState.onTitlePrinted()) pw.println();
22304
22305                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22306                ipw.println();
22307                ipw.println("Frozen packages:");
22308                ipw.increaseIndent();
22309                if (mFrozenPackages.size() == 0) {
22310                    ipw.println("(none)");
22311                } else {
22312                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22313                        ipw.println(mFrozenPackages.valueAt(i));
22314                    }
22315                }
22316                ipw.decreaseIndent();
22317            }
22318
22319            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22320                if (dumpState.onTitlePrinted()) pw.println();
22321
22322                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22323                ipw.println();
22324                ipw.println("Loaded volumes:");
22325                ipw.increaseIndent();
22326                if (mLoadedVolumes.size() == 0) {
22327                    ipw.println("(none)");
22328                } else {
22329                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22330                        ipw.println(mLoadedVolumes.valueAt(i));
22331                    }
22332                }
22333                ipw.decreaseIndent();
22334            }
22335
22336            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22337                if (dumpState.onTitlePrinted()) pw.println();
22338                dumpDexoptStateLPr(pw, packageName);
22339            }
22340
22341            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22342                if (dumpState.onTitlePrinted()) pw.println();
22343                dumpCompilerStatsLPr(pw, packageName);
22344            }
22345
22346            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22347                if (dumpState.onTitlePrinted()) pw.println();
22348                mSettings.dumpReadMessagesLPr(pw, dumpState);
22349
22350                pw.println();
22351                pw.println("Package warning messages:");
22352                BufferedReader in = null;
22353                String line = null;
22354                try {
22355                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22356                    while ((line = in.readLine()) != null) {
22357                        if (line.contains("ignored: updated version")) continue;
22358                        pw.println(line);
22359                    }
22360                } catch (IOException ignored) {
22361                } finally {
22362                    IoUtils.closeQuietly(in);
22363                }
22364            }
22365
22366            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22367                BufferedReader in = null;
22368                String line = null;
22369                try {
22370                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22371                    while ((line = in.readLine()) != null) {
22372                        if (line.contains("ignored: updated version")) continue;
22373                        pw.print("msg,");
22374                        pw.println(line);
22375                    }
22376                } catch (IOException ignored) {
22377                } finally {
22378                    IoUtils.closeQuietly(in);
22379                }
22380            }
22381        }
22382
22383        // PackageInstaller should be called outside of mPackages lock
22384        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22385            // XXX should handle packageName != null by dumping only install data that
22386            // the given package is involved with.
22387            if (dumpState.onTitlePrinted()) pw.println();
22388            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22389        }
22390    }
22391
22392    private void dumpProto(FileDescriptor fd) {
22393        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22394
22395        synchronized (mPackages) {
22396            final long requiredVerifierPackageToken =
22397                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22398            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22399            proto.write(
22400                    PackageServiceDumpProto.PackageShortProto.UID,
22401                    getPackageUid(
22402                            mRequiredVerifierPackage,
22403                            MATCH_DEBUG_TRIAGED_MISSING,
22404                            UserHandle.USER_SYSTEM));
22405            proto.end(requiredVerifierPackageToken);
22406
22407            if (mIntentFilterVerifierComponent != null) {
22408                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22409                final long verifierPackageToken =
22410                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22411                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22412                proto.write(
22413                        PackageServiceDumpProto.PackageShortProto.UID,
22414                        getPackageUid(
22415                                verifierPackageName,
22416                                MATCH_DEBUG_TRIAGED_MISSING,
22417                                UserHandle.USER_SYSTEM));
22418                proto.end(verifierPackageToken);
22419            }
22420
22421            dumpSharedLibrariesProto(proto);
22422            dumpFeaturesProto(proto);
22423            mSettings.dumpPackagesProto(proto);
22424            mSettings.dumpSharedUsersProto(proto);
22425            dumpMessagesProto(proto);
22426        }
22427        proto.flush();
22428    }
22429
22430    private void dumpMessagesProto(ProtoOutputStream proto) {
22431        BufferedReader in = null;
22432        String line = null;
22433        try {
22434            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22435            while ((line = in.readLine()) != null) {
22436                if (line.contains("ignored: updated version")) continue;
22437                proto.write(PackageServiceDumpProto.MESSAGES, line);
22438            }
22439        } catch (IOException ignored) {
22440        } finally {
22441            IoUtils.closeQuietly(in);
22442        }
22443    }
22444
22445    private void dumpFeaturesProto(ProtoOutputStream proto) {
22446        synchronized (mAvailableFeatures) {
22447            final int count = mAvailableFeatures.size();
22448            for (int i = 0; i < count; i++) {
22449                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22450                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22451                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22452                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22453                proto.end(featureToken);
22454            }
22455        }
22456    }
22457
22458    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22459        final int count = mSharedLibraries.size();
22460        for (int i = 0; i < count; i++) {
22461            final String libName = mSharedLibraries.keyAt(i);
22462            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22463            if (versionedLib == null) {
22464                continue;
22465            }
22466            final int versionCount = versionedLib.size();
22467            for (int j = 0; j < versionCount; j++) {
22468                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22469                final long sharedLibraryToken =
22470                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22471                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22472                final boolean isJar = (libEntry.path != null);
22473                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22474                if (isJar) {
22475                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22476                } else {
22477                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22478                }
22479                proto.end(sharedLibraryToken);
22480            }
22481        }
22482    }
22483
22484    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22485        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22486        ipw.println();
22487        ipw.println("Dexopt state:");
22488        ipw.increaseIndent();
22489        Collection<PackageParser.Package> packages = null;
22490        if (packageName != null) {
22491            PackageParser.Package targetPackage = mPackages.get(packageName);
22492            if (targetPackage != null) {
22493                packages = Collections.singletonList(targetPackage);
22494            } else {
22495                ipw.println("Unable to find package: " + packageName);
22496                return;
22497            }
22498        } else {
22499            packages = mPackages.values();
22500        }
22501
22502        for (PackageParser.Package pkg : packages) {
22503            ipw.println("[" + pkg.packageName + "]");
22504            ipw.increaseIndent();
22505            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22506            ipw.decreaseIndent();
22507        }
22508    }
22509
22510    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22511        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22512        ipw.println();
22513        ipw.println("Compiler stats:");
22514        ipw.increaseIndent();
22515        Collection<PackageParser.Package> packages = null;
22516        if (packageName != null) {
22517            PackageParser.Package targetPackage = mPackages.get(packageName);
22518            if (targetPackage != null) {
22519                packages = Collections.singletonList(targetPackage);
22520            } else {
22521                ipw.println("Unable to find package: " + packageName);
22522                return;
22523            }
22524        } else {
22525            packages = mPackages.values();
22526        }
22527
22528        for (PackageParser.Package pkg : packages) {
22529            ipw.println("[" + pkg.packageName + "]");
22530            ipw.increaseIndent();
22531
22532            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22533            if (stats == null) {
22534                ipw.println("(No recorded stats)");
22535            } else {
22536                stats.dump(ipw);
22537            }
22538            ipw.decreaseIndent();
22539        }
22540    }
22541
22542    private String dumpDomainString(String packageName) {
22543        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22544                .getList();
22545        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22546
22547        ArraySet<String> result = new ArraySet<>();
22548        if (iviList.size() > 0) {
22549            for (IntentFilterVerificationInfo ivi : iviList) {
22550                for (String host : ivi.getDomains()) {
22551                    result.add(host);
22552                }
22553            }
22554        }
22555        if (filters != null && filters.size() > 0) {
22556            for (IntentFilter filter : filters) {
22557                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22558                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22559                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22560                    result.addAll(filter.getHostsList());
22561                }
22562            }
22563        }
22564
22565        StringBuilder sb = new StringBuilder(result.size() * 16);
22566        for (String domain : result) {
22567            if (sb.length() > 0) sb.append(" ");
22568            sb.append(domain);
22569        }
22570        return sb.toString();
22571    }
22572
22573    // ------- apps on sdcard specific code -------
22574    static final boolean DEBUG_SD_INSTALL = false;
22575
22576    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22577
22578    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22579
22580    private boolean mMediaMounted = false;
22581
22582    static String getEncryptKey() {
22583        try {
22584            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22585                    SD_ENCRYPTION_KEYSTORE_NAME);
22586            if (sdEncKey == null) {
22587                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22588                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22589                if (sdEncKey == null) {
22590                    Slog.e(TAG, "Failed to create encryption keys");
22591                    return null;
22592                }
22593            }
22594            return sdEncKey;
22595        } catch (NoSuchAlgorithmException nsae) {
22596            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22597            return null;
22598        } catch (IOException ioe) {
22599            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22600            return null;
22601        }
22602    }
22603
22604    /*
22605     * Update media status on PackageManager.
22606     */
22607    @Override
22608    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22609        enforceSystemOrRoot("Media status can only be updated by the system");
22610        // reader; this apparently protects mMediaMounted, but should probably
22611        // be a different lock in that case.
22612        synchronized (mPackages) {
22613            Log.i(TAG, "Updating external media status from "
22614                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22615                    + (mediaStatus ? "mounted" : "unmounted"));
22616            if (DEBUG_SD_INSTALL)
22617                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22618                        + ", mMediaMounted=" + mMediaMounted);
22619            if (mediaStatus == mMediaMounted) {
22620                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22621                        : 0, -1);
22622                mHandler.sendMessage(msg);
22623                return;
22624            }
22625            mMediaMounted = mediaStatus;
22626        }
22627        // Queue up an async operation since the package installation may take a
22628        // little while.
22629        mHandler.post(new Runnable() {
22630            public void run() {
22631                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22632            }
22633        });
22634    }
22635
22636    /**
22637     * Called by StorageManagerService when the initial ASECs to scan are available.
22638     * Should block until all the ASEC containers are finished being scanned.
22639     */
22640    public void scanAvailableAsecs() {
22641        updateExternalMediaStatusInner(true, false, false);
22642    }
22643
22644    /*
22645     * Collect information of applications on external media, map them against
22646     * existing containers and update information based on current mount status.
22647     * Please note that we always have to report status if reportStatus has been
22648     * set to true especially when unloading packages.
22649     */
22650    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22651            boolean externalStorage) {
22652        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22653        int[] uidArr = EmptyArray.INT;
22654
22655        final String[] list = PackageHelper.getSecureContainerList();
22656        if (ArrayUtils.isEmpty(list)) {
22657            Log.i(TAG, "No secure containers found");
22658        } else {
22659            // Process list of secure containers and categorize them
22660            // as active or stale based on their package internal state.
22661
22662            // reader
22663            synchronized (mPackages) {
22664                for (String cid : list) {
22665                    // Leave stages untouched for now; installer service owns them
22666                    if (PackageInstallerService.isStageName(cid)) continue;
22667
22668                    if (DEBUG_SD_INSTALL)
22669                        Log.i(TAG, "Processing container " + cid);
22670                    String pkgName = getAsecPackageName(cid);
22671                    if (pkgName == null) {
22672                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22673                        continue;
22674                    }
22675                    if (DEBUG_SD_INSTALL)
22676                        Log.i(TAG, "Looking for pkg : " + pkgName);
22677
22678                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22679                    if (ps == null) {
22680                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22681                        continue;
22682                    }
22683
22684                    /*
22685                     * Skip packages that are not external if we're unmounting
22686                     * external storage.
22687                     */
22688                    if (externalStorage && !isMounted && !isExternal(ps)) {
22689                        continue;
22690                    }
22691
22692                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22693                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22694                    // The package status is changed only if the code path
22695                    // matches between settings and the container id.
22696                    if (ps.codePathString != null
22697                            && ps.codePathString.startsWith(args.getCodePath())) {
22698                        if (DEBUG_SD_INSTALL) {
22699                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22700                                    + " at code path: " + ps.codePathString);
22701                        }
22702
22703                        // We do have a valid package installed on sdcard
22704                        processCids.put(args, ps.codePathString);
22705                        final int uid = ps.appId;
22706                        if (uid != -1) {
22707                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22708                        }
22709                    } else {
22710                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22711                                + ps.codePathString);
22712                    }
22713                }
22714            }
22715
22716            Arrays.sort(uidArr);
22717        }
22718
22719        // Process packages with valid entries.
22720        if (isMounted) {
22721            if (DEBUG_SD_INSTALL)
22722                Log.i(TAG, "Loading packages");
22723            loadMediaPackages(processCids, uidArr, externalStorage);
22724            startCleaningPackages();
22725            mInstallerService.onSecureContainersAvailable();
22726        } else {
22727            if (DEBUG_SD_INSTALL)
22728                Log.i(TAG, "Unloading packages");
22729            unloadMediaPackages(processCids, uidArr, reportStatus);
22730        }
22731    }
22732
22733    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22734            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22735        final int size = infos.size();
22736        final String[] packageNames = new String[size];
22737        final int[] packageUids = new int[size];
22738        for (int i = 0; i < size; i++) {
22739            final ApplicationInfo info = infos.get(i);
22740            packageNames[i] = info.packageName;
22741            packageUids[i] = info.uid;
22742        }
22743        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22744                finishedReceiver);
22745    }
22746
22747    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22748            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22749        sendResourcesChangedBroadcast(mediaStatus, replacing,
22750                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22751    }
22752
22753    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22754            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22755        int size = pkgList.length;
22756        if (size > 0) {
22757            // Send broadcasts here
22758            Bundle extras = new Bundle();
22759            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22760            if (uidArr != null) {
22761                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22762            }
22763            if (replacing) {
22764                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22765            }
22766            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22767                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22768            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22769        }
22770    }
22771
22772   /*
22773     * Look at potentially valid container ids from processCids If package
22774     * information doesn't match the one on record or package scanning fails,
22775     * the cid is added to list of removeCids. We currently don't delete stale
22776     * containers.
22777     */
22778    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22779            boolean externalStorage) {
22780        ArrayList<String> pkgList = new ArrayList<String>();
22781        Set<AsecInstallArgs> keys = processCids.keySet();
22782
22783        for (AsecInstallArgs args : keys) {
22784            String codePath = processCids.get(args);
22785            if (DEBUG_SD_INSTALL)
22786                Log.i(TAG, "Loading container : " + args.cid);
22787            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22788            try {
22789                // Make sure there are no container errors first.
22790                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22791                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22792                            + " when installing from sdcard");
22793                    continue;
22794                }
22795                // Check code path here.
22796                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22797                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22798                            + " does not match one in settings " + codePath);
22799                    continue;
22800                }
22801                // Parse package
22802                int parseFlags = mDefParseFlags;
22803                if (args.isExternalAsec()) {
22804                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22805                }
22806                if (args.isFwdLocked()) {
22807                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22808                }
22809
22810                synchronized (mInstallLock) {
22811                    PackageParser.Package pkg = null;
22812                    try {
22813                        // Sadly we don't know the package name yet to freeze it
22814                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22815                                SCAN_IGNORE_FROZEN, 0, null);
22816                    } catch (PackageManagerException e) {
22817                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22818                    }
22819                    // Scan the package
22820                    if (pkg != null) {
22821                        /*
22822                         * TODO why is the lock being held? doPostInstall is
22823                         * called in other places without the lock. This needs
22824                         * to be straightened out.
22825                         */
22826                        // writer
22827                        synchronized (mPackages) {
22828                            retCode = PackageManager.INSTALL_SUCCEEDED;
22829                            pkgList.add(pkg.packageName);
22830                            // Post process args
22831                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22832                                    pkg.applicationInfo.uid);
22833                        }
22834                    } else {
22835                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22836                    }
22837                }
22838
22839            } finally {
22840                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22841                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22842                }
22843            }
22844        }
22845        // writer
22846        synchronized (mPackages) {
22847            // If the platform SDK has changed since the last time we booted,
22848            // we need to re-grant app permission to catch any new ones that
22849            // appear. This is really a hack, and means that apps can in some
22850            // cases get permissions that the user didn't initially explicitly
22851            // allow... it would be nice to have some better way to handle
22852            // this situation.
22853            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22854                    : mSettings.getInternalVersion();
22855            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22856                    : StorageManager.UUID_PRIVATE_INTERNAL;
22857
22858            int updateFlags = UPDATE_PERMISSIONS_ALL;
22859            if (ver.sdkVersion != mSdkVersion) {
22860                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22861                        + mSdkVersion + "; regranting permissions for external");
22862                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22863            }
22864            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22865
22866            // Yay, everything is now upgraded
22867            ver.forceCurrent();
22868
22869            // can downgrade to reader
22870            // Persist settings
22871            mSettings.writeLPr();
22872        }
22873        // Send a broadcast to let everyone know we are done processing
22874        if (pkgList.size() > 0) {
22875            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22876        }
22877    }
22878
22879   /*
22880     * Utility method to unload a list of specified containers
22881     */
22882    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22883        // Just unmount all valid containers.
22884        for (AsecInstallArgs arg : cidArgs) {
22885            synchronized (mInstallLock) {
22886                arg.doPostDeleteLI(false);
22887           }
22888       }
22889   }
22890
22891    /*
22892     * Unload packages mounted on external media. This involves deleting package
22893     * data from internal structures, sending broadcasts about disabled packages,
22894     * gc'ing to free up references, unmounting all secure containers
22895     * corresponding to packages on external media, and posting a
22896     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22897     * that we always have to post this message if status has been requested no
22898     * matter what.
22899     */
22900    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22901            final boolean reportStatus) {
22902        if (DEBUG_SD_INSTALL)
22903            Log.i(TAG, "unloading media packages");
22904        ArrayList<String> pkgList = new ArrayList<String>();
22905        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22906        final Set<AsecInstallArgs> keys = processCids.keySet();
22907        for (AsecInstallArgs args : keys) {
22908            String pkgName = args.getPackageName();
22909            if (DEBUG_SD_INSTALL)
22910                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22911            // Delete package internally
22912            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22913            synchronized (mInstallLock) {
22914                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22915                final boolean res;
22916                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22917                        "unloadMediaPackages")) {
22918                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22919                            null);
22920                }
22921                if (res) {
22922                    pkgList.add(pkgName);
22923                } else {
22924                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22925                    failedList.add(args);
22926                }
22927            }
22928        }
22929
22930        // reader
22931        synchronized (mPackages) {
22932            // We didn't update the settings after removing each package;
22933            // write them now for all packages.
22934            mSettings.writeLPr();
22935        }
22936
22937        // We have to absolutely send UPDATED_MEDIA_STATUS only
22938        // after confirming that all the receivers processed the ordered
22939        // broadcast when packages get disabled, force a gc to clean things up.
22940        // and unload all the containers.
22941        if (pkgList.size() > 0) {
22942            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22943                    new IIntentReceiver.Stub() {
22944                public void performReceive(Intent intent, int resultCode, String data,
22945                        Bundle extras, boolean ordered, boolean sticky,
22946                        int sendingUser) throws RemoteException {
22947                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22948                            reportStatus ? 1 : 0, 1, keys);
22949                    mHandler.sendMessage(msg);
22950                }
22951            });
22952        } else {
22953            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22954                    keys);
22955            mHandler.sendMessage(msg);
22956        }
22957    }
22958
22959    private void loadPrivatePackages(final VolumeInfo vol) {
22960        mHandler.post(new Runnable() {
22961            @Override
22962            public void run() {
22963                loadPrivatePackagesInner(vol);
22964            }
22965        });
22966    }
22967
22968    private void loadPrivatePackagesInner(VolumeInfo vol) {
22969        final String volumeUuid = vol.fsUuid;
22970        if (TextUtils.isEmpty(volumeUuid)) {
22971            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22972            return;
22973        }
22974
22975        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22976        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22977        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22978
22979        final VersionInfo ver;
22980        final List<PackageSetting> packages;
22981        synchronized (mPackages) {
22982            ver = mSettings.findOrCreateVersion(volumeUuid);
22983            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22984        }
22985
22986        for (PackageSetting ps : packages) {
22987            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22988            synchronized (mInstallLock) {
22989                final PackageParser.Package pkg;
22990                try {
22991                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22992                    loaded.add(pkg.applicationInfo);
22993
22994                } catch (PackageManagerException e) {
22995                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22996                }
22997
22998                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22999                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23000                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23001                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23002                }
23003            }
23004        }
23005
23006        // Reconcile app data for all started/unlocked users
23007        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23008        final UserManager um = mContext.getSystemService(UserManager.class);
23009        UserManagerInternal umInternal = getUserManagerInternal();
23010        for (UserInfo user : um.getUsers()) {
23011            final int flags;
23012            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23013                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23014            } else if (umInternal.isUserRunning(user.id)) {
23015                flags = StorageManager.FLAG_STORAGE_DE;
23016            } else {
23017                continue;
23018            }
23019
23020            try {
23021                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23022                synchronized (mInstallLock) {
23023                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23024                }
23025            } catch (IllegalStateException e) {
23026                // Device was probably ejected, and we'll process that event momentarily
23027                Slog.w(TAG, "Failed to prepare storage: " + e);
23028            }
23029        }
23030
23031        synchronized (mPackages) {
23032            int updateFlags = UPDATE_PERMISSIONS_ALL;
23033            if (ver.sdkVersion != mSdkVersion) {
23034                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23035                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23036                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23037            }
23038            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23039
23040            // Yay, everything is now upgraded
23041            ver.forceCurrent();
23042
23043            mSettings.writeLPr();
23044        }
23045
23046        for (PackageFreezer freezer : freezers) {
23047            freezer.close();
23048        }
23049
23050        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23051        sendResourcesChangedBroadcast(true, false, loaded, null);
23052        mLoadedVolumes.add(vol.getId());
23053    }
23054
23055    private void unloadPrivatePackages(final VolumeInfo vol) {
23056        mHandler.post(new Runnable() {
23057            @Override
23058            public void run() {
23059                unloadPrivatePackagesInner(vol);
23060            }
23061        });
23062    }
23063
23064    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23065        final String volumeUuid = vol.fsUuid;
23066        if (TextUtils.isEmpty(volumeUuid)) {
23067            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23068            return;
23069        }
23070
23071        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23072        synchronized (mInstallLock) {
23073        synchronized (mPackages) {
23074            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23075            for (PackageSetting ps : packages) {
23076                if (ps.pkg == null) continue;
23077
23078                final ApplicationInfo info = ps.pkg.applicationInfo;
23079                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23080                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23081
23082                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23083                        "unloadPrivatePackagesInner")) {
23084                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23085                            false, null)) {
23086                        unloaded.add(info);
23087                    } else {
23088                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23089                    }
23090                }
23091
23092                // Try very hard to release any references to this package
23093                // so we don't risk the system server being killed due to
23094                // open FDs
23095                AttributeCache.instance().removePackage(ps.name);
23096            }
23097
23098            mSettings.writeLPr();
23099        }
23100        }
23101
23102        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23103        sendResourcesChangedBroadcast(false, false, unloaded, null);
23104        mLoadedVolumes.remove(vol.getId());
23105
23106        // Try very hard to release any references to this path so we don't risk
23107        // the system server being killed due to open FDs
23108        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23109
23110        for (int i = 0; i < 3; i++) {
23111            System.gc();
23112            System.runFinalization();
23113        }
23114    }
23115
23116    private void assertPackageKnown(String volumeUuid, String packageName)
23117            throws PackageManagerException {
23118        synchronized (mPackages) {
23119            // Normalize package name to handle renamed packages
23120            packageName = normalizePackageNameLPr(packageName);
23121
23122            final PackageSetting ps = mSettings.mPackages.get(packageName);
23123            if (ps == null) {
23124                throw new PackageManagerException("Package " + packageName + " is unknown");
23125            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23126                throw new PackageManagerException(
23127                        "Package " + packageName + " found on unknown volume " + volumeUuid
23128                                + "; expected volume " + ps.volumeUuid);
23129            }
23130        }
23131    }
23132
23133    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23134            throws PackageManagerException {
23135        synchronized (mPackages) {
23136            // Normalize package name to handle renamed packages
23137            packageName = normalizePackageNameLPr(packageName);
23138
23139            final PackageSetting ps = mSettings.mPackages.get(packageName);
23140            if (ps == null) {
23141                throw new PackageManagerException("Package " + packageName + " is unknown");
23142            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23143                throw new PackageManagerException(
23144                        "Package " + packageName + " found on unknown volume " + volumeUuid
23145                                + "; expected volume " + ps.volumeUuid);
23146            } else if (!ps.getInstalled(userId)) {
23147                throw new PackageManagerException(
23148                        "Package " + packageName + " not installed for user " + userId);
23149            }
23150        }
23151    }
23152
23153    private List<String> collectAbsoluteCodePaths() {
23154        synchronized (mPackages) {
23155            List<String> codePaths = new ArrayList<>();
23156            final int packageCount = mSettings.mPackages.size();
23157            for (int i = 0; i < packageCount; i++) {
23158                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23159                codePaths.add(ps.codePath.getAbsolutePath());
23160            }
23161            return codePaths;
23162        }
23163    }
23164
23165    /**
23166     * Examine all apps present on given mounted volume, and destroy apps that
23167     * aren't expected, either due to uninstallation or reinstallation on
23168     * another volume.
23169     */
23170    private void reconcileApps(String volumeUuid) {
23171        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23172        List<File> filesToDelete = null;
23173
23174        final File[] files = FileUtils.listFilesOrEmpty(
23175                Environment.getDataAppDirectory(volumeUuid));
23176        for (File file : files) {
23177            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23178                    && !PackageInstallerService.isStageName(file.getName());
23179            if (!isPackage) {
23180                // Ignore entries which are not packages
23181                continue;
23182            }
23183
23184            String absolutePath = file.getAbsolutePath();
23185
23186            boolean pathValid = false;
23187            final int absoluteCodePathCount = absoluteCodePaths.size();
23188            for (int i = 0; i < absoluteCodePathCount; i++) {
23189                String absoluteCodePath = absoluteCodePaths.get(i);
23190                if (absolutePath.startsWith(absoluteCodePath)) {
23191                    pathValid = true;
23192                    break;
23193                }
23194            }
23195
23196            if (!pathValid) {
23197                if (filesToDelete == null) {
23198                    filesToDelete = new ArrayList<>();
23199                }
23200                filesToDelete.add(file);
23201            }
23202        }
23203
23204        if (filesToDelete != null) {
23205            final int fileToDeleteCount = filesToDelete.size();
23206            for (int i = 0; i < fileToDeleteCount; i++) {
23207                File fileToDelete = filesToDelete.get(i);
23208                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23209                synchronized (mInstallLock) {
23210                    removeCodePathLI(fileToDelete);
23211                }
23212            }
23213        }
23214    }
23215
23216    /**
23217     * Reconcile all app data for the given user.
23218     * <p>
23219     * Verifies that directories exist and that ownership and labeling is
23220     * correct for all installed apps on all mounted volumes.
23221     */
23222    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23223        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23224        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23225            final String volumeUuid = vol.getFsUuid();
23226            synchronized (mInstallLock) {
23227                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23228            }
23229        }
23230    }
23231
23232    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23233            boolean migrateAppData) {
23234        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23235    }
23236
23237    /**
23238     * Reconcile all app data on given mounted volume.
23239     * <p>
23240     * Destroys app data that isn't expected, either due to uninstallation or
23241     * reinstallation on another volume.
23242     * <p>
23243     * Verifies that directories exist and that ownership and labeling is
23244     * correct for all installed apps.
23245     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23246     */
23247    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23248            boolean migrateAppData, boolean onlyCoreApps) {
23249        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23250                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23251        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23252
23253        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23254        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23255
23256        // First look for stale data that doesn't belong, and check if things
23257        // have changed since we did our last restorecon
23258        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23259            if (StorageManager.isFileEncryptedNativeOrEmulated()
23260                    && !StorageManager.isUserKeyUnlocked(userId)) {
23261                throw new RuntimeException(
23262                        "Yikes, someone asked us to reconcile CE storage while " + userId
23263                                + " was still locked; this would have caused massive data loss!");
23264            }
23265
23266            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23267            for (File file : files) {
23268                final String packageName = file.getName();
23269                try {
23270                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23271                } catch (PackageManagerException e) {
23272                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23273                    try {
23274                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23275                                StorageManager.FLAG_STORAGE_CE, 0);
23276                    } catch (InstallerException e2) {
23277                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23278                    }
23279                }
23280            }
23281        }
23282        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23283            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23284            for (File file : files) {
23285                final String packageName = file.getName();
23286                try {
23287                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23288                } catch (PackageManagerException e) {
23289                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23290                    try {
23291                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23292                                StorageManager.FLAG_STORAGE_DE, 0);
23293                    } catch (InstallerException e2) {
23294                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23295                    }
23296                }
23297            }
23298        }
23299
23300        // Ensure that data directories are ready to roll for all packages
23301        // installed for this volume and user
23302        final List<PackageSetting> packages;
23303        synchronized (mPackages) {
23304            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23305        }
23306        int preparedCount = 0;
23307        for (PackageSetting ps : packages) {
23308            final String packageName = ps.name;
23309            if (ps.pkg == null) {
23310                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23311                // TODO: might be due to legacy ASEC apps; we should circle back
23312                // and reconcile again once they're scanned
23313                continue;
23314            }
23315            // Skip non-core apps if requested
23316            if (onlyCoreApps && !ps.pkg.coreApp) {
23317                result.add(packageName);
23318                continue;
23319            }
23320
23321            if (ps.getInstalled(userId)) {
23322                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23323                preparedCount++;
23324            }
23325        }
23326
23327        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23328        return result;
23329    }
23330
23331    /**
23332     * Prepare app data for the given app just after it was installed or
23333     * upgraded. This method carefully only touches users that it's installed
23334     * for, and it forces a restorecon to handle any seinfo changes.
23335     * <p>
23336     * Verifies that directories exist and that ownership and labeling is
23337     * correct for all installed apps. If there is an ownership mismatch, it
23338     * will try recovering system apps by wiping data; third-party app data is
23339     * left intact.
23340     * <p>
23341     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23342     */
23343    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23344        final PackageSetting ps;
23345        synchronized (mPackages) {
23346            ps = mSettings.mPackages.get(pkg.packageName);
23347            mSettings.writeKernelMappingLPr(ps);
23348        }
23349
23350        final UserManager um = mContext.getSystemService(UserManager.class);
23351        UserManagerInternal umInternal = getUserManagerInternal();
23352        for (UserInfo user : um.getUsers()) {
23353            final int flags;
23354            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23355                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23356            } else if (umInternal.isUserRunning(user.id)) {
23357                flags = StorageManager.FLAG_STORAGE_DE;
23358            } else {
23359                continue;
23360            }
23361
23362            if (ps.getInstalled(user.id)) {
23363                // TODO: when user data is locked, mark that we're still dirty
23364                prepareAppDataLIF(pkg, user.id, flags);
23365            }
23366        }
23367    }
23368
23369    /**
23370     * Prepare app data for the given app.
23371     * <p>
23372     * Verifies that directories exist and that ownership and labeling is
23373     * correct for all installed apps. If there is an ownership mismatch, this
23374     * will try recovering system apps by wiping data; third-party app data is
23375     * left intact.
23376     */
23377    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23378        if (pkg == null) {
23379            Slog.wtf(TAG, "Package was null!", new Throwable());
23380            return;
23381        }
23382        prepareAppDataLeafLIF(pkg, userId, flags);
23383        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23384        for (int i = 0; i < childCount; i++) {
23385            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23386        }
23387    }
23388
23389    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23390            boolean maybeMigrateAppData) {
23391        prepareAppDataLIF(pkg, userId, flags);
23392
23393        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23394            // We may have just shuffled around app data directories, so
23395            // prepare them one more time
23396            prepareAppDataLIF(pkg, userId, flags);
23397        }
23398    }
23399
23400    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23401        if (DEBUG_APP_DATA) {
23402            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23403                    + Integer.toHexString(flags));
23404        }
23405
23406        final String volumeUuid = pkg.volumeUuid;
23407        final String packageName = pkg.packageName;
23408        final ApplicationInfo app = pkg.applicationInfo;
23409        final int appId = UserHandle.getAppId(app.uid);
23410
23411        Preconditions.checkNotNull(app.seInfo);
23412
23413        long ceDataInode = -1;
23414        try {
23415            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23416                    appId, app.seInfo, app.targetSdkVersion);
23417        } catch (InstallerException e) {
23418            if (app.isSystemApp()) {
23419                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23420                        + ", but trying to recover: " + e);
23421                destroyAppDataLeafLIF(pkg, userId, flags);
23422                try {
23423                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23424                            appId, app.seInfo, app.targetSdkVersion);
23425                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23426                } catch (InstallerException e2) {
23427                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23428                }
23429            } else {
23430                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23431            }
23432        }
23433
23434        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23435            // TODO: mark this structure as dirty so we persist it!
23436            synchronized (mPackages) {
23437                final PackageSetting ps = mSettings.mPackages.get(packageName);
23438                if (ps != null) {
23439                    ps.setCeDataInode(ceDataInode, userId);
23440                }
23441            }
23442        }
23443
23444        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23445    }
23446
23447    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23448        if (pkg == null) {
23449            Slog.wtf(TAG, "Package was null!", new Throwable());
23450            return;
23451        }
23452        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23453        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23454        for (int i = 0; i < childCount; i++) {
23455            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23456        }
23457    }
23458
23459    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23460        final String volumeUuid = pkg.volumeUuid;
23461        final String packageName = pkg.packageName;
23462        final ApplicationInfo app = pkg.applicationInfo;
23463
23464        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23465            // Create a native library symlink only if we have native libraries
23466            // and if the native libraries are 32 bit libraries. We do not provide
23467            // this symlink for 64 bit libraries.
23468            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23469                final String nativeLibPath = app.nativeLibraryDir;
23470                try {
23471                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23472                            nativeLibPath, userId);
23473                } catch (InstallerException e) {
23474                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23475                }
23476            }
23477        }
23478    }
23479
23480    /**
23481     * For system apps on non-FBE devices, this method migrates any existing
23482     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23483     * requested by the app.
23484     */
23485    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23486        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23487                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23488            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23489                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23490            try {
23491                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23492                        storageTarget);
23493            } catch (InstallerException e) {
23494                logCriticalInfo(Log.WARN,
23495                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23496            }
23497            return true;
23498        } else {
23499            return false;
23500        }
23501    }
23502
23503    public PackageFreezer freezePackage(String packageName, String killReason) {
23504        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23505    }
23506
23507    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23508        return new PackageFreezer(packageName, userId, killReason);
23509    }
23510
23511    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23512            String killReason) {
23513        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23514    }
23515
23516    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23517            String killReason) {
23518        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23519            return new PackageFreezer();
23520        } else {
23521            return freezePackage(packageName, userId, killReason);
23522        }
23523    }
23524
23525    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23526            String killReason) {
23527        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23528    }
23529
23530    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23531            String killReason) {
23532        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23533            return new PackageFreezer();
23534        } else {
23535            return freezePackage(packageName, userId, killReason);
23536        }
23537    }
23538
23539    /**
23540     * Class that freezes and kills the given package upon creation, and
23541     * unfreezes it upon closing. This is typically used when doing surgery on
23542     * app code/data to prevent the app from running while you're working.
23543     */
23544    private class PackageFreezer implements AutoCloseable {
23545        private final String mPackageName;
23546        private final PackageFreezer[] mChildren;
23547
23548        private final boolean mWeFroze;
23549
23550        private final AtomicBoolean mClosed = new AtomicBoolean();
23551        private final CloseGuard mCloseGuard = CloseGuard.get();
23552
23553        /**
23554         * Create and return a stub freezer that doesn't actually do anything,
23555         * typically used when someone requested
23556         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23557         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23558         */
23559        public PackageFreezer() {
23560            mPackageName = null;
23561            mChildren = null;
23562            mWeFroze = false;
23563            mCloseGuard.open("close");
23564        }
23565
23566        public PackageFreezer(String packageName, int userId, String killReason) {
23567            synchronized (mPackages) {
23568                mPackageName = packageName;
23569                mWeFroze = mFrozenPackages.add(mPackageName);
23570
23571                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23572                if (ps != null) {
23573                    killApplication(ps.name, ps.appId, userId, killReason);
23574                }
23575
23576                final PackageParser.Package p = mPackages.get(packageName);
23577                if (p != null && p.childPackages != null) {
23578                    final int N = p.childPackages.size();
23579                    mChildren = new PackageFreezer[N];
23580                    for (int i = 0; i < N; i++) {
23581                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23582                                userId, killReason);
23583                    }
23584                } else {
23585                    mChildren = null;
23586                }
23587            }
23588            mCloseGuard.open("close");
23589        }
23590
23591        @Override
23592        protected void finalize() throws Throwable {
23593            try {
23594                if (mCloseGuard != null) {
23595                    mCloseGuard.warnIfOpen();
23596                }
23597
23598                close();
23599            } finally {
23600                super.finalize();
23601            }
23602        }
23603
23604        @Override
23605        public void close() {
23606            mCloseGuard.close();
23607            if (mClosed.compareAndSet(false, true)) {
23608                synchronized (mPackages) {
23609                    if (mWeFroze) {
23610                        mFrozenPackages.remove(mPackageName);
23611                    }
23612
23613                    if (mChildren != null) {
23614                        for (PackageFreezer freezer : mChildren) {
23615                            freezer.close();
23616                        }
23617                    }
23618                }
23619            }
23620        }
23621    }
23622
23623    /**
23624     * Verify that given package is currently frozen.
23625     */
23626    private void checkPackageFrozen(String packageName) {
23627        synchronized (mPackages) {
23628            if (!mFrozenPackages.contains(packageName)) {
23629                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23630            }
23631        }
23632    }
23633
23634    @Override
23635    public int movePackage(final String packageName, final String volumeUuid) {
23636        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23637
23638        final int callingUid = Binder.getCallingUid();
23639        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23640        final int moveId = mNextMoveId.getAndIncrement();
23641        mHandler.post(new Runnable() {
23642            @Override
23643            public void run() {
23644                try {
23645                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23646                } catch (PackageManagerException e) {
23647                    Slog.w(TAG, "Failed to move " + packageName, e);
23648                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
23649                }
23650            }
23651        });
23652        return moveId;
23653    }
23654
23655    private void movePackageInternal(final String packageName, final String volumeUuid,
23656            final int moveId, final int callingUid, UserHandle user)
23657                    throws PackageManagerException {
23658        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23659        final PackageManager pm = mContext.getPackageManager();
23660
23661        final boolean currentAsec;
23662        final String currentVolumeUuid;
23663        final File codeFile;
23664        final String installerPackageName;
23665        final String packageAbiOverride;
23666        final int appId;
23667        final String seinfo;
23668        final String label;
23669        final int targetSdkVersion;
23670        final PackageFreezer freezer;
23671        final int[] installedUserIds;
23672
23673        // reader
23674        synchronized (mPackages) {
23675            final PackageParser.Package pkg = mPackages.get(packageName);
23676            final PackageSetting ps = mSettings.mPackages.get(packageName);
23677            if (pkg == null
23678                    || ps == null
23679                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23680                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23681            }
23682            if (pkg.applicationInfo.isSystemApp()) {
23683                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23684                        "Cannot move system application");
23685            }
23686
23687            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23688            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23689                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23690            if (isInternalStorage && !allow3rdPartyOnInternal) {
23691                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23692                        "3rd party apps are not allowed on internal storage");
23693            }
23694
23695            if (pkg.applicationInfo.isExternalAsec()) {
23696                currentAsec = true;
23697                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23698            } else if (pkg.applicationInfo.isForwardLocked()) {
23699                currentAsec = true;
23700                currentVolumeUuid = "forward_locked";
23701            } else {
23702                currentAsec = false;
23703                currentVolumeUuid = ps.volumeUuid;
23704
23705                final File probe = new File(pkg.codePath);
23706                final File probeOat = new File(probe, "oat");
23707                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23708                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23709                            "Move only supported for modern cluster style installs");
23710                }
23711            }
23712
23713            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23714                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23715                        "Package already moved to " + volumeUuid);
23716            }
23717            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23718                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23719                        "Device admin cannot be moved");
23720            }
23721
23722            if (mFrozenPackages.contains(packageName)) {
23723                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23724                        "Failed to move already frozen package");
23725            }
23726
23727            codeFile = new File(pkg.codePath);
23728            installerPackageName = ps.installerPackageName;
23729            packageAbiOverride = ps.cpuAbiOverrideString;
23730            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23731            seinfo = pkg.applicationInfo.seInfo;
23732            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23733            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23734            freezer = freezePackage(packageName, "movePackageInternal");
23735            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23736        }
23737
23738        final Bundle extras = new Bundle();
23739        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23740        extras.putString(Intent.EXTRA_TITLE, label);
23741        mMoveCallbacks.notifyCreated(moveId, extras);
23742
23743        int installFlags;
23744        final boolean moveCompleteApp;
23745        final File measurePath;
23746
23747        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23748            installFlags = INSTALL_INTERNAL;
23749            moveCompleteApp = !currentAsec;
23750            measurePath = Environment.getDataAppDirectory(volumeUuid);
23751        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23752            installFlags = INSTALL_EXTERNAL;
23753            moveCompleteApp = false;
23754            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23755        } else {
23756            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23757            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23758                    || !volume.isMountedWritable()) {
23759                freezer.close();
23760                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23761                        "Move location not mounted private volume");
23762            }
23763
23764            Preconditions.checkState(!currentAsec);
23765
23766            installFlags = INSTALL_INTERNAL;
23767            moveCompleteApp = true;
23768            measurePath = Environment.getDataAppDirectory(volumeUuid);
23769        }
23770
23771        // If we're moving app data around, we need all the users unlocked
23772        if (moveCompleteApp) {
23773            for (int userId : installedUserIds) {
23774                if (StorageManager.isFileEncryptedNativeOrEmulated()
23775                        && !StorageManager.isUserKeyUnlocked(userId)) {
23776                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
23777                            "User " + userId + " must be unlocked");
23778                }
23779            }
23780        }
23781
23782        final PackageStats stats = new PackageStats(null, -1);
23783        synchronized (mInstaller) {
23784            for (int userId : installedUserIds) {
23785                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23786                    freezer.close();
23787                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23788                            "Failed to measure package size");
23789                }
23790            }
23791        }
23792
23793        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23794                + stats.dataSize);
23795
23796        final long startFreeBytes = measurePath.getUsableSpace();
23797        final long sizeBytes;
23798        if (moveCompleteApp) {
23799            sizeBytes = stats.codeSize + stats.dataSize;
23800        } else {
23801            sizeBytes = stats.codeSize;
23802        }
23803
23804        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23805            freezer.close();
23806            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23807                    "Not enough free space to move");
23808        }
23809
23810        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23811
23812        final CountDownLatch installedLatch = new CountDownLatch(1);
23813        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23814            @Override
23815            public void onUserActionRequired(Intent intent) throws RemoteException {
23816                throw new IllegalStateException();
23817            }
23818
23819            @Override
23820            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23821                    Bundle extras) throws RemoteException {
23822                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23823                        + PackageManager.installStatusToString(returnCode, msg));
23824
23825                installedLatch.countDown();
23826                freezer.close();
23827
23828                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23829                switch (status) {
23830                    case PackageInstaller.STATUS_SUCCESS:
23831                        mMoveCallbacks.notifyStatusChanged(moveId,
23832                                PackageManager.MOVE_SUCCEEDED);
23833                        break;
23834                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23835                        mMoveCallbacks.notifyStatusChanged(moveId,
23836                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23837                        break;
23838                    default:
23839                        mMoveCallbacks.notifyStatusChanged(moveId,
23840                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23841                        break;
23842                }
23843            }
23844        };
23845
23846        final MoveInfo move;
23847        if (moveCompleteApp) {
23848            // Kick off a thread to report progress estimates
23849            new Thread() {
23850                @Override
23851                public void run() {
23852                    while (true) {
23853                        try {
23854                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23855                                break;
23856                            }
23857                        } catch (InterruptedException ignored) {
23858                        }
23859
23860                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23861                        final int progress = 10 + (int) MathUtils.constrain(
23862                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23863                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23864                    }
23865                }
23866            }.start();
23867
23868            final String dataAppName = codeFile.getName();
23869            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23870                    dataAppName, appId, seinfo, targetSdkVersion);
23871        } else {
23872            move = null;
23873        }
23874
23875        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23876
23877        final Message msg = mHandler.obtainMessage(INIT_COPY);
23878        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23879        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23880                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23881                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23882                PackageManager.INSTALL_REASON_UNKNOWN);
23883        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23884        msg.obj = params;
23885
23886        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23887                System.identityHashCode(msg.obj));
23888        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23889                System.identityHashCode(msg.obj));
23890
23891        mHandler.sendMessage(msg);
23892    }
23893
23894    @Override
23895    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23896        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23897
23898        final int realMoveId = mNextMoveId.getAndIncrement();
23899        final Bundle extras = new Bundle();
23900        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23901        mMoveCallbacks.notifyCreated(realMoveId, extras);
23902
23903        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23904            @Override
23905            public void onCreated(int moveId, Bundle extras) {
23906                // Ignored
23907            }
23908
23909            @Override
23910            public void onStatusChanged(int moveId, int status, long estMillis) {
23911                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23912            }
23913        };
23914
23915        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23916        storage.setPrimaryStorageUuid(volumeUuid, callback);
23917        return realMoveId;
23918    }
23919
23920    @Override
23921    public int getMoveStatus(int moveId) {
23922        mContext.enforceCallingOrSelfPermission(
23923                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23924        return mMoveCallbacks.mLastStatus.get(moveId);
23925    }
23926
23927    @Override
23928    public void registerMoveCallback(IPackageMoveObserver callback) {
23929        mContext.enforceCallingOrSelfPermission(
23930                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23931        mMoveCallbacks.register(callback);
23932    }
23933
23934    @Override
23935    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23936        mContext.enforceCallingOrSelfPermission(
23937                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23938        mMoveCallbacks.unregister(callback);
23939    }
23940
23941    @Override
23942    public boolean setInstallLocation(int loc) {
23943        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23944                null);
23945        if (getInstallLocation() == loc) {
23946            return true;
23947        }
23948        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23949                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23950            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23951                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23952            return true;
23953        }
23954        return false;
23955   }
23956
23957    @Override
23958    public int getInstallLocation() {
23959        // allow instant app access
23960        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23961                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23962                PackageHelper.APP_INSTALL_AUTO);
23963    }
23964
23965    /** Called by UserManagerService */
23966    void cleanUpUser(UserManagerService userManager, int userHandle) {
23967        synchronized (mPackages) {
23968            mDirtyUsers.remove(userHandle);
23969            mUserNeedsBadging.delete(userHandle);
23970            mSettings.removeUserLPw(userHandle);
23971            mPendingBroadcasts.remove(userHandle);
23972            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23973            removeUnusedPackagesLPw(userManager, userHandle);
23974        }
23975    }
23976
23977    /**
23978     * We're removing userHandle and would like to remove any downloaded packages
23979     * that are no longer in use by any other user.
23980     * @param userHandle the user being removed
23981     */
23982    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23983        final boolean DEBUG_CLEAN_APKS = false;
23984        int [] users = userManager.getUserIds();
23985        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23986        while (psit.hasNext()) {
23987            PackageSetting ps = psit.next();
23988            if (ps.pkg == null) {
23989                continue;
23990            }
23991            final String packageName = ps.pkg.packageName;
23992            // Skip over if system app
23993            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23994                continue;
23995            }
23996            if (DEBUG_CLEAN_APKS) {
23997                Slog.i(TAG, "Checking package " + packageName);
23998            }
23999            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24000            if (keep) {
24001                if (DEBUG_CLEAN_APKS) {
24002                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24003                }
24004            } else {
24005                for (int i = 0; i < users.length; i++) {
24006                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24007                        keep = true;
24008                        if (DEBUG_CLEAN_APKS) {
24009                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24010                                    + users[i]);
24011                        }
24012                        break;
24013                    }
24014                }
24015            }
24016            if (!keep) {
24017                if (DEBUG_CLEAN_APKS) {
24018                    Slog.i(TAG, "  Removing package " + packageName);
24019                }
24020                mHandler.post(new Runnable() {
24021                    public void run() {
24022                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24023                                userHandle, 0);
24024                    } //end run
24025                });
24026            }
24027        }
24028    }
24029
24030    /** Called by UserManagerService */
24031    void createNewUser(int userId, String[] disallowedPackages) {
24032        synchronized (mInstallLock) {
24033            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24034        }
24035        synchronized (mPackages) {
24036            scheduleWritePackageRestrictionsLocked(userId);
24037            scheduleWritePackageListLocked(userId);
24038            applyFactoryDefaultBrowserLPw(userId);
24039            primeDomainVerificationsLPw(userId);
24040        }
24041    }
24042
24043    void onNewUserCreated(final int userId) {
24044        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24045        // If permission review for legacy apps is required, we represent
24046        // dagerous permissions for such apps as always granted runtime
24047        // permissions to keep per user flag state whether review is needed.
24048        // Hence, if a new user is added we have to propagate dangerous
24049        // permission grants for these legacy apps.
24050        if (mPermissionReviewRequired) {
24051            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24052                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24053        }
24054    }
24055
24056    @Override
24057    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24058        mContext.enforceCallingOrSelfPermission(
24059                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24060                "Only package verification agents can read the verifier device identity");
24061
24062        synchronized (mPackages) {
24063            return mSettings.getVerifierDeviceIdentityLPw();
24064        }
24065    }
24066
24067    @Override
24068    public void setPermissionEnforced(String permission, boolean enforced) {
24069        // TODO: Now that we no longer change GID for storage, this should to away.
24070        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24071                "setPermissionEnforced");
24072        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24073            synchronized (mPackages) {
24074                if (mSettings.mReadExternalStorageEnforced == null
24075                        || mSettings.mReadExternalStorageEnforced != enforced) {
24076                    mSettings.mReadExternalStorageEnforced = enforced;
24077                    mSettings.writeLPr();
24078                }
24079            }
24080            // kill any non-foreground processes so we restart them and
24081            // grant/revoke the GID.
24082            final IActivityManager am = ActivityManager.getService();
24083            if (am != null) {
24084                final long token = Binder.clearCallingIdentity();
24085                try {
24086                    am.killProcessesBelowForeground("setPermissionEnforcement");
24087                } catch (RemoteException e) {
24088                } finally {
24089                    Binder.restoreCallingIdentity(token);
24090                }
24091            }
24092        } else {
24093            throw new IllegalArgumentException("No selective enforcement for " + permission);
24094        }
24095    }
24096
24097    @Override
24098    @Deprecated
24099    public boolean isPermissionEnforced(String permission) {
24100        // allow instant applications
24101        return true;
24102    }
24103
24104    @Override
24105    public boolean isStorageLow() {
24106        // allow instant applications
24107        final long token = Binder.clearCallingIdentity();
24108        try {
24109            final DeviceStorageMonitorInternal
24110                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24111            if (dsm != null) {
24112                return dsm.isMemoryLow();
24113            } else {
24114                return false;
24115            }
24116        } finally {
24117            Binder.restoreCallingIdentity(token);
24118        }
24119    }
24120
24121    @Override
24122    public IPackageInstaller getPackageInstaller() {
24123        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24124            return null;
24125        }
24126        return mInstallerService;
24127    }
24128
24129    private boolean userNeedsBadging(int userId) {
24130        int index = mUserNeedsBadging.indexOfKey(userId);
24131        if (index < 0) {
24132            final UserInfo userInfo;
24133            final long token = Binder.clearCallingIdentity();
24134            try {
24135                userInfo = sUserManager.getUserInfo(userId);
24136            } finally {
24137                Binder.restoreCallingIdentity(token);
24138            }
24139            final boolean b;
24140            if (userInfo != null && userInfo.isManagedProfile()) {
24141                b = true;
24142            } else {
24143                b = false;
24144            }
24145            mUserNeedsBadging.put(userId, b);
24146            return b;
24147        }
24148        return mUserNeedsBadging.valueAt(index);
24149    }
24150
24151    @Override
24152    public KeySet getKeySetByAlias(String packageName, String alias) {
24153        if (packageName == null || alias == null) {
24154            return null;
24155        }
24156        synchronized(mPackages) {
24157            final PackageParser.Package pkg = mPackages.get(packageName);
24158            if (pkg == null) {
24159                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24160                throw new IllegalArgumentException("Unknown package: " + packageName);
24161            }
24162            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24163            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24164                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24165                throw new IllegalArgumentException("Unknown package: " + packageName);
24166            }
24167            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24168            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24169        }
24170    }
24171
24172    @Override
24173    public KeySet getSigningKeySet(String packageName) {
24174        if (packageName == null) {
24175            return null;
24176        }
24177        synchronized(mPackages) {
24178            final int callingUid = Binder.getCallingUid();
24179            final int callingUserId = UserHandle.getUserId(callingUid);
24180            final PackageParser.Package pkg = mPackages.get(packageName);
24181            if (pkg == null) {
24182                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24183                throw new IllegalArgumentException("Unknown package: " + packageName);
24184            }
24185            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24186            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24187                // filter and pretend the package doesn't exist
24188                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24189                        + ", uid:" + callingUid);
24190                throw new IllegalArgumentException("Unknown package: " + packageName);
24191            }
24192            if (pkg.applicationInfo.uid != callingUid
24193                    && Process.SYSTEM_UID != callingUid) {
24194                throw new SecurityException("May not access signing KeySet of other apps.");
24195            }
24196            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24197            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24198        }
24199    }
24200
24201    @Override
24202    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24203        final int callingUid = Binder.getCallingUid();
24204        if (getInstantAppPackageName(callingUid) != null) {
24205            return false;
24206        }
24207        if (packageName == null || ks == null) {
24208            return false;
24209        }
24210        synchronized(mPackages) {
24211            final PackageParser.Package pkg = mPackages.get(packageName);
24212            if (pkg == null
24213                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24214                            UserHandle.getUserId(callingUid))) {
24215                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24216                throw new IllegalArgumentException("Unknown package: " + packageName);
24217            }
24218            IBinder ksh = ks.getToken();
24219            if (ksh instanceof KeySetHandle) {
24220                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24221                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24222            }
24223            return false;
24224        }
24225    }
24226
24227    @Override
24228    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24229        final int callingUid = Binder.getCallingUid();
24230        if (getInstantAppPackageName(callingUid) != null) {
24231            return false;
24232        }
24233        if (packageName == null || ks == null) {
24234            return false;
24235        }
24236        synchronized(mPackages) {
24237            final PackageParser.Package pkg = mPackages.get(packageName);
24238            if (pkg == null
24239                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24240                            UserHandle.getUserId(callingUid))) {
24241                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24242                throw new IllegalArgumentException("Unknown package: " + packageName);
24243            }
24244            IBinder ksh = ks.getToken();
24245            if (ksh instanceof KeySetHandle) {
24246                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24247                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24248            }
24249            return false;
24250        }
24251    }
24252
24253    private void deletePackageIfUnusedLPr(final String packageName) {
24254        PackageSetting ps = mSettings.mPackages.get(packageName);
24255        if (ps == null) {
24256            return;
24257        }
24258        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24259            // TODO Implement atomic delete if package is unused
24260            // It is currently possible that the package will be deleted even if it is installed
24261            // after this method returns.
24262            mHandler.post(new Runnable() {
24263                public void run() {
24264                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24265                            0, PackageManager.DELETE_ALL_USERS);
24266                }
24267            });
24268        }
24269    }
24270
24271    /**
24272     * Check and throw if the given before/after packages would be considered a
24273     * downgrade.
24274     */
24275    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24276            throws PackageManagerException {
24277        if (after.versionCode < before.mVersionCode) {
24278            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24279                    "Update version code " + after.versionCode + " is older than current "
24280                    + before.mVersionCode);
24281        } else if (after.versionCode == before.mVersionCode) {
24282            if (after.baseRevisionCode < before.baseRevisionCode) {
24283                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24284                        "Update base revision code " + after.baseRevisionCode
24285                        + " is older than current " + before.baseRevisionCode);
24286            }
24287
24288            if (!ArrayUtils.isEmpty(after.splitNames)) {
24289                for (int i = 0; i < after.splitNames.length; i++) {
24290                    final String splitName = after.splitNames[i];
24291                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24292                    if (j != -1) {
24293                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24294                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24295                                    "Update split " + splitName + " revision code "
24296                                    + after.splitRevisionCodes[i] + " is older than current "
24297                                    + before.splitRevisionCodes[j]);
24298                        }
24299                    }
24300                }
24301            }
24302        }
24303    }
24304
24305    private static class MoveCallbacks extends Handler {
24306        private static final int MSG_CREATED = 1;
24307        private static final int MSG_STATUS_CHANGED = 2;
24308
24309        private final RemoteCallbackList<IPackageMoveObserver>
24310                mCallbacks = new RemoteCallbackList<>();
24311
24312        private final SparseIntArray mLastStatus = new SparseIntArray();
24313
24314        public MoveCallbacks(Looper looper) {
24315            super(looper);
24316        }
24317
24318        public void register(IPackageMoveObserver callback) {
24319            mCallbacks.register(callback);
24320        }
24321
24322        public void unregister(IPackageMoveObserver callback) {
24323            mCallbacks.unregister(callback);
24324        }
24325
24326        @Override
24327        public void handleMessage(Message msg) {
24328            final SomeArgs args = (SomeArgs) msg.obj;
24329            final int n = mCallbacks.beginBroadcast();
24330            for (int i = 0; i < n; i++) {
24331                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24332                try {
24333                    invokeCallback(callback, msg.what, args);
24334                } catch (RemoteException ignored) {
24335                }
24336            }
24337            mCallbacks.finishBroadcast();
24338            args.recycle();
24339        }
24340
24341        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24342                throws RemoteException {
24343            switch (what) {
24344                case MSG_CREATED: {
24345                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24346                    break;
24347                }
24348                case MSG_STATUS_CHANGED: {
24349                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24350                    break;
24351                }
24352            }
24353        }
24354
24355        private void notifyCreated(int moveId, Bundle extras) {
24356            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24357
24358            final SomeArgs args = SomeArgs.obtain();
24359            args.argi1 = moveId;
24360            args.arg2 = extras;
24361            obtainMessage(MSG_CREATED, args).sendToTarget();
24362        }
24363
24364        private void notifyStatusChanged(int moveId, int status) {
24365            notifyStatusChanged(moveId, status, -1);
24366        }
24367
24368        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24369            Slog.v(TAG, "Move " + moveId + " status " + status);
24370
24371            final SomeArgs args = SomeArgs.obtain();
24372            args.argi1 = moveId;
24373            args.argi2 = status;
24374            args.arg3 = estMillis;
24375            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24376
24377            synchronized (mLastStatus) {
24378                mLastStatus.put(moveId, status);
24379            }
24380        }
24381    }
24382
24383    private final static class OnPermissionChangeListeners extends Handler {
24384        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24385
24386        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24387                new RemoteCallbackList<>();
24388
24389        public OnPermissionChangeListeners(Looper looper) {
24390            super(looper);
24391        }
24392
24393        @Override
24394        public void handleMessage(Message msg) {
24395            switch (msg.what) {
24396                case MSG_ON_PERMISSIONS_CHANGED: {
24397                    final int uid = msg.arg1;
24398                    handleOnPermissionsChanged(uid);
24399                } break;
24400            }
24401        }
24402
24403        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24404            mPermissionListeners.register(listener);
24405
24406        }
24407
24408        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24409            mPermissionListeners.unregister(listener);
24410        }
24411
24412        public void onPermissionsChanged(int uid) {
24413            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24414                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24415            }
24416        }
24417
24418        private void handleOnPermissionsChanged(int uid) {
24419            final int count = mPermissionListeners.beginBroadcast();
24420            try {
24421                for (int i = 0; i < count; i++) {
24422                    IOnPermissionsChangeListener callback = mPermissionListeners
24423                            .getBroadcastItem(i);
24424                    try {
24425                        callback.onPermissionsChanged(uid);
24426                    } catch (RemoteException e) {
24427                        Log.e(TAG, "Permission listener is dead", e);
24428                    }
24429                }
24430            } finally {
24431                mPermissionListeners.finishBroadcast();
24432            }
24433        }
24434    }
24435
24436    private class PackageManagerInternalImpl extends PackageManagerInternal {
24437        @Override
24438        public void setLocationPackagesProvider(PackagesProvider provider) {
24439            synchronized (mPackages) {
24440                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24441            }
24442        }
24443
24444        @Override
24445        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24446            synchronized (mPackages) {
24447                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24448            }
24449        }
24450
24451        @Override
24452        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24453            synchronized (mPackages) {
24454                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24455            }
24456        }
24457
24458        @Override
24459        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24460            synchronized (mPackages) {
24461                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24462            }
24463        }
24464
24465        @Override
24466        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24467            synchronized (mPackages) {
24468                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24469            }
24470        }
24471
24472        @Override
24473        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24474            synchronized (mPackages) {
24475                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24476            }
24477        }
24478
24479        @Override
24480        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24481            synchronized (mPackages) {
24482                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24483                        packageName, userId);
24484            }
24485        }
24486
24487        @Override
24488        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24489            synchronized (mPackages) {
24490                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24491                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24492                        packageName, userId);
24493            }
24494        }
24495
24496        @Override
24497        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24498            synchronized (mPackages) {
24499                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24500                        packageName, userId);
24501            }
24502        }
24503
24504        @Override
24505        public void setKeepUninstalledPackages(final List<String> packageList) {
24506            Preconditions.checkNotNull(packageList);
24507            List<String> removedFromList = null;
24508            synchronized (mPackages) {
24509                if (mKeepUninstalledPackages != null) {
24510                    final int packagesCount = mKeepUninstalledPackages.size();
24511                    for (int i = 0; i < packagesCount; i++) {
24512                        String oldPackage = mKeepUninstalledPackages.get(i);
24513                        if (packageList != null && packageList.contains(oldPackage)) {
24514                            continue;
24515                        }
24516                        if (removedFromList == null) {
24517                            removedFromList = new ArrayList<>();
24518                        }
24519                        removedFromList.add(oldPackage);
24520                    }
24521                }
24522                mKeepUninstalledPackages = new ArrayList<>(packageList);
24523                if (removedFromList != null) {
24524                    final int removedCount = removedFromList.size();
24525                    for (int i = 0; i < removedCount; i++) {
24526                        deletePackageIfUnusedLPr(removedFromList.get(i));
24527                    }
24528                }
24529            }
24530        }
24531
24532        @Override
24533        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24534            synchronized (mPackages) {
24535                // If we do not support permission review, done.
24536                if (!mPermissionReviewRequired) {
24537                    return false;
24538                }
24539
24540                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24541                if (packageSetting == null) {
24542                    return false;
24543                }
24544
24545                // Permission review applies only to apps not supporting the new permission model.
24546                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24547                    return false;
24548                }
24549
24550                // Legacy apps have the permission and get user consent on launch.
24551                PermissionsState permissionsState = packageSetting.getPermissionsState();
24552                return permissionsState.isPermissionReviewRequired(userId);
24553            }
24554        }
24555
24556        @Override
24557        public PackageInfo getPackageInfo(
24558                String packageName, int flags, int filterCallingUid, int userId) {
24559            return PackageManagerService.this
24560                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24561                            flags, filterCallingUid, userId);
24562        }
24563
24564        @Override
24565        public ApplicationInfo getApplicationInfo(
24566                String packageName, int flags, int filterCallingUid, int userId) {
24567            return PackageManagerService.this
24568                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24569        }
24570
24571        @Override
24572        public ActivityInfo getActivityInfo(
24573                ComponentName component, int flags, int filterCallingUid, int userId) {
24574            return PackageManagerService.this
24575                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24576        }
24577
24578        @Override
24579        public List<ResolveInfo> queryIntentActivities(
24580                Intent intent, int flags, int filterCallingUid, int userId) {
24581            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24582            return PackageManagerService.this
24583                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24584                            userId, false /*resolveForStart*/);
24585        }
24586
24587        @Override
24588        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24589                int userId) {
24590            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24591        }
24592
24593        @Override
24594        public void setDeviceAndProfileOwnerPackages(
24595                int deviceOwnerUserId, String deviceOwnerPackage,
24596                SparseArray<String> profileOwnerPackages) {
24597            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24598                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24599        }
24600
24601        @Override
24602        public boolean isPackageDataProtected(int userId, String packageName) {
24603            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24604        }
24605
24606        @Override
24607        public boolean isPackageEphemeral(int userId, String packageName) {
24608            synchronized (mPackages) {
24609                final PackageSetting ps = mSettings.mPackages.get(packageName);
24610                return ps != null ? ps.getInstantApp(userId) : false;
24611            }
24612        }
24613
24614        @Override
24615        public boolean wasPackageEverLaunched(String packageName, int userId) {
24616            synchronized (mPackages) {
24617                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24618            }
24619        }
24620
24621        @Override
24622        public void grantRuntimePermission(String packageName, String name, int userId,
24623                boolean overridePolicy) {
24624            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24625                    overridePolicy);
24626        }
24627
24628        @Override
24629        public void revokeRuntimePermission(String packageName, String name, int userId,
24630                boolean overridePolicy) {
24631            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24632                    overridePolicy);
24633        }
24634
24635        @Override
24636        public String getNameForUid(int uid) {
24637            return PackageManagerService.this.getNameForUid(uid);
24638        }
24639
24640        @Override
24641        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24642                Intent origIntent, String resolvedType, String callingPackage,
24643                Bundle verificationBundle, int userId) {
24644            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24645                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24646                    userId);
24647        }
24648
24649        @Override
24650        public void grantEphemeralAccess(int userId, Intent intent,
24651                int targetAppId, int ephemeralAppId) {
24652            synchronized (mPackages) {
24653                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24654                        targetAppId, ephemeralAppId);
24655            }
24656        }
24657
24658        @Override
24659        public boolean isInstantAppInstallerComponent(ComponentName component) {
24660            synchronized (mPackages) {
24661                return mInstantAppInstallerActivity != null
24662                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24663            }
24664        }
24665
24666        @Override
24667        public void pruneInstantApps() {
24668            mInstantAppRegistry.pruneInstantApps();
24669        }
24670
24671        @Override
24672        public String getSetupWizardPackageName() {
24673            return mSetupWizardPackage;
24674        }
24675
24676        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24677            if (policy != null) {
24678                mExternalSourcesPolicy = policy;
24679            }
24680        }
24681
24682        @Override
24683        public boolean isPackagePersistent(String packageName) {
24684            synchronized (mPackages) {
24685                PackageParser.Package pkg = mPackages.get(packageName);
24686                return pkg != null
24687                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24688                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24689                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24690                        : false;
24691            }
24692        }
24693
24694        @Override
24695        public List<PackageInfo> getOverlayPackages(int userId) {
24696            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24697            synchronized (mPackages) {
24698                for (PackageParser.Package p : mPackages.values()) {
24699                    if (p.mOverlayTarget != null) {
24700                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24701                        if (pkg != null) {
24702                            overlayPackages.add(pkg);
24703                        }
24704                    }
24705                }
24706            }
24707            return overlayPackages;
24708        }
24709
24710        @Override
24711        public List<String> getTargetPackageNames(int userId) {
24712            List<String> targetPackages = new ArrayList<>();
24713            synchronized (mPackages) {
24714                for (PackageParser.Package p : mPackages.values()) {
24715                    if (p.mOverlayTarget == null) {
24716                        targetPackages.add(p.packageName);
24717                    }
24718                }
24719            }
24720            return targetPackages;
24721        }
24722
24723        @Override
24724        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24725                @Nullable List<String> overlayPackageNames) {
24726            synchronized (mPackages) {
24727                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24728                    Slog.e(TAG, "failed to find package " + targetPackageName);
24729                    return false;
24730                }
24731                ArrayList<String> overlayPaths = null;
24732                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24733                    final int N = overlayPackageNames.size();
24734                    overlayPaths = new ArrayList<>(N);
24735                    for (int i = 0; i < N; i++) {
24736                        final String packageName = overlayPackageNames.get(i);
24737                        final PackageParser.Package pkg = mPackages.get(packageName);
24738                        if (pkg == null) {
24739                            Slog.e(TAG, "failed to find package " + packageName);
24740                            return false;
24741                        }
24742                        overlayPaths.add(pkg.baseCodePath);
24743                    }
24744                }
24745
24746                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24747                ps.setOverlayPaths(overlayPaths, userId);
24748                return true;
24749            }
24750        }
24751
24752        @Override
24753        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24754                int flags, int userId) {
24755            return resolveIntentInternal(
24756                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24757        }
24758
24759        @Override
24760        public ResolveInfo resolveService(Intent intent, String resolvedType,
24761                int flags, int userId, int callingUid) {
24762            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24763        }
24764
24765        @Override
24766        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24767            synchronized (mPackages) {
24768                mIsolatedOwners.put(isolatedUid, ownerUid);
24769            }
24770        }
24771
24772        @Override
24773        public void removeIsolatedUid(int isolatedUid) {
24774            synchronized (mPackages) {
24775                mIsolatedOwners.delete(isolatedUid);
24776            }
24777        }
24778
24779        @Override
24780        public int getUidTargetSdkVersion(int uid) {
24781            synchronized (mPackages) {
24782                return getUidTargetSdkVersionLockedLPr(uid);
24783            }
24784        }
24785
24786        @Override
24787        public boolean canAccessInstantApps(int callingUid, int userId) {
24788            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24789        }
24790    }
24791
24792    @Override
24793    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24794        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24795        synchronized (mPackages) {
24796            final long identity = Binder.clearCallingIdentity();
24797            try {
24798                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24799                        packageNames, userId);
24800            } finally {
24801                Binder.restoreCallingIdentity(identity);
24802            }
24803        }
24804    }
24805
24806    @Override
24807    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24808        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24809        synchronized (mPackages) {
24810            final long identity = Binder.clearCallingIdentity();
24811            try {
24812                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24813                        packageNames, userId);
24814            } finally {
24815                Binder.restoreCallingIdentity(identity);
24816            }
24817        }
24818    }
24819
24820    private static void enforceSystemOrPhoneCaller(String tag) {
24821        int callingUid = Binder.getCallingUid();
24822        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24823            throw new SecurityException(
24824                    "Cannot call " + tag + " from UID " + callingUid);
24825        }
24826    }
24827
24828    boolean isHistoricalPackageUsageAvailable() {
24829        return mPackageUsage.isHistoricalPackageUsageAvailable();
24830    }
24831
24832    /**
24833     * Return a <b>copy</b> of the collection of packages known to the package manager.
24834     * @return A copy of the values of mPackages.
24835     */
24836    Collection<PackageParser.Package> getPackages() {
24837        synchronized (mPackages) {
24838            return new ArrayList<>(mPackages.values());
24839        }
24840    }
24841
24842    /**
24843     * Logs process start information (including base APK hash) to the security log.
24844     * @hide
24845     */
24846    @Override
24847    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24848            String apkFile, int pid) {
24849        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24850            return;
24851        }
24852        if (!SecurityLog.isLoggingEnabled()) {
24853            return;
24854        }
24855        Bundle data = new Bundle();
24856        data.putLong("startTimestamp", System.currentTimeMillis());
24857        data.putString("processName", processName);
24858        data.putInt("uid", uid);
24859        data.putString("seinfo", seinfo);
24860        data.putString("apkFile", apkFile);
24861        data.putInt("pid", pid);
24862        Message msg = mProcessLoggingHandler.obtainMessage(
24863                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24864        msg.setData(data);
24865        mProcessLoggingHandler.sendMessage(msg);
24866    }
24867
24868    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24869        return mCompilerStats.getPackageStats(pkgName);
24870    }
24871
24872    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24873        return getOrCreateCompilerPackageStats(pkg.packageName);
24874    }
24875
24876    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24877        return mCompilerStats.getOrCreatePackageStats(pkgName);
24878    }
24879
24880    public void deleteCompilerPackageStats(String pkgName) {
24881        mCompilerStats.deletePackageStats(pkgName);
24882    }
24883
24884    @Override
24885    public int getInstallReason(String packageName, int userId) {
24886        final int callingUid = Binder.getCallingUid();
24887        enforceCrossUserPermission(callingUid, userId,
24888                true /* requireFullPermission */, false /* checkShell */,
24889                "get install reason");
24890        synchronized (mPackages) {
24891            final PackageSetting ps = mSettings.mPackages.get(packageName);
24892            if (filterAppAccessLPr(ps, callingUid, userId)) {
24893                return PackageManager.INSTALL_REASON_UNKNOWN;
24894            }
24895            if (ps != null) {
24896                return ps.getInstallReason(userId);
24897            }
24898        }
24899        return PackageManager.INSTALL_REASON_UNKNOWN;
24900    }
24901
24902    @Override
24903    public boolean canRequestPackageInstalls(String packageName, int userId) {
24904        return canRequestPackageInstallsInternal(packageName, 0, userId,
24905                true /* throwIfPermNotDeclared*/);
24906    }
24907
24908    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24909            boolean throwIfPermNotDeclared) {
24910        int callingUid = Binder.getCallingUid();
24911        int uid = getPackageUid(packageName, 0, userId);
24912        if (callingUid != uid && callingUid != Process.ROOT_UID
24913                && callingUid != Process.SYSTEM_UID) {
24914            throw new SecurityException(
24915                    "Caller uid " + callingUid + " does not own package " + packageName);
24916        }
24917        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24918        if (info == null) {
24919            return false;
24920        }
24921        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24922            return false;
24923        }
24924        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24925        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24926        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24927            if (throwIfPermNotDeclared) {
24928                throw new SecurityException("Need to declare " + appOpPermission
24929                        + " to call this api");
24930            } else {
24931                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24932                return false;
24933            }
24934        }
24935        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24936            return false;
24937        }
24938        if (mExternalSourcesPolicy != null) {
24939            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24940            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24941                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24942            }
24943        }
24944        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24945    }
24946
24947    @Override
24948    public ComponentName getInstantAppResolverSettingsComponent() {
24949        return mInstantAppResolverSettingsComponent;
24950    }
24951
24952    @Override
24953    public ComponentName getInstantAppInstallerComponent() {
24954        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24955            return null;
24956        }
24957        return mInstantAppInstallerActivity == null
24958                ? null : mInstantAppInstallerActivity.getComponentName();
24959    }
24960
24961    @Override
24962    public String getInstantAppAndroidId(String packageName, int userId) {
24963        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24964                "getInstantAppAndroidId");
24965        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24966                true /* requireFullPermission */, false /* checkShell */,
24967                "getInstantAppAndroidId");
24968        // Make sure the target is an Instant App.
24969        if (!isInstantApp(packageName, userId)) {
24970            return null;
24971        }
24972        synchronized (mPackages) {
24973            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24974        }
24975    }
24976}
24977
24978interface PackageSender {
24979    void sendPackageBroadcast(final String action, final String pkg,
24980        final Bundle extras, final int flags, final String targetPkg,
24981        final IIntentReceiver finishedReceiver, final int[] userIds);
24982    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
24983        int appId, int... userIds);
24984}
24985