PackageManagerService.java revision 3bec94d78b0a66c4fa5cebd851ea33bcc51916b0
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.pm.dex.DexoptOptions;
287import com.android.server.pm.dex.PackageDexUsage;
288import com.android.server.storage.DeviceStorageMonitorInternal;
289
290import dalvik.system.CloseGuard;
291import dalvik.system.DexFile;
292import dalvik.system.VMRuntime;
293
294import libcore.io.IoUtils;
295import libcore.util.EmptyArray;
296
297import org.xmlpull.v1.XmlPullParser;
298import org.xmlpull.v1.XmlPullParserException;
299import org.xmlpull.v1.XmlSerializer;
300
301import java.io.BufferedOutputStream;
302import java.io.BufferedReader;
303import java.io.ByteArrayInputStream;
304import java.io.ByteArrayOutputStream;
305import java.io.File;
306import java.io.FileDescriptor;
307import java.io.FileInputStream;
308import java.io.FileOutputStream;
309import java.io.FileReader;
310import java.io.FilenameFilter;
311import java.io.IOException;
312import java.io.PrintWriter;
313import java.lang.annotation.Retention;
314import java.lang.annotation.RetentionPolicy;
315import java.nio.charset.StandardCharsets;
316import java.security.DigestInputStream;
317import java.security.MessageDigest;
318import java.security.NoSuchAlgorithmException;
319import java.security.PublicKey;
320import java.security.SecureRandom;
321import java.security.cert.Certificate;
322import java.security.cert.CertificateEncodingException;
323import java.security.cert.CertificateException;
324import java.text.SimpleDateFormat;
325import java.util.ArrayList;
326import java.util.Arrays;
327import java.util.Collection;
328import java.util.Collections;
329import java.util.Comparator;
330import java.util.Date;
331import java.util.HashMap;
332import java.util.HashSet;
333import java.util.Iterator;
334import java.util.List;
335import java.util.Map;
336import java.util.Objects;
337import java.util.Set;
338import java.util.concurrent.CountDownLatch;
339import java.util.concurrent.Future;
340import java.util.concurrent.TimeUnit;
341import java.util.concurrent.atomic.AtomicBoolean;
342import java.util.concurrent.atomic.AtomicInteger;
343
344/**
345 * Keep track of all those APKs everywhere.
346 * <p>
347 * Internally there are two important locks:
348 * <ul>
349 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
350 * and other related state. It is a fine-grained lock that should only be held
351 * momentarily, as it's one of the most contended locks in the system.
352 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
353 * operations typically involve heavy lifting of application data on disk. Since
354 * {@code installd} is single-threaded, and it's operations can often be slow,
355 * this lock should never be acquired while already holding {@link #mPackages}.
356 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
357 * holding {@link #mInstallLock}.
358 * </ul>
359 * Many internal methods rely on the caller to hold the appropriate locks, and
360 * this contract is expressed through method name suffixes:
361 * <ul>
362 * <li>fooLI(): the caller must hold {@link #mInstallLock}
363 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
364 * being modified must be frozen
365 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
366 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
367 * </ul>
368 * <p>
369 * Because this class is very central to the platform's security; please run all
370 * CTS and unit tests whenever making modifications:
371 *
372 * <pre>
373 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
374 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
375 * </pre>
376 */
377public class PackageManagerService extends IPackageManager.Stub
378        implements PackageSender {
379    static final String TAG = "PackageManager";
380    static final boolean DEBUG_SETTINGS = false;
381    static final boolean DEBUG_PREFERRED = false;
382    static final boolean DEBUG_UPGRADE = false;
383    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
384    private static final boolean DEBUG_BACKUP = false;
385    private static final boolean DEBUG_INSTALL = false;
386    private static final boolean DEBUG_REMOVE = false;
387    private static final boolean DEBUG_BROADCASTS = false;
388    private static final boolean DEBUG_SHOW_INFO = false;
389    private static final boolean DEBUG_PACKAGE_INFO = false;
390    private static final boolean DEBUG_INTENT_MATCHING = false;
391    private static final boolean DEBUG_PACKAGE_SCANNING = false;
392    private static final boolean DEBUG_VERIFY = false;
393    private static final boolean DEBUG_FILTERS = false;
394    private static final boolean DEBUG_PERMISSIONS = false;
395    private static final boolean DEBUG_SHARED_LIBRARIES = false;
396
397    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
398    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
399    // user, but by default initialize to this.
400    public static final boolean DEBUG_DEXOPT = false;
401
402    private static final boolean DEBUG_ABI_SELECTION = false;
403    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
404    private static final boolean DEBUG_TRIAGED_MISSING = false;
405    private static final boolean DEBUG_APP_DATA = false;
406
407    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
408    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
409
410    private static final boolean HIDE_EPHEMERAL_APIS = false;
411
412    private static final boolean ENABLE_FREE_CACHE_V2 =
413            SystemProperties.getBoolean("fw.free_cache_v2", true);
414
415    private static final int RADIO_UID = Process.PHONE_UID;
416    private static final int LOG_UID = Process.LOG_UID;
417    private static final int NFC_UID = Process.NFC_UID;
418    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
419    private static final int SHELL_UID = Process.SHELL_UID;
420
421    // Cap the size of permission trees that 3rd party apps can define
422    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
423
424    // Suffix used during package installation when copying/moving
425    // package apks to install directory.
426    private static final String INSTALL_PACKAGE_SUFFIX = "-";
427
428    static final int SCAN_NO_DEX = 1<<1;
429    static final int SCAN_FORCE_DEX = 1<<2;
430    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
431    static final int SCAN_NEW_INSTALL = 1<<4;
432    static final int SCAN_UPDATE_TIME = 1<<5;
433    static final int SCAN_BOOTING = 1<<6;
434    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
435    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
436    static final int SCAN_REPLACING = 1<<9;
437    static final int SCAN_REQUIRE_KNOWN = 1<<10;
438    static final int SCAN_MOVE = 1<<11;
439    static final int SCAN_INITIAL = 1<<12;
440    static final int SCAN_CHECK_ONLY = 1<<13;
441    static final int SCAN_DONT_KILL_APP = 1<<14;
442    static final int SCAN_IGNORE_FROZEN = 1<<15;
443    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
444    static final int SCAN_AS_INSTANT_APP = 1<<17;
445    static final int SCAN_AS_FULL_APP = 1<<18;
446    /** Should not be with the scan flags */
447    static final int FLAGS_REMOVE_CHATTY = 1<<31;
448
449    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
450
451    private static final int[] EMPTY_INT_ARRAY = new int[0];
452
453    private static final int TYPE_UNKNOWN = 0;
454    private static final int TYPE_ACTIVITY = 1;
455    private static final int TYPE_RECEIVER = 2;
456    private static final int TYPE_SERVICE = 3;
457    private static final int TYPE_PROVIDER = 4;
458    @IntDef(prefix = { "TYPE_" }, value = {
459            TYPE_UNKNOWN,
460            TYPE_ACTIVITY,
461            TYPE_RECEIVER,
462            TYPE_SERVICE,
463            TYPE_PROVIDER,
464    })
465    @Retention(RetentionPolicy.SOURCE)
466    public @interface ComponentType {}
467
468    /**
469     * Timeout (in milliseconds) after which the watchdog should declare that
470     * our handler thread is wedged.  The usual default for such things is one
471     * minute but we sometimes do very lengthy I/O operations on this thread,
472     * such as installing multi-gigabyte applications, so ours needs to be longer.
473     */
474    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
475
476    /**
477     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
478     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
479     * settings entry if available, otherwise we use the hardcoded default.  If it's been
480     * more than this long since the last fstrim, we force one during the boot sequence.
481     *
482     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
483     * one gets run at the next available charging+idle time.  This final mandatory
484     * no-fstrim check kicks in only of the other scheduling criteria is never met.
485     */
486    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
487
488    /**
489     * Whether verification is enabled by default.
490     */
491    private static final boolean DEFAULT_VERIFY_ENABLE = true;
492
493    /**
494     * The default maximum time to wait for the verification agent to return in
495     * milliseconds.
496     */
497    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
498
499    /**
500     * The default response for package verification timeout.
501     *
502     * This can be either PackageManager.VERIFICATION_ALLOW or
503     * PackageManager.VERIFICATION_REJECT.
504     */
505    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
506
507    static final String PLATFORM_PACKAGE_NAME = "android";
508
509    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
510
511    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
512            DEFAULT_CONTAINER_PACKAGE,
513            "com.android.defcontainer.DefaultContainerService");
514
515    private static final String KILL_APP_REASON_GIDS_CHANGED =
516            "permission grant or revoke changed gids";
517
518    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
519            "permissions revoked";
520
521    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
522
523    private static final String PACKAGE_SCHEME = "package";
524
525    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
526
527    /** Permission grant: not grant the permission. */
528    private static final int GRANT_DENIED = 1;
529
530    /** Permission grant: grant the permission as an install permission. */
531    private static final int GRANT_INSTALL = 2;
532
533    /** Permission grant: grant the permission as a runtime one. */
534    private static final int GRANT_RUNTIME = 3;
535
536    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
537    private static final int GRANT_UPGRADE = 4;
538
539    /** Canonical intent used to identify what counts as a "web browser" app */
540    private static final Intent sBrowserIntent;
541    static {
542        sBrowserIntent = new Intent();
543        sBrowserIntent.setAction(Intent.ACTION_VIEW);
544        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
545        sBrowserIntent.setData(Uri.parse("http:"));
546    }
547
548    /**
549     * The set of all protected actions [i.e. those actions for which a high priority
550     * intent filter is disallowed].
551     */
552    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
553    static {
554        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
555        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
556        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
557        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
558    }
559
560    // Compilation reasons.
561    public static final int REASON_FIRST_BOOT = 0;
562    public static final int REASON_BOOT = 1;
563    public static final int REASON_INSTALL = 2;
564    public static final int REASON_BACKGROUND_DEXOPT = 3;
565    public static final int REASON_AB_OTA = 4;
566    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
567
568    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
569
570    /** All dangerous permission names in the same order as the events in MetricsEvent */
571    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
572            Manifest.permission.READ_CALENDAR,
573            Manifest.permission.WRITE_CALENDAR,
574            Manifest.permission.CAMERA,
575            Manifest.permission.READ_CONTACTS,
576            Manifest.permission.WRITE_CONTACTS,
577            Manifest.permission.GET_ACCOUNTS,
578            Manifest.permission.ACCESS_FINE_LOCATION,
579            Manifest.permission.ACCESS_COARSE_LOCATION,
580            Manifest.permission.RECORD_AUDIO,
581            Manifest.permission.READ_PHONE_STATE,
582            Manifest.permission.CALL_PHONE,
583            Manifest.permission.READ_CALL_LOG,
584            Manifest.permission.WRITE_CALL_LOG,
585            Manifest.permission.ADD_VOICEMAIL,
586            Manifest.permission.USE_SIP,
587            Manifest.permission.PROCESS_OUTGOING_CALLS,
588            Manifest.permission.READ_CELL_BROADCASTS,
589            Manifest.permission.BODY_SENSORS,
590            Manifest.permission.SEND_SMS,
591            Manifest.permission.RECEIVE_SMS,
592            Manifest.permission.READ_SMS,
593            Manifest.permission.RECEIVE_WAP_PUSH,
594            Manifest.permission.RECEIVE_MMS,
595            Manifest.permission.READ_EXTERNAL_STORAGE,
596            Manifest.permission.WRITE_EXTERNAL_STORAGE,
597            Manifest.permission.READ_PHONE_NUMBERS,
598            Manifest.permission.ANSWER_PHONE_CALLS);
599
600
601    /**
602     * Version number for the package parser cache. Increment this whenever the format or
603     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
604     */
605    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
606
607    /**
608     * Whether the package parser cache is enabled.
609     */
610    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
611
612    final ServiceThread mHandlerThread;
613
614    final PackageHandler mHandler;
615
616    private final ProcessLoggingHandler mProcessLoggingHandler;
617
618    /**
619     * Messages for {@link #mHandler} that need to wait for system ready before
620     * being dispatched.
621     */
622    private ArrayList<Message> mPostSystemReadyMessages;
623
624    final int mSdkVersion = Build.VERSION.SDK_INT;
625
626    final Context mContext;
627    final boolean mFactoryTest;
628    final boolean mOnlyCore;
629    final DisplayMetrics mMetrics;
630    final int mDefParseFlags;
631    final String[] mSeparateProcesses;
632    final boolean mIsUpgrade;
633    final boolean mIsPreNUpgrade;
634    final boolean mIsPreNMR1Upgrade;
635
636    // Have we told the Activity Manager to whitelist the default container service by uid yet?
637    @GuardedBy("mPackages")
638    boolean mDefaultContainerWhitelisted = false;
639
640    @GuardedBy("mPackages")
641    private boolean mDexOptDialogShown;
642
643    /** The location for ASEC container files on internal storage. */
644    final String mAsecInternalPath;
645
646    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
647    // LOCK HELD.  Can be called with mInstallLock held.
648    @GuardedBy("mInstallLock")
649    final Installer mInstaller;
650
651    /** Directory where installed third-party apps stored */
652    final File mAppInstallDir;
653
654    /**
655     * Directory to which applications installed internally have their
656     * 32 bit native libraries copied.
657     */
658    private File mAppLib32InstallDir;
659
660    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
661    // apps.
662    final File mDrmAppPrivateInstallDir;
663
664    // ----------------------------------------------------------------
665
666    // Lock for state used when installing and doing other long running
667    // operations.  Methods that must be called with this lock held have
668    // the suffix "LI".
669    final Object mInstallLock = new Object();
670
671    // ----------------------------------------------------------------
672
673    // Keys are String (package name), values are Package.  This also serves
674    // as the lock for the global state.  Methods that must be called with
675    // this lock held have the prefix "LP".
676    @GuardedBy("mPackages")
677    final ArrayMap<String, PackageParser.Package> mPackages =
678            new ArrayMap<String, PackageParser.Package>();
679
680    final ArrayMap<String, Set<String>> mKnownCodebase =
681            new ArrayMap<String, Set<String>>();
682
683    // Keys are isolated uids and values are the uid of the application
684    // that created the isolated proccess.
685    @GuardedBy("mPackages")
686    final SparseIntArray mIsolatedOwners = new SparseIntArray();
687
688    /**
689     * Tracks new system packages [received in an OTA] that we expect to
690     * find updated user-installed versions. Keys are package name, values
691     * are package location.
692     */
693    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
694    /**
695     * Tracks high priority intent filters for protected actions. During boot, certain
696     * filter actions are protected and should never be allowed to have a high priority
697     * intent filter for them. However, there is one, and only one exception -- the
698     * setup wizard. It must be able to define a high priority intent filter for these
699     * actions to ensure there are no escapes from the wizard. We need to delay processing
700     * of these during boot as we need to look at all of the system packages in order
701     * to know which component is the setup wizard.
702     */
703    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
704    /**
705     * Whether or not processing protected filters should be deferred.
706     */
707    private boolean mDeferProtectedFilters = true;
708
709    /**
710     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
711     */
712    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
713    /**
714     * Whether or not system app permissions should be promoted from install to runtime.
715     */
716    boolean mPromoteSystemApps;
717
718    @GuardedBy("mPackages")
719    final Settings mSettings;
720
721    /**
722     * Set of package names that are currently "frozen", which means active
723     * surgery is being done on the code/data for that package. The platform
724     * will refuse to launch frozen packages to avoid race conditions.
725     *
726     * @see PackageFreezer
727     */
728    @GuardedBy("mPackages")
729    final ArraySet<String> mFrozenPackages = new ArraySet<>();
730
731    final ProtectedPackages mProtectedPackages;
732
733    @GuardedBy("mLoadedVolumes")
734    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
735
736    boolean mFirstBoot;
737
738    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
739
740    // System configuration read by SystemConfig.
741    final int[] mGlobalGids;
742    final SparseArray<ArraySet<String>> mSystemPermissions;
743    @GuardedBy("mAvailableFeatures")
744    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
745
746    // If mac_permissions.xml was found for seinfo labeling.
747    boolean mFoundPolicyFile;
748
749    private final InstantAppRegistry mInstantAppRegistry;
750
751    @GuardedBy("mPackages")
752    int mChangedPackagesSequenceNumber;
753    /**
754     * List of changed [installed, removed or updated] packages.
755     * mapping from user id -> sequence number -> package name
756     */
757    @GuardedBy("mPackages")
758    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
759    /**
760     * The sequence number of the last change to a package.
761     * mapping from user id -> package name -> sequence number
762     */
763    @GuardedBy("mPackages")
764    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
765
766    class PackageParserCallback implements PackageParser.Callback {
767        @Override public final boolean hasFeature(String feature) {
768            return PackageManagerService.this.hasSystemFeature(feature, 0);
769        }
770
771        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
772                Collection<PackageParser.Package> allPackages, String targetPackageName) {
773            List<PackageParser.Package> overlayPackages = null;
774            for (PackageParser.Package p : allPackages) {
775                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
776                    if (overlayPackages == null) {
777                        overlayPackages = new ArrayList<PackageParser.Package>();
778                    }
779                    overlayPackages.add(p);
780                }
781            }
782            if (overlayPackages != null) {
783                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
784                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
785                        return p1.mOverlayPriority - p2.mOverlayPriority;
786                    }
787                };
788                Collections.sort(overlayPackages, cmp);
789            }
790            return overlayPackages;
791        }
792
793        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
794                String targetPackageName, String targetPath) {
795            if ("android".equals(targetPackageName)) {
796                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
797                // native AssetManager.
798                return null;
799            }
800            List<PackageParser.Package> overlayPackages =
801                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
802            if (overlayPackages == null || overlayPackages.isEmpty()) {
803                return null;
804            }
805            List<String> overlayPathList = null;
806            for (PackageParser.Package overlayPackage : overlayPackages) {
807                if (targetPath == null) {
808                    if (overlayPathList == null) {
809                        overlayPathList = new ArrayList<String>();
810                    }
811                    overlayPathList.add(overlayPackage.baseCodePath);
812                    continue;
813                }
814
815                try {
816                    // Creates idmaps for system to parse correctly the Android manifest of the
817                    // target package.
818                    //
819                    // OverlayManagerService will update each of them with a correct gid from its
820                    // target package app id.
821                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
822                            UserHandle.getSharedAppGid(
823                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
824                    if (overlayPathList == null) {
825                        overlayPathList = new ArrayList<String>();
826                    }
827                    overlayPathList.add(overlayPackage.baseCodePath);
828                } catch (InstallerException e) {
829                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
830                            overlayPackage.baseCodePath);
831                }
832            }
833            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
834        }
835
836        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
837            synchronized (mPackages) {
838                return getStaticOverlayPathsLocked(
839                        mPackages.values(), targetPackageName, targetPath);
840            }
841        }
842
843        @Override public final String[] getOverlayApks(String targetPackageName) {
844            return getStaticOverlayPaths(targetPackageName, null);
845        }
846
847        @Override public final String[] getOverlayPaths(String targetPackageName,
848                String targetPath) {
849            return getStaticOverlayPaths(targetPackageName, targetPath);
850        }
851    };
852
853    class ParallelPackageParserCallback extends PackageParserCallback {
854        List<PackageParser.Package> mOverlayPackages = null;
855
856        void findStaticOverlayPackages() {
857            synchronized (mPackages) {
858                for (PackageParser.Package p : mPackages.values()) {
859                    if (p.mIsStaticOverlay) {
860                        if (mOverlayPackages == null) {
861                            mOverlayPackages = new ArrayList<PackageParser.Package>();
862                        }
863                        mOverlayPackages.add(p);
864                    }
865                }
866            }
867        }
868
869        @Override
870        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
871            // We can trust mOverlayPackages without holding mPackages because package uninstall
872            // can't happen while running parallel parsing.
873            // Moreover holding mPackages on each parsing thread causes dead-lock.
874            return mOverlayPackages == null ? null :
875                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
876        }
877    }
878
879    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
880    final ParallelPackageParserCallback mParallelPackageParserCallback =
881            new ParallelPackageParserCallback();
882
883    public static final class SharedLibraryEntry {
884        public final @Nullable String path;
885        public final @Nullable String apk;
886        public final @NonNull SharedLibraryInfo info;
887
888        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
889                String declaringPackageName, int declaringPackageVersionCode) {
890            path = _path;
891            apk = _apk;
892            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
893                    declaringPackageName, declaringPackageVersionCode), null);
894        }
895    }
896
897    // Currently known shared libraries.
898    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
899    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
900            new ArrayMap<>();
901
902    // All available activities, for your resolving pleasure.
903    final ActivityIntentResolver mActivities =
904            new ActivityIntentResolver();
905
906    // All available receivers, for your resolving pleasure.
907    final ActivityIntentResolver mReceivers =
908            new ActivityIntentResolver();
909
910    // All available services, for your resolving pleasure.
911    final ServiceIntentResolver mServices = new ServiceIntentResolver();
912
913    // All available providers, for your resolving pleasure.
914    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
915
916    // Mapping from provider base names (first directory in content URI codePath)
917    // to the provider information.
918    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
919            new ArrayMap<String, PackageParser.Provider>();
920
921    // Mapping from instrumentation class names to info about them.
922    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
923            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
924
925    // Mapping from permission names to info about them.
926    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
927            new ArrayMap<String, PackageParser.PermissionGroup>();
928
929    // Packages whose data we have transfered into another package, thus
930    // should no longer exist.
931    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
932
933    // Broadcast actions that are only available to the system.
934    @GuardedBy("mProtectedBroadcasts")
935    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
936
937    /** List of packages waiting for verification. */
938    final SparseArray<PackageVerificationState> mPendingVerification
939            = new SparseArray<PackageVerificationState>();
940
941    /** Set of packages associated with each app op permission. */
942    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
943
944    final PackageInstallerService mInstallerService;
945
946    private final PackageDexOptimizer mPackageDexOptimizer;
947    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
948    // is used by other apps).
949    private final DexManager mDexManager;
950
951    private AtomicInteger mNextMoveId = new AtomicInteger();
952    private final MoveCallbacks mMoveCallbacks;
953
954    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
955
956    // Cache of users who need badging.
957    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
958
959    /** Token for keys in mPendingVerification. */
960    private int mPendingVerificationToken = 0;
961
962    volatile boolean mSystemReady;
963    volatile boolean mSafeMode;
964    volatile boolean mHasSystemUidErrors;
965    private volatile boolean mEphemeralAppsDisabled;
966
967    ApplicationInfo mAndroidApplication;
968    final ActivityInfo mResolveActivity = new ActivityInfo();
969    final ResolveInfo mResolveInfo = new ResolveInfo();
970    ComponentName mResolveComponentName;
971    PackageParser.Package mPlatformPackage;
972    ComponentName mCustomResolverComponentName;
973
974    boolean mResolverReplaced = false;
975
976    private final @Nullable ComponentName mIntentFilterVerifierComponent;
977    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
978
979    private int mIntentFilterVerificationToken = 0;
980
981    /** The service connection to the ephemeral resolver */
982    final EphemeralResolverConnection mInstantAppResolverConnection;
983    /** Component used to show resolver settings for Instant Apps */
984    final ComponentName mInstantAppResolverSettingsComponent;
985
986    /** Activity used to install instant applications */
987    ActivityInfo mInstantAppInstallerActivity;
988    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
989
990    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
991            = new SparseArray<IntentFilterVerificationState>();
992
993    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
994
995    // List of packages names to keep cached, even if they are uninstalled for all users
996    private List<String> mKeepUninstalledPackages;
997
998    private UserManagerInternal mUserManagerInternal;
999
1000    private DeviceIdleController.LocalService mDeviceIdleController;
1001
1002    private File mCacheDir;
1003
1004    private ArraySet<String> mPrivappPermissionsViolations;
1005
1006    private Future<?> mPrepareAppDataFuture;
1007
1008    private static class IFVerificationParams {
1009        PackageParser.Package pkg;
1010        boolean replacing;
1011        int userId;
1012        int verifierUid;
1013
1014        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1015                int _userId, int _verifierUid) {
1016            pkg = _pkg;
1017            replacing = _replacing;
1018            userId = _userId;
1019            replacing = _replacing;
1020            verifierUid = _verifierUid;
1021        }
1022    }
1023
1024    private interface IntentFilterVerifier<T extends IntentFilter> {
1025        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1026                                               T filter, String packageName);
1027        void startVerifications(int userId);
1028        void receiveVerificationResponse(int verificationId);
1029    }
1030
1031    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1032        private Context mContext;
1033        private ComponentName mIntentFilterVerifierComponent;
1034        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1035
1036        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1037            mContext = context;
1038            mIntentFilterVerifierComponent = verifierComponent;
1039        }
1040
1041        private String getDefaultScheme() {
1042            return IntentFilter.SCHEME_HTTPS;
1043        }
1044
1045        @Override
1046        public void startVerifications(int userId) {
1047            // Launch verifications requests
1048            int count = mCurrentIntentFilterVerifications.size();
1049            for (int n=0; n<count; n++) {
1050                int verificationId = mCurrentIntentFilterVerifications.get(n);
1051                final IntentFilterVerificationState ivs =
1052                        mIntentFilterVerificationStates.get(verificationId);
1053
1054                String packageName = ivs.getPackageName();
1055
1056                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1057                final int filterCount = filters.size();
1058                ArraySet<String> domainsSet = new ArraySet<>();
1059                for (int m=0; m<filterCount; m++) {
1060                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1061                    domainsSet.addAll(filter.getHostsList());
1062                }
1063                synchronized (mPackages) {
1064                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1065                            packageName, domainsSet) != null) {
1066                        scheduleWriteSettingsLocked();
1067                    }
1068                }
1069                sendVerificationRequest(verificationId, ivs);
1070            }
1071            mCurrentIntentFilterVerifications.clear();
1072        }
1073
1074        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1075            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1076            verificationIntent.putExtra(
1077                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1078                    verificationId);
1079            verificationIntent.putExtra(
1080                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1081                    getDefaultScheme());
1082            verificationIntent.putExtra(
1083                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1084                    ivs.getHostsString());
1085            verificationIntent.putExtra(
1086                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1087                    ivs.getPackageName());
1088            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1089            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1090
1091            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1092            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1093                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1094                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1095
1096            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1097            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1098                    "Sending IntentFilter verification broadcast");
1099        }
1100
1101        public void receiveVerificationResponse(int verificationId) {
1102            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1103
1104            final boolean verified = ivs.isVerified();
1105
1106            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1107            final int count = filters.size();
1108            if (DEBUG_DOMAIN_VERIFICATION) {
1109                Slog.i(TAG, "Received verification response " + verificationId
1110                        + " for " + count + " filters, verified=" + verified);
1111            }
1112            for (int n=0; n<count; n++) {
1113                PackageParser.ActivityIntentInfo filter = filters.get(n);
1114                filter.setVerified(verified);
1115
1116                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1117                        + " verified with result:" + verified + " and hosts:"
1118                        + ivs.getHostsString());
1119            }
1120
1121            mIntentFilterVerificationStates.remove(verificationId);
1122
1123            final String packageName = ivs.getPackageName();
1124            IntentFilterVerificationInfo ivi = null;
1125
1126            synchronized (mPackages) {
1127                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1128            }
1129            if (ivi == null) {
1130                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1131                        + verificationId + " packageName:" + packageName);
1132                return;
1133            }
1134            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1135                    "Updating IntentFilterVerificationInfo for package " + packageName
1136                            +" verificationId:" + verificationId);
1137
1138            synchronized (mPackages) {
1139                if (verified) {
1140                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1141                } else {
1142                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1143                }
1144                scheduleWriteSettingsLocked();
1145
1146                final int userId = ivs.getUserId();
1147                if (userId != UserHandle.USER_ALL) {
1148                    final int userStatus =
1149                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1150
1151                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1152                    boolean needUpdate = false;
1153
1154                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1155                    // already been set by the User thru the Disambiguation dialog
1156                    switch (userStatus) {
1157                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1158                            if (verified) {
1159                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1160                            } else {
1161                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1162                            }
1163                            needUpdate = true;
1164                            break;
1165
1166                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1167                            if (verified) {
1168                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1169                                needUpdate = true;
1170                            }
1171                            break;
1172
1173                        default:
1174                            // Nothing to do
1175                    }
1176
1177                    if (needUpdate) {
1178                        mSettings.updateIntentFilterVerificationStatusLPw(
1179                                packageName, updatedStatus, userId);
1180                        scheduleWritePackageRestrictionsLocked(userId);
1181                    }
1182                }
1183            }
1184        }
1185
1186        @Override
1187        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1188                    ActivityIntentInfo filter, String packageName) {
1189            if (!hasValidDomains(filter)) {
1190                return false;
1191            }
1192            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1193            if (ivs == null) {
1194                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1195                        packageName);
1196            }
1197            if (DEBUG_DOMAIN_VERIFICATION) {
1198                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1199            }
1200            ivs.addFilter(filter);
1201            return true;
1202        }
1203
1204        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1205                int userId, int verificationId, String packageName) {
1206            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1207                    verifierUid, userId, packageName);
1208            ivs.setPendingState();
1209            synchronized (mPackages) {
1210                mIntentFilterVerificationStates.append(verificationId, ivs);
1211                mCurrentIntentFilterVerifications.add(verificationId);
1212            }
1213            return ivs;
1214        }
1215    }
1216
1217    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1218        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1219                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1220                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1221    }
1222
1223    // Set of pending broadcasts for aggregating enable/disable of components.
1224    static class PendingPackageBroadcasts {
1225        // for each user id, a map of <package name -> components within that package>
1226        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1227
1228        public PendingPackageBroadcasts() {
1229            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1230        }
1231
1232        public ArrayList<String> get(int userId, String packageName) {
1233            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1234            return packages.get(packageName);
1235        }
1236
1237        public void put(int userId, String packageName, ArrayList<String> components) {
1238            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1239            packages.put(packageName, components);
1240        }
1241
1242        public void remove(int userId, String packageName) {
1243            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1244            if (packages != null) {
1245                packages.remove(packageName);
1246            }
1247        }
1248
1249        public void remove(int userId) {
1250            mUidMap.remove(userId);
1251        }
1252
1253        public int userIdCount() {
1254            return mUidMap.size();
1255        }
1256
1257        public int userIdAt(int n) {
1258            return mUidMap.keyAt(n);
1259        }
1260
1261        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1262            return mUidMap.get(userId);
1263        }
1264
1265        public int size() {
1266            // total number of pending broadcast entries across all userIds
1267            int num = 0;
1268            for (int i = 0; i< mUidMap.size(); i++) {
1269                num += mUidMap.valueAt(i).size();
1270            }
1271            return num;
1272        }
1273
1274        public void clear() {
1275            mUidMap.clear();
1276        }
1277
1278        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1279            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1280            if (map == null) {
1281                map = new ArrayMap<String, ArrayList<String>>();
1282                mUidMap.put(userId, map);
1283            }
1284            return map;
1285        }
1286    }
1287    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1288
1289    // Service Connection to remote media container service to copy
1290    // package uri's from external media onto secure containers
1291    // or internal storage.
1292    private IMediaContainerService mContainerService = null;
1293
1294    static final int SEND_PENDING_BROADCAST = 1;
1295    static final int MCS_BOUND = 3;
1296    static final int END_COPY = 4;
1297    static final int INIT_COPY = 5;
1298    static final int MCS_UNBIND = 6;
1299    static final int START_CLEANING_PACKAGE = 7;
1300    static final int FIND_INSTALL_LOC = 8;
1301    static final int POST_INSTALL = 9;
1302    static final int MCS_RECONNECT = 10;
1303    static final int MCS_GIVE_UP = 11;
1304    static final int UPDATED_MEDIA_STATUS = 12;
1305    static final int WRITE_SETTINGS = 13;
1306    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1307    static final int PACKAGE_VERIFIED = 15;
1308    static final int CHECK_PENDING_VERIFICATION = 16;
1309    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1310    static final int INTENT_FILTER_VERIFIED = 18;
1311    static final int WRITE_PACKAGE_LIST = 19;
1312    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1313
1314    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1315
1316    // Delay time in millisecs
1317    static final int BROADCAST_DELAY = 10 * 1000;
1318
1319    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1320            2 * 60 * 60 * 1000L; /* two hours */
1321
1322    static UserManagerService sUserManager;
1323
1324    // Stores a list of users whose package restrictions file needs to be updated
1325    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1326
1327    final private DefaultContainerConnection mDefContainerConn =
1328            new DefaultContainerConnection();
1329    class DefaultContainerConnection implements ServiceConnection {
1330        public void onServiceConnected(ComponentName name, IBinder service) {
1331            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1332            final IMediaContainerService imcs = IMediaContainerService.Stub
1333                    .asInterface(Binder.allowBlocking(service));
1334            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1335        }
1336
1337        public void onServiceDisconnected(ComponentName name) {
1338            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1339        }
1340    }
1341
1342    // Recordkeeping of restore-after-install operations that are currently in flight
1343    // between the Package Manager and the Backup Manager
1344    static class PostInstallData {
1345        public InstallArgs args;
1346        public PackageInstalledInfo res;
1347
1348        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1349            args = _a;
1350            res = _r;
1351        }
1352    }
1353
1354    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1355    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1356
1357    // XML tags for backup/restore of various bits of state
1358    private static final String TAG_PREFERRED_BACKUP = "pa";
1359    private static final String TAG_DEFAULT_APPS = "da";
1360    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1361
1362    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1363    private static final String TAG_ALL_GRANTS = "rt-grants";
1364    private static final String TAG_GRANT = "grant";
1365    private static final String ATTR_PACKAGE_NAME = "pkg";
1366
1367    private static final String TAG_PERMISSION = "perm";
1368    private static final String ATTR_PERMISSION_NAME = "name";
1369    private static final String ATTR_IS_GRANTED = "g";
1370    private static final String ATTR_USER_SET = "set";
1371    private static final String ATTR_USER_FIXED = "fixed";
1372    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1373
1374    // System/policy permission grants are not backed up
1375    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1376            FLAG_PERMISSION_POLICY_FIXED
1377            | FLAG_PERMISSION_SYSTEM_FIXED
1378            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1379
1380    // And we back up these user-adjusted states
1381    private static final int USER_RUNTIME_GRANT_MASK =
1382            FLAG_PERMISSION_USER_SET
1383            | FLAG_PERMISSION_USER_FIXED
1384            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1385
1386    final @Nullable String mRequiredVerifierPackage;
1387    final @NonNull String mRequiredInstallerPackage;
1388    final @NonNull String mRequiredUninstallerPackage;
1389    final @Nullable String mSetupWizardPackage;
1390    final @Nullable String mStorageManagerPackage;
1391    final @NonNull String mServicesSystemSharedLibraryPackageName;
1392    final @NonNull String mSharedSystemSharedLibraryPackageName;
1393
1394    final boolean mPermissionReviewRequired;
1395
1396    private final PackageUsage mPackageUsage = new PackageUsage();
1397    private final CompilerStats mCompilerStats = new CompilerStats();
1398
1399    class PackageHandler extends Handler {
1400        private boolean mBound = false;
1401        final ArrayList<HandlerParams> mPendingInstalls =
1402            new ArrayList<HandlerParams>();
1403
1404        private boolean connectToService() {
1405            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1406                    " DefaultContainerService");
1407            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1408            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1409            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1410                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1411                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1412                mBound = true;
1413                return true;
1414            }
1415            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1416            return false;
1417        }
1418
1419        private void disconnectService() {
1420            mContainerService = null;
1421            mBound = false;
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1423            mContext.unbindService(mDefContainerConn);
1424            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1425        }
1426
1427        PackageHandler(Looper looper) {
1428            super(looper);
1429        }
1430
1431        public void handleMessage(Message msg) {
1432            try {
1433                doHandleMessage(msg);
1434            } finally {
1435                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1436            }
1437        }
1438
1439        void doHandleMessage(Message msg) {
1440            switch (msg.what) {
1441                case INIT_COPY: {
1442                    HandlerParams params = (HandlerParams) msg.obj;
1443                    int idx = mPendingInstalls.size();
1444                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1445                    // If a bind was already initiated we dont really
1446                    // need to do anything. The pending install
1447                    // will be processed later on.
1448                    if (!mBound) {
1449                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1450                                System.identityHashCode(mHandler));
1451                        // If this is the only one pending we might
1452                        // have to bind to the service again.
1453                        if (!connectToService()) {
1454                            Slog.e(TAG, "Failed to bind to media container service");
1455                            params.serviceError();
1456                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1457                                    System.identityHashCode(mHandler));
1458                            if (params.traceMethod != null) {
1459                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1460                                        params.traceCookie);
1461                            }
1462                            return;
1463                        } else {
1464                            // Once we bind to the service, the first
1465                            // pending request will be processed.
1466                            mPendingInstalls.add(idx, params);
1467                        }
1468                    } else {
1469                        mPendingInstalls.add(idx, params);
1470                        // Already bound to the service. Just make
1471                        // sure we trigger off processing the first request.
1472                        if (idx == 0) {
1473                            mHandler.sendEmptyMessage(MCS_BOUND);
1474                        }
1475                    }
1476                    break;
1477                }
1478                case MCS_BOUND: {
1479                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1480                    if (msg.obj != null) {
1481                        mContainerService = (IMediaContainerService) msg.obj;
1482                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1483                                System.identityHashCode(mHandler));
1484                    }
1485                    if (mContainerService == null) {
1486                        if (!mBound) {
1487                            // Something seriously wrong since we are not bound and we are not
1488                            // waiting for connection. Bail out.
1489                            Slog.e(TAG, "Cannot bind to media container service");
1490                            for (HandlerParams params : mPendingInstalls) {
1491                                // Indicate service bind error
1492                                params.serviceError();
1493                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1494                                        System.identityHashCode(params));
1495                                if (params.traceMethod != null) {
1496                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1497                                            params.traceMethod, params.traceCookie);
1498                                }
1499                                return;
1500                            }
1501                            mPendingInstalls.clear();
1502                        } else {
1503                            Slog.w(TAG, "Waiting to connect to media container service");
1504                        }
1505                    } else if (mPendingInstalls.size() > 0) {
1506                        HandlerParams params = mPendingInstalls.get(0);
1507                        if (params != null) {
1508                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1509                                    System.identityHashCode(params));
1510                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1511                            if (params.startCopy()) {
1512                                // We are done...  look for more work or to
1513                                // go idle.
1514                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1515                                        "Checking for more work or unbind...");
1516                                // Delete pending install
1517                                if (mPendingInstalls.size() > 0) {
1518                                    mPendingInstalls.remove(0);
1519                                }
1520                                if (mPendingInstalls.size() == 0) {
1521                                    if (mBound) {
1522                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1523                                                "Posting delayed MCS_UNBIND");
1524                                        removeMessages(MCS_UNBIND);
1525                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1526                                        // Unbind after a little delay, to avoid
1527                                        // continual thrashing.
1528                                        sendMessageDelayed(ubmsg, 10000);
1529                                    }
1530                                } else {
1531                                    // There are more pending requests in queue.
1532                                    // Just post MCS_BOUND message to trigger processing
1533                                    // of next pending install.
1534                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1535                                            "Posting MCS_BOUND for next work");
1536                                    mHandler.sendEmptyMessage(MCS_BOUND);
1537                                }
1538                            }
1539                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1540                        }
1541                    } else {
1542                        // Should never happen ideally.
1543                        Slog.w(TAG, "Empty queue");
1544                    }
1545                    break;
1546                }
1547                case MCS_RECONNECT: {
1548                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1549                    if (mPendingInstalls.size() > 0) {
1550                        if (mBound) {
1551                            disconnectService();
1552                        }
1553                        if (!connectToService()) {
1554                            Slog.e(TAG, "Failed to bind to media container service");
1555                            for (HandlerParams params : mPendingInstalls) {
1556                                // Indicate service bind error
1557                                params.serviceError();
1558                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1559                                        System.identityHashCode(params));
1560                            }
1561                            mPendingInstalls.clear();
1562                        }
1563                    }
1564                    break;
1565                }
1566                case MCS_UNBIND: {
1567                    // If there is no actual work left, then time to unbind.
1568                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1569
1570                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1571                        if (mBound) {
1572                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1573
1574                            disconnectService();
1575                        }
1576                    } else if (mPendingInstalls.size() > 0) {
1577                        // There are more pending requests in queue.
1578                        // Just post MCS_BOUND message to trigger processing
1579                        // of next pending install.
1580                        mHandler.sendEmptyMessage(MCS_BOUND);
1581                    }
1582
1583                    break;
1584                }
1585                case MCS_GIVE_UP: {
1586                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1587                    HandlerParams params = mPendingInstalls.remove(0);
1588                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1589                            System.identityHashCode(params));
1590                    break;
1591                }
1592                case SEND_PENDING_BROADCAST: {
1593                    String packages[];
1594                    ArrayList<String> components[];
1595                    int size = 0;
1596                    int uids[];
1597                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1598                    synchronized (mPackages) {
1599                        if (mPendingBroadcasts == null) {
1600                            return;
1601                        }
1602                        size = mPendingBroadcasts.size();
1603                        if (size <= 0) {
1604                            // Nothing to be done. Just return
1605                            return;
1606                        }
1607                        packages = new String[size];
1608                        components = new ArrayList[size];
1609                        uids = new int[size];
1610                        int i = 0;  // filling out the above arrays
1611
1612                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1613                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1614                            Iterator<Map.Entry<String, ArrayList<String>>> it
1615                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1616                                            .entrySet().iterator();
1617                            while (it.hasNext() && i < size) {
1618                                Map.Entry<String, ArrayList<String>> ent = it.next();
1619                                packages[i] = ent.getKey();
1620                                components[i] = ent.getValue();
1621                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1622                                uids[i] = (ps != null)
1623                                        ? UserHandle.getUid(packageUserId, ps.appId)
1624                                        : -1;
1625                                i++;
1626                            }
1627                        }
1628                        size = i;
1629                        mPendingBroadcasts.clear();
1630                    }
1631                    // Send broadcasts
1632                    for (int i = 0; i < size; i++) {
1633                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1634                    }
1635                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1636                    break;
1637                }
1638                case START_CLEANING_PACKAGE: {
1639                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1640                    final String packageName = (String)msg.obj;
1641                    final int userId = msg.arg1;
1642                    final boolean andCode = msg.arg2 != 0;
1643                    synchronized (mPackages) {
1644                        if (userId == UserHandle.USER_ALL) {
1645                            int[] users = sUserManager.getUserIds();
1646                            for (int user : users) {
1647                                mSettings.addPackageToCleanLPw(
1648                                        new PackageCleanItem(user, packageName, andCode));
1649                            }
1650                        } else {
1651                            mSettings.addPackageToCleanLPw(
1652                                    new PackageCleanItem(userId, packageName, andCode));
1653                        }
1654                    }
1655                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1656                    startCleaningPackages();
1657                } break;
1658                case POST_INSTALL: {
1659                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1660
1661                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1662                    final boolean didRestore = (msg.arg2 != 0);
1663                    mRunningInstalls.delete(msg.arg1);
1664
1665                    if (data != null) {
1666                        InstallArgs args = data.args;
1667                        PackageInstalledInfo parentRes = data.res;
1668
1669                        final boolean grantPermissions = (args.installFlags
1670                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1671                        final boolean killApp = (args.installFlags
1672                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1673                        final String[] grantedPermissions = args.installGrantPermissions;
1674
1675                        // Handle the parent package
1676                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1677                                grantedPermissions, didRestore, args.installerPackageName,
1678                                args.observer);
1679
1680                        // Handle the child packages
1681                        final int childCount = (parentRes.addedChildPackages != null)
1682                                ? parentRes.addedChildPackages.size() : 0;
1683                        for (int i = 0; i < childCount; i++) {
1684                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1685                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1686                                    grantedPermissions, false, args.installerPackageName,
1687                                    args.observer);
1688                        }
1689
1690                        // Log tracing if needed
1691                        if (args.traceMethod != null) {
1692                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1693                                    args.traceCookie);
1694                        }
1695                    } else {
1696                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1697                    }
1698
1699                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1700                } break;
1701                case UPDATED_MEDIA_STATUS: {
1702                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1703                    boolean reportStatus = msg.arg1 == 1;
1704                    boolean doGc = msg.arg2 == 1;
1705                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1706                    if (doGc) {
1707                        // Force a gc to clear up stale containers.
1708                        Runtime.getRuntime().gc();
1709                    }
1710                    if (msg.obj != null) {
1711                        @SuppressWarnings("unchecked")
1712                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1713                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1714                        // Unload containers
1715                        unloadAllContainers(args);
1716                    }
1717                    if (reportStatus) {
1718                        try {
1719                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1720                                    "Invoking StorageManagerService call back");
1721                            PackageHelper.getStorageManager().finishMediaUpdate();
1722                        } catch (RemoteException e) {
1723                            Log.e(TAG, "StorageManagerService not running?");
1724                        }
1725                    }
1726                } break;
1727                case WRITE_SETTINGS: {
1728                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1729                    synchronized (mPackages) {
1730                        removeMessages(WRITE_SETTINGS);
1731                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1732                        mSettings.writeLPr();
1733                        mDirtyUsers.clear();
1734                    }
1735                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1736                } break;
1737                case WRITE_PACKAGE_RESTRICTIONS: {
1738                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1739                    synchronized (mPackages) {
1740                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1741                        for (int userId : mDirtyUsers) {
1742                            mSettings.writePackageRestrictionsLPr(userId);
1743                        }
1744                        mDirtyUsers.clear();
1745                    }
1746                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1747                } break;
1748                case WRITE_PACKAGE_LIST: {
1749                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1750                    synchronized (mPackages) {
1751                        removeMessages(WRITE_PACKAGE_LIST);
1752                        mSettings.writePackageListLPr(msg.arg1);
1753                    }
1754                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1755                } break;
1756                case CHECK_PENDING_VERIFICATION: {
1757                    final int verificationId = msg.arg1;
1758                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1759
1760                    if ((state != null) && !state.timeoutExtended()) {
1761                        final InstallArgs args = state.getInstallArgs();
1762                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1763
1764                        Slog.i(TAG, "Verification timed out for " + originUri);
1765                        mPendingVerification.remove(verificationId);
1766
1767                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1768
1769                        final UserHandle user = args.getUser();
1770                        if (getDefaultVerificationResponse(user)
1771                                == PackageManager.VERIFICATION_ALLOW) {
1772                            Slog.i(TAG, "Continuing with installation of " + originUri);
1773                            state.setVerifierResponse(Binder.getCallingUid(),
1774                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1775                            broadcastPackageVerified(verificationId, originUri,
1776                                    PackageManager.VERIFICATION_ALLOW, user);
1777                            try {
1778                                ret = args.copyApk(mContainerService, true);
1779                            } catch (RemoteException e) {
1780                                Slog.e(TAG, "Could not contact the ContainerService");
1781                            }
1782                        } else {
1783                            broadcastPackageVerified(verificationId, originUri,
1784                                    PackageManager.VERIFICATION_REJECT, user);
1785                        }
1786
1787                        Trace.asyncTraceEnd(
1788                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1789
1790                        processPendingInstall(args, ret);
1791                        mHandler.sendEmptyMessage(MCS_UNBIND);
1792                    }
1793                    break;
1794                }
1795                case PACKAGE_VERIFIED: {
1796                    final int verificationId = msg.arg1;
1797
1798                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1799                    if (state == null) {
1800                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1801                        break;
1802                    }
1803
1804                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1805
1806                    state.setVerifierResponse(response.callerUid, response.code);
1807
1808                    if (state.isVerificationComplete()) {
1809                        mPendingVerification.remove(verificationId);
1810
1811                        final InstallArgs args = state.getInstallArgs();
1812                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1813
1814                        int ret;
1815                        if (state.isInstallAllowed()) {
1816                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1817                            broadcastPackageVerified(verificationId, originUri,
1818                                    response.code, state.getInstallArgs().getUser());
1819                            try {
1820                                ret = args.copyApk(mContainerService, true);
1821                            } catch (RemoteException e) {
1822                                Slog.e(TAG, "Could not contact the ContainerService");
1823                            }
1824                        } else {
1825                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1826                        }
1827
1828                        Trace.asyncTraceEnd(
1829                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1830
1831                        processPendingInstall(args, ret);
1832                        mHandler.sendEmptyMessage(MCS_UNBIND);
1833                    }
1834
1835                    break;
1836                }
1837                case START_INTENT_FILTER_VERIFICATIONS: {
1838                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1839                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1840                            params.replacing, params.pkg);
1841                    break;
1842                }
1843                case INTENT_FILTER_VERIFIED: {
1844                    final int verificationId = msg.arg1;
1845
1846                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1847                            verificationId);
1848                    if (state == null) {
1849                        Slog.w(TAG, "Invalid IntentFilter verification token "
1850                                + verificationId + " received");
1851                        break;
1852                    }
1853
1854                    final int userId = state.getUserId();
1855
1856                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1857                            "Processing IntentFilter verification with token:"
1858                            + verificationId + " and userId:" + userId);
1859
1860                    final IntentFilterVerificationResponse response =
1861                            (IntentFilterVerificationResponse) msg.obj;
1862
1863                    state.setVerifierResponse(response.callerUid, response.code);
1864
1865                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1866                            "IntentFilter verification with token:" + verificationId
1867                            + " and userId:" + userId
1868                            + " is settings verifier response with response code:"
1869                            + response.code);
1870
1871                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1872                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1873                                + response.getFailedDomainsString());
1874                    }
1875
1876                    if (state.isVerificationComplete()) {
1877                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1878                    } else {
1879                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1880                                "IntentFilter verification with token:" + verificationId
1881                                + " was not said to be complete");
1882                    }
1883
1884                    break;
1885                }
1886                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1887                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1888                            mInstantAppResolverConnection,
1889                            (InstantAppRequest) msg.obj,
1890                            mInstantAppInstallerActivity,
1891                            mHandler);
1892                }
1893            }
1894        }
1895    }
1896
1897    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1898            boolean killApp, String[] grantedPermissions,
1899            boolean launchedForRestore, String installerPackage,
1900            IPackageInstallObserver2 installObserver) {
1901        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1902            // Send the removed broadcasts
1903            if (res.removedInfo != null) {
1904                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1905            }
1906
1907            // Now that we successfully installed the package, grant runtime
1908            // permissions if requested before broadcasting the install. Also
1909            // for legacy apps in permission review mode we clear the permission
1910            // review flag which is used to emulate runtime permissions for
1911            // legacy apps.
1912            if (grantPermissions) {
1913                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1914            }
1915
1916            final boolean update = res.removedInfo != null
1917                    && res.removedInfo.removedPackage != null;
1918            final String origInstallerPackageName = res.removedInfo != null
1919                    ? res.removedInfo.installerPackageName : null;
1920
1921            // If this is the first time we have child packages for a disabled privileged
1922            // app that had no children, we grant requested runtime permissions to the new
1923            // children if the parent on the system image had them already granted.
1924            if (res.pkg.parentPackage != null) {
1925                synchronized (mPackages) {
1926                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1927                }
1928            }
1929
1930            synchronized (mPackages) {
1931                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1932            }
1933
1934            final String packageName = res.pkg.applicationInfo.packageName;
1935
1936            // Determine the set of users who are adding this package for
1937            // the first time vs. those who are seeing an update.
1938            int[] firstUsers = EMPTY_INT_ARRAY;
1939            int[] updateUsers = EMPTY_INT_ARRAY;
1940            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1941            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1942            for (int newUser : res.newUsers) {
1943                if (ps.getInstantApp(newUser)) {
1944                    continue;
1945                }
1946                if (allNewUsers) {
1947                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1948                    continue;
1949                }
1950                boolean isNew = true;
1951                for (int origUser : res.origUsers) {
1952                    if (origUser == newUser) {
1953                        isNew = false;
1954                        break;
1955                    }
1956                }
1957                if (isNew) {
1958                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1959                } else {
1960                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1961                }
1962            }
1963
1964            // Send installed broadcasts if the package is not a static shared lib.
1965            if (res.pkg.staticSharedLibName == null) {
1966                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1967
1968                // Send added for users that see the package for the first time
1969                // sendPackageAddedForNewUsers also deals with system apps
1970                int appId = UserHandle.getAppId(res.uid);
1971                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1972                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1973
1974                // Send added for users that don't see the package for the first time
1975                Bundle extras = new Bundle(1);
1976                extras.putInt(Intent.EXTRA_UID, res.uid);
1977                if (update) {
1978                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1979                }
1980                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1981                        extras, 0 /*flags*/,
1982                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1983                if (origInstallerPackageName != null) {
1984                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1985                            extras, 0 /*flags*/,
1986                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1987                }
1988
1989                // Send replaced for users that don't see the package for the first time
1990                if (update) {
1991                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1992                            packageName, extras, 0 /*flags*/,
1993                            null /*targetPackage*/, null /*finishedReceiver*/,
1994                            updateUsers);
1995                    if (origInstallerPackageName != null) {
1996                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1997                                extras, 0 /*flags*/,
1998                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1999                    }
2000                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2001                            null /*package*/, null /*extras*/, 0 /*flags*/,
2002                            packageName /*targetPackage*/,
2003                            null /*finishedReceiver*/, updateUsers);
2004                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2005                    // First-install and we did a restore, so we're responsible for the
2006                    // first-launch broadcast.
2007                    if (DEBUG_BACKUP) {
2008                        Slog.i(TAG, "Post-restore of " + packageName
2009                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2010                    }
2011                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2012                }
2013
2014                // Send broadcast package appeared if forward locked/external for all users
2015                // treat asec-hosted packages like removable media on upgrade
2016                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2017                    if (DEBUG_INSTALL) {
2018                        Slog.i(TAG, "upgrading pkg " + res.pkg
2019                                + " is ASEC-hosted -> AVAILABLE");
2020                    }
2021                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2022                    ArrayList<String> pkgList = new ArrayList<>(1);
2023                    pkgList.add(packageName);
2024                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2025                }
2026            }
2027
2028            // Work that needs to happen on first install within each user
2029            if (firstUsers != null && firstUsers.length > 0) {
2030                synchronized (mPackages) {
2031                    for (int userId : firstUsers) {
2032                        // If this app is a browser and it's newly-installed for some
2033                        // users, clear any default-browser state in those users. The
2034                        // app's nature doesn't depend on the user, so we can just check
2035                        // its browser nature in any user and generalize.
2036                        if (packageIsBrowser(packageName, userId)) {
2037                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2038                        }
2039
2040                        // We may also need to apply pending (restored) runtime
2041                        // permission grants within these users.
2042                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2043                    }
2044                }
2045            }
2046
2047            // Log current value of "unknown sources" setting
2048            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2049                    getUnknownSourcesSettings());
2050
2051            // Remove the replaced package's older resources safely now
2052            // We delete after a gc for applications  on sdcard.
2053            if (res.removedInfo != null && res.removedInfo.args != null) {
2054                Runtime.getRuntime().gc();
2055                synchronized (mInstallLock) {
2056                    res.removedInfo.args.doPostDeleteLI(true);
2057                }
2058            } else {
2059                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2060                // and not block here.
2061                VMRuntime.getRuntime().requestConcurrentGC();
2062            }
2063
2064            // Notify DexManager that the package was installed for new users.
2065            // The updated users should already be indexed and the package code paths
2066            // should not change.
2067            // Don't notify the manager for ephemeral apps as they are not expected to
2068            // survive long enough to benefit of background optimizations.
2069            for (int userId : firstUsers) {
2070                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2071                // There's a race currently where some install events may interleave with an uninstall.
2072                // This can lead to package info being null (b/36642664).
2073                if (info != null) {
2074                    mDexManager.notifyPackageInstalled(info, userId);
2075                }
2076            }
2077        }
2078
2079        // If someone is watching installs - notify them
2080        if (installObserver != null) {
2081            try {
2082                Bundle extras = extrasForInstallResult(res);
2083                installObserver.onPackageInstalled(res.name, res.returnCode,
2084                        res.returnMsg, extras);
2085            } catch (RemoteException e) {
2086                Slog.i(TAG, "Observer no longer exists.");
2087            }
2088        }
2089    }
2090
2091    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2092            PackageParser.Package pkg) {
2093        if (pkg.parentPackage == null) {
2094            return;
2095        }
2096        if (pkg.requestedPermissions == null) {
2097            return;
2098        }
2099        final PackageSetting disabledSysParentPs = mSettings
2100                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2101        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2102                || !disabledSysParentPs.isPrivileged()
2103                || (disabledSysParentPs.childPackageNames != null
2104                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2105            return;
2106        }
2107        final int[] allUserIds = sUserManager.getUserIds();
2108        final int permCount = pkg.requestedPermissions.size();
2109        for (int i = 0; i < permCount; i++) {
2110            String permission = pkg.requestedPermissions.get(i);
2111            BasePermission bp = mSettings.mPermissions.get(permission);
2112            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2113                continue;
2114            }
2115            for (int userId : allUserIds) {
2116                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2117                        permission, userId)) {
2118                    grantRuntimePermission(pkg.packageName, permission, userId);
2119                }
2120            }
2121        }
2122    }
2123
2124    private StorageEventListener mStorageListener = new StorageEventListener() {
2125        @Override
2126        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2127            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2128                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2129                    final String volumeUuid = vol.getFsUuid();
2130
2131                    // Clean up any users or apps that were removed or recreated
2132                    // while this volume was missing
2133                    sUserManager.reconcileUsers(volumeUuid);
2134                    reconcileApps(volumeUuid);
2135
2136                    // Clean up any install sessions that expired or were
2137                    // cancelled while this volume was missing
2138                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2139
2140                    loadPrivatePackages(vol);
2141
2142                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2143                    unloadPrivatePackages(vol);
2144                }
2145            }
2146
2147            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2148                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2149                    updateExternalMediaStatus(true, false);
2150                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2151                    updateExternalMediaStatus(false, false);
2152                }
2153            }
2154        }
2155
2156        @Override
2157        public void onVolumeForgotten(String fsUuid) {
2158            if (TextUtils.isEmpty(fsUuid)) {
2159                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2160                return;
2161            }
2162
2163            // Remove any apps installed on the forgotten volume
2164            synchronized (mPackages) {
2165                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2166                for (PackageSetting ps : packages) {
2167                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2168                    deletePackageVersioned(new VersionedPackage(ps.name,
2169                            PackageManager.VERSION_CODE_HIGHEST),
2170                            new LegacyPackageDeleteObserver(null).getBinder(),
2171                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2172                    // Try very hard to release any references to this package
2173                    // so we don't risk the system server being killed due to
2174                    // open FDs
2175                    AttributeCache.instance().removePackage(ps.name);
2176                }
2177
2178                mSettings.onVolumeForgotten(fsUuid);
2179                mSettings.writeLPr();
2180            }
2181        }
2182    };
2183
2184    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2185            String[] grantedPermissions) {
2186        for (int userId : userIds) {
2187            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2188        }
2189    }
2190
2191    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2192            String[] grantedPermissions) {
2193        PackageSetting ps = (PackageSetting) pkg.mExtras;
2194        if (ps == null) {
2195            return;
2196        }
2197
2198        PermissionsState permissionsState = ps.getPermissionsState();
2199
2200        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2201                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2202
2203        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2204                >= Build.VERSION_CODES.M;
2205
2206        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2207
2208        for (String permission : pkg.requestedPermissions) {
2209            final BasePermission bp;
2210            synchronized (mPackages) {
2211                bp = mSettings.mPermissions.get(permission);
2212            }
2213            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2214                    && (!instantApp || bp.isInstant())
2215                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2216                    && (grantedPermissions == null
2217                           || ArrayUtils.contains(grantedPermissions, permission))) {
2218                final int flags = permissionsState.getPermissionFlags(permission, userId);
2219                if (supportsRuntimePermissions) {
2220                    // Installer cannot change immutable permissions.
2221                    if ((flags & immutableFlags) == 0) {
2222                        grantRuntimePermission(pkg.packageName, permission, userId);
2223                    }
2224                } else if (mPermissionReviewRequired) {
2225                    // In permission review mode we clear the review flag when we
2226                    // are asked to install the app with all permissions granted.
2227                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2228                        updatePermissionFlags(permission, pkg.packageName,
2229                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2230                    }
2231                }
2232            }
2233        }
2234    }
2235
2236    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2237        Bundle extras = null;
2238        switch (res.returnCode) {
2239            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2240                extras = new Bundle();
2241                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2242                        res.origPermission);
2243                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2244                        res.origPackage);
2245                break;
2246            }
2247            case PackageManager.INSTALL_SUCCEEDED: {
2248                extras = new Bundle();
2249                extras.putBoolean(Intent.EXTRA_REPLACING,
2250                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2251                break;
2252            }
2253        }
2254        return extras;
2255    }
2256
2257    void scheduleWriteSettingsLocked() {
2258        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2259            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2260        }
2261    }
2262
2263    void scheduleWritePackageListLocked(int userId) {
2264        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2265            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2266            msg.arg1 = userId;
2267            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2268        }
2269    }
2270
2271    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2272        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2273        scheduleWritePackageRestrictionsLocked(userId);
2274    }
2275
2276    void scheduleWritePackageRestrictionsLocked(int userId) {
2277        final int[] userIds = (userId == UserHandle.USER_ALL)
2278                ? sUserManager.getUserIds() : new int[]{userId};
2279        for (int nextUserId : userIds) {
2280            if (!sUserManager.exists(nextUserId)) return;
2281            mDirtyUsers.add(nextUserId);
2282            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2283                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2284            }
2285        }
2286    }
2287
2288    public static PackageManagerService main(Context context, Installer installer,
2289            boolean factoryTest, boolean onlyCore) {
2290        // Self-check for initial settings.
2291        PackageManagerServiceCompilerMapping.checkProperties();
2292
2293        PackageManagerService m = new PackageManagerService(context, installer,
2294                factoryTest, onlyCore);
2295        m.enableSystemUserPackages();
2296        ServiceManager.addService("package", m);
2297        return m;
2298    }
2299
2300    private void enableSystemUserPackages() {
2301        if (!UserManager.isSplitSystemUser()) {
2302            return;
2303        }
2304        // For system user, enable apps based on the following conditions:
2305        // - app is whitelisted or belong to one of these groups:
2306        //   -- system app which has no launcher icons
2307        //   -- system app which has INTERACT_ACROSS_USERS permission
2308        //   -- system IME app
2309        // - app is not in the blacklist
2310        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2311        Set<String> enableApps = new ArraySet<>();
2312        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2313                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2314                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2315        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2316        enableApps.addAll(wlApps);
2317        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2318                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2319        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2320        enableApps.removeAll(blApps);
2321        Log.i(TAG, "Applications installed for system user: " + enableApps);
2322        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2323                UserHandle.SYSTEM);
2324        final int allAppsSize = allAps.size();
2325        synchronized (mPackages) {
2326            for (int i = 0; i < allAppsSize; i++) {
2327                String pName = allAps.get(i);
2328                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2329                // Should not happen, but we shouldn't be failing if it does
2330                if (pkgSetting == null) {
2331                    continue;
2332                }
2333                boolean install = enableApps.contains(pName);
2334                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2335                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2336                            + " for system user");
2337                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2338                }
2339            }
2340            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2341        }
2342    }
2343
2344    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2345        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2346                Context.DISPLAY_SERVICE);
2347        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2348    }
2349
2350    /**
2351     * Requests that files preopted on a secondary system partition be copied to the data partition
2352     * if possible.  Note that the actual copying of the files is accomplished by init for security
2353     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2354     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2355     */
2356    private static void requestCopyPreoptedFiles() {
2357        final int WAIT_TIME_MS = 100;
2358        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2359        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2360            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2361            // We will wait for up to 100 seconds.
2362            final long timeStart = SystemClock.uptimeMillis();
2363            final long timeEnd = timeStart + 100 * 1000;
2364            long timeNow = timeStart;
2365            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2366                try {
2367                    Thread.sleep(WAIT_TIME_MS);
2368                } catch (InterruptedException e) {
2369                    // Do nothing
2370                }
2371                timeNow = SystemClock.uptimeMillis();
2372                if (timeNow > timeEnd) {
2373                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2374                    Slog.wtf(TAG, "cppreopt did not finish!");
2375                    break;
2376                }
2377            }
2378
2379            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2380        }
2381    }
2382
2383    public PackageManagerService(Context context, Installer installer,
2384            boolean factoryTest, boolean onlyCore) {
2385        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2386        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2387        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2388                SystemClock.uptimeMillis());
2389
2390        if (mSdkVersion <= 0) {
2391            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2392        }
2393
2394        mContext = context;
2395
2396        mPermissionReviewRequired = context.getResources().getBoolean(
2397                R.bool.config_permissionReviewRequired);
2398
2399        mFactoryTest = factoryTest;
2400        mOnlyCore = onlyCore;
2401        mMetrics = new DisplayMetrics();
2402        mSettings = new Settings(mPackages);
2403        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2408                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2409        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2410                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2411        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2412                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2413        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2414                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2415
2416        String separateProcesses = SystemProperties.get("debug.separate_processes");
2417        if (separateProcesses != null && separateProcesses.length() > 0) {
2418            if ("*".equals(separateProcesses)) {
2419                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2420                mSeparateProcesses = null;
2421                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2422            } else {
2423                mDefParseFlags = 0;
2424                mSeparateProcesses = separateProcesses.split(",");
2425                Slog.w(TAG, "Running with debug.separate_processes: "
2426                        + separateProcesses);
2427            }
2428        } else {
2429            mDefParseFlags = 0;
2430            mSeparateProcesses = null;
2431        }
2432
2433        mInstaller = installer;
2434        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2435                "*dexopt*");
2436        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2437        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2438
2439        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2440                FgThread.get().getLooper());
2441
2442        getDefaultDisplayMetrics(context, mMetrics);
2443
2444        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2445        SystemConfig systemConfig = SystemConfig.getInstance();
2446        mGlobalGids = systemConfig.getGlobalGids();
2447        mSystemPermissions = systemConfig.getSystemPermissions();
2448        mAvailableFeatures = systemConfig.getAvailableFeatures();
2449        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2450
2451        mProtectedPackages = new ProtectedPackages(mContext);
2452
2453        synchronized (mInstallLock) {
2454        // writer
2455        synchronized (mPackages) {
2456            mHandlerThread = new ServiceThread(TAG,
2457                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2458            mHandlerThread.start();
2459            mHandler = new PackageHandler(mHandlerThread.getLooper());
2460            mProcessLoggingHandler = new ProcessLoggingHandler();
2461            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2462
2463            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2464            mInstantAppRegistry = new InstantAppRegistry(this);
2465
2466            File dataDir = Environment.getDataDirectory();
2467            mAppInstallDir = new File(dataDir, "app");
2468            mAppLib32InstallDir = new File(dataDir, "app-lib");
2469            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2470            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2471            sUserManager = new UserManagerService(context, this,
2472                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2473
2474            // Propagate permission configuration in to package manager.
2475            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2476                    = systemConfig.getPermissions();
2477            for (int i=0; i<permConfig.size(); i++) {
2478                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2479                BasePermission bp = mSettings.mPermissions.get(perm.name);
2480                if (bp == null) {
2481                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2482                    mSettings.mPermissions.put(perm.name, bp);
2483                }
2484                if (perm.gids != null) {
2485                    bp.setGids(perm.gids, perm.perUser);
2486                }
2487            }
2488
2489            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2490            final int builtInLibCount = libConfig.size();
2491            for (int i = 0; i < builtInLibCount; i++) {
2492                String name = libConfig.keyAt(i);
2493                String path = libConfig.valueAt(i);
2494                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2495                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2496            }
2497
2498            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2499
2500            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2501            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2502            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2503
2504            // Clean up orphaned packages for which the code path doesn't exist
2505            // and they are an update to a system app - caused by bug/32321269
2506            final int packageSettingCount = mSettings.mPackages.size();
2507            for (int i = packageSettingCount - 1; i >= 0; i--) {
2508                PackageSetting ps = mSettings.mPackages.valueAt(i);
2509                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2510                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2511                    mSettings.mPackages.removeAt(i);
2512                    mSettings.enableSystemPackageLPw(ps.name);
2513                }
2514            }
2515
2516            if (mFirstBoot) {
2517                requestCopyPreoptedFiles();
2518            }
2519
2520            String customResolverActivity = Resources.getSystem().getString(
2521                    R.string.config_customResolverActivity);
2522            if (TextUtils.isEmpty(customResolverActivity)) {
2523                customResolverActivity = null;
2524            } else {
2525                mCustomResolverComponentName = ComponentName.unflattenFromString(
2526                        customResolverActivity);
2527            }
2528
2529            long startTime = SystemClock.uptimeMillis();
2530
2531            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2532                    startTime);
2533
2534            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2535            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2536
2537            if (bootClassPath == null) {
2538                Slog.w(TAG, "No BOOTCLASSPATH found!");
2539            }
2540
2541            if (systemServerClassPath == null) {
2542                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2543            }
2544
2545            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2546
2547            final VersionInfo ver = mSettings.getInternalVersion();
2548            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2549            if (mIsUpgrade) {
2550                logCriticalInfo(Log.INFO,
2551                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2552            }
2553
2554            // when upgrading from pre-M, promote system app permissions from install to runtime
2555            mPromoteSystemApps =
2556                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2557
2558            // When upgrading from pre-N, we need to handle package extraction like first boot,
2559            // as there is no profiling data available.
2560            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2561
2562            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2563
2564            // save off the names of pre-existing system packages prior to scanning; we don't
2565            // want to automatically grant runtime permissions for new system apps
2566            if (mPromoteSystemApps) {
2567                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2568                while (pkgSettingIter.hasNext()) {
2569                    PackageSetting ps = pkgSettingIter.next();
2570                    if (isSystemApp(ps)) {
2571                        mExistingSystemPackages.add(ps.name);
2572                    }
2573                }
2574            }
2575
2576            mCacheDir = preparePackageParserCache(mIsUpgrade);
2577
2578            // Set flag to monitor and not change apk file paths when
2579            // scanning install directories.
2580            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2581
2582            if (mIsUpgrade || mFirstBoot) {
2583                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2584            }
2585
2586            // Collect vendor overlay packages. (Do this before scanning any apps.)
2587            // For security and version matching reason, only consider
2588            // overlay packages if they reside in the right directory.
2589            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2590                    | PackageParser.PARSE_IS_SYSTEM
2591                    | PackageParser.PARSE_IS_SYSTEM_DIR
2592                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2593
2594            mParallelPackageParserCallback.findStaticOverlayPackages();
2595
2596            // Find base frameworks (resource packages without code).
2597            scanDirTracedLI(frameworkDir, mDefParseFlags
2598                    | PackageParser.PARSE_IS_SYSTEM
2599                    | PackageParser.PARSE_IS_SYSTEM_DIR
2600                    | PackageParser.PARSE_IS_PRIVILEGED,
2601                    scanFlags | SCAN_NO_DEX, 0);
2602
2603            // Collected privileged system packages.
2604            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2605            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2606                    | PackageParser.PARSE_IS_SYSTEM
2607                    | PackageParser.PARSE_IS_SYSTEM_DIR
2608                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2609
2610            // Collect ordinary system packages.
2611            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2612            scanDirTracedLI(systemAppDir, mDefParseFlags
2613                    | PackageParser.PARSE_IS_SYSTEM
2614                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2615
2616            // Collect all vendor packages.
2617            File vendorAppDir = new File("/vendor/app");
2618            try {
2619                vendorAppDir = vendorAppDir.getCanonicalFile();
2620            } catch (IOException e) {
2621                // failed to look up canonical path, continue with original one
2622            }
2623            scanDirTracedLI(vendorAppDir, mDefParseFlags
2624                    | PackageParser.PARSE_IS_SYSTEM
2625                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2626
2627            // Collect all OEM packages.
2628            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2629            scanDirTracedLI(oemAppDir, mDefParseFlags
2630                    | PackageParser.PARSE_IS_SYSTEM
2631                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2632
2633            // Prune any system packages that no longer exist.
2634            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2635            if (!mOnlyCore) {
2636                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2637                while (psit.hasNext()) {
2638                    PackageSetting ps = psit.next();
2639
2640                    /*
2641                     * If this is not a system app, it can't be a
2642                     * disable system app.
2643                     */
2644                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2645                        continue;
2646                    }
2647
2648                    /*
2649                     * If the package is scanned, it's not erased.
2650                     */
2651                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2652                    if (scannedPkg != null) {
2653                        /*
2654                         * If the system app is both scanned and in the
2655                         * disabled packages list, then it must have been
2656                         * added via OTA. Remove it from the currently
2657                         * scanned package so the previously user-installed
2658                         * application can be scanned.
2659                         */
2660                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2661                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2662                                    + ps.name + "; removing system app.  Last known codePath="
2663                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2664                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2665                                    + scannedPkg.mVersionCode);
2666                            removePackageLI(scannedPkg, true);
2667                            mExpectingBetter.put(ps.name, ps.codePath);
2668                        }
2669
2670                        continue;
2671                    }
2672
2673                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2674                        psit.remove();
2675                        logCriticalInfo(Log.WARN, "System package " + ps.name
2676                                + " no longer exists; it's data will be wiped");
2677                        // Actual deletion of code and data will be handled by later
2678                        // reconciliation step
2679                    } else {
2680                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2681                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2682                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2683                        }
2684                    }
2685                }
2686            }
2687
2688            //look for any incomplete package installations
2689            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2690            for (int i = 0; i < deletePkgsList.size(); i++) {
2691                // Actual deletion of code and data will be handled by later
2692                // reconciliation step
2693                final String packageName = deletePkgsList.get(i).name;
2694                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2695                synchronized (mPackages) {
2696                    mSettings.removePackageLPw(packageName);
2697                }
2698            }
2699
2700            //delete tmp files
2701            deleteTempPackageFiles();
2702
2703            // Remove any shared userIDs that have no associated packages
2704            mSettings.pruneSharedUsersLPw();
2705            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2706            final int systemPackagesCount = mPackages.size();
2707            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2708                    + " ms, packageCount: " + systemPackagesCount
2709                    + " ms, timePerPackage: "
2710                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount));
2711            if (mIsUpgrade && systemPackagesCount > 0) {
2712                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2713                        ((int) systemScanTime) / systemPackagesCount);
2714            }
2715            if (!mOnlyCore) {
2716                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2717                        SystemClock.uptimeMillis());
2718                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2719
2720                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2721                        | PackageParser.PARSE_FORWARD_LOCK,
2722                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2723
2724                /**
2725                 * Remove disable package settings for any updated system
2726                 * apps that were removed via an OTA. If they're not a
2727                 * previously-updated app, remove them completely.
2728                 * Otherwise, just revoke their system-level permissions.
2729                 */
2730                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2731                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2732                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2733
2734                    String msg;
2735                    if (deletedPkg == null) {
2736                        msg = "Updated system package " + deletedAppName
2737                                + " no longer exists; it's data will be wiped";
2738                        // Actual deletion of code and data will be handled by later
2739                        // reconciliation step
2740                    } else {
2741                        msg = "Updated system app + " + deletedAppName
2742                                + " no longer present; removing system privileges for "
2743                                + deletedAppName;
2744
2745                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2746
2747                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2748                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2749                    }
2750                    logCriticalInfo(Log.WARN, msg);
2751                }
2752
2753                /**
2754                 * Make sure all system apps that we expected to appear on
2755                 * the userdata partition actually showed up. If they never
2756                 * appeared, crawl back and revive the system version.
2757                 */
2758                for (int i = 0; i < mExpectingBetter.size(); i++) {
2759                    final String packageName = mExpectingBetter.keyAt(i);
2760                    if (!mPackages.containsKey(packageName)) {
2761                        final File scanFile = mExpectingBetter.valueAt(i);
2762
2763                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2764                                + " but never showed up; reverting to system");
2765
2766                        int reparseFlags = mDefParseFlags;
2767                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2768                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2769                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2770                                    | PackageParser.PARSE_IS_PRIVILEGED;
2771                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2772                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2773                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2774                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2775                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2776                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2777                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2778                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2779                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2780                        } else {
2781                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2782                            continue;
2783                        }
2784
2785                        mSettings.enableSystemPackageLPw(packageName);
2786
2787                        try {
2788                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2789                        } catch (PackageManagerException e) {
2790                            Slog.e(TAG, "Failed to parse original system package: "
2791                                    + e.getMessage());
2792                        }
2793                    }
2794                }
2795                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2796                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2797                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2798                        + " ms, packageCount: " + dataPackagesCount
2799                        + " ms, timePerPackage: "
2800                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount));
2801                if (mIsUpgrade && dataPackagesCount > 0) {
2802                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2803                            ((int) dataScanTime) / dataPackagesCount);
2804                }
2805            }
2806            mExpectingBetter.clear();
2807
2808            // Resolve the storage manager.
2809            mStorageManagerPackage = getStorageManagerPackageName();
2810
2811            // Resolve protected action filters. Only the setup wizard is allowed to
2812            // have a high priority filter for these actions.
2813            mSetupWizardPackage = getSetupWizardPackageName();
2814            if (mProtectedFilters.size() > 0) {
2815                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2816                    Slog.i(TAG, "No setup wizard;"
2817                        + " All protected intents capped to priority 0");
2818                }
2819                for (ActivityIntentInfo filter : mProtectedFilters) {
2820                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2821                        if (DEBUG_FILTERS) {
2822                            Slog.i(TAG, "Found setup wizard;"
2823                                + " allow priority " + filter.getPriority() + ";"
2824                                + " package: " + filter.activity.info.packageName
2825                                + " activity: " + filter.activity.className
2826                                + " priority: " + filter.getPriority());
2827                        }
2828                        // skip setup wizard; allow it to keep the high priority filter
2829                        continue;
2830                    }
2831                    if (DEBUG_FILTERS) {
2832                        Slog.i(TAG, "Protected action; cap priority to 0;"
2833                                + " package: " + filter.activity.info.packageName
2834                                + " activity: " + filter.activity.className
2835                                + " origPrio: " + filter.getPriority());
2836                    }
2837                    filter.setPriority(0);
2838                }
2839            }
2840            mDeferProtectedFilters = false;
2841            mProtectedFilters.clear();
2842
2843            // Now that we know all of the shared libraries, update all clients to have
2844            // the correct library paths.
2845            updateAllSharedLibrariesLPw(null);
2846
2847            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2848                // NOTE: We ignore potential failures here during a system scan (like
2849                // the rest of the commands above) because there's precious little we
2850                // can do about it. A settings error is reported, though.
2851                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2852            }
2853
2854            // Now that we know all the packages we are keeping,
2855            // read and update their last usage times.
2856            mPackageUsage.read(mPackages);
2857            mCompilerStats.read();
2858
2859            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2860                    SystemClock.uptimeMillis());
2861            Slog.i(TAG, "Time to scan packages: "
2862                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2863                    + " seconds");
2864
2865            // If the platform SDK has changed since the last time we booted,
2866            // we need to re-grant app permission to catch any new ones that
2867            // appear.  This is really a hack, and means that apps can in some
2868            // cases get permissions that the user didn't initially explicitly
2869            // allow...  it would be nice to have some better way to handle
2870            // this situation.
2871            int updateFlags = UPDATE_PERMISSIONS_ALL;
2872            if (ver.sdkVersion != mSdkVersion) {
2873                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2874                        + mSdkVersion + "; regranting permissions for internal storage");
2875                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2876            }
2877            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2878            ver.sdkVersion = mSdkVersion;
2879
2880            // If this is the first boot or an update from pre-M, and it is a normal
2881            // boot, then we need to initialize the default preferred apps across
2882            // all defined users.
2883            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2884                for (UserInfo user : sUserManager.getUsers(true)) {
2885                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2886                    applyFactoryDefaultBrowserLPw(user.id);
2887                    primeDomainVerificationsLPw(user.id);
2888                }
2889            }
2890
2891            // Prepare storage for system user really early during boot,
2892            // since core system apps like SettingsProvider and SystemUI
2893            // can't wait for user to start
2894            final int storageFlags;
2895            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2896                storageFlags = StorageManager.FLAG_STORAGE_DE;
2897            } else {
2898                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2899            }
2900            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2901                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2902                    true /* onlyCoreApps */);
2903            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2904                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2905                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2906                traceLog.traceBegin("AppDataFixup");
2907                try {
2908                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2909                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2910                } catch (InstallerException e) {
2911                    Slog.w(TAG, "Trouble fixing GIDs", e);
2912                }
2913                traceLog.traceEnd();
2914
2915                traceLog.traceBegin("AppDataPrepare");
2916                if (deferPackages == null || deferPackages.isEmpty()) {
2917                    return;
2918                }
2919                int count = 0;
2920                for (String pkgName : deferPackages) {
2921                    PackageParser.Package pkg = null;
2922                    synchronized (mPackages) {
2923                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2924                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2925                            pkg = ps.pkg;
2926                        }
2927                    }
2928                    if (pkg != null) {
2929                        synchronized (mInstallLock) {
2930                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2931                                    true /* maybeMigrateAppData */);
2932                        }
2933                        count++;
2934                    }
2935                }
2936                traceLog.traceEnd();
2937                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2938            }, "prepareAppData");
2939
2940            // If this is first boot after an OTA, and a normal boot, then
2941            // we need to clear code cache directories.
2942            // Note that we do *not* clear the application profiles. These remain valid
2943            // across OTAs and are used to drive profile verification (post OTA) and
2944            // profile compilation (without waiting to collect a fresh set of profiles).
2945            if (mIsUpgrade && !onlyCore) {
2946                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2947                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2948                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2949                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2950                        // No apps are running this early, so no need to freeze
2951                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2952                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2953                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2954                    }
2955                }
2956                ver.fingerprint = Build.FINGERPRINT;
2957            }
2958
2959            checkDefaultBrowser();
2960
2961            // clear only after permissions and other defaults have been updated
2962            mExistingSystemPackages.clear();
2963            mPromoteSystemApps = false;
2964
2965            // All the changes are done during package scanning.
2966            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2967
2968            // can downgrade to reader
2969            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2970            mSettings.writeLPr();
2971            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2972            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2973                    SystemClock.uptimeMillis());
2974
2975            if (!mOnlyCore) {
2976                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2977                mRequiredInstallerPackage = getRequiredInstallerLPr();
2978                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2979                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2980                if (mIntentFilterVerifierComponent != null) {
2981                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2982                            mIntentFilterVerifierComponent);
2983                } else {
2984                    mIntentFilterVerifier = null;
2985                }
2986                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2987                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2988                        SharedLibraryInfo.VERSION_UNDEFINED);
2989                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2990                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2991                        SharedLibraryInfo.VERSION_UNDEFINED);
2992            } else {
2993                mRequiredVerifierPackage = null;
2994                mRequiredInstallerPackage = null;
2995                mRequiredUninstallerPackage = null;
2996                mIntentFilterVerifierComponent = null;
2997                mIntentFilterVerifier = null;
2998                mServicesSystemSharedLibraryPackageName = null;
2999                mSharedSystemSharedLibraryPackageName = null;
3000            }
3001
3002            mInstallerService = new PackageInstallerService(context, this);
3003            final Pair<ComponentName, String> instantAppResolverComponent =
3004                    getInstantAppResolverLPr();
3005            if (instantAppResolverComponent != null) {
3006                if (DEBUG_EPHEMERAL) {
3007                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3008                }
3009                mInstantAppResolverConnection = new EphemeralResolverConnection(
3010                        mContext, instantAppResolverComponent.first,
3011                        instantAppResolverComponent.second);
3012                mInstantAppResolverSettingsComponent =
3013                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3014            } else {
3015                mInstantAppResolverConnection = null;
3016                mInstantAppResolverSettingsComponent = null;
3017            }
3018            updateInstantAppInstallerLocked(null);
3019
3020            // Read and update the usage of dex files.
3021            // Do this at the end of PM init so that all the packages have their
3022            // data directory reconciled.
3023            // At this point we know the code paths of the packages, so we can validate
3024            // the disk file and build the internal cache.
3025            // The usage file is expected to be small so loading and verifying it
3026            // should take a fairly small time compare to the other activities (e.g. package
3027            // scanning).
3028            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3029            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3030            for (int userId : currentUserIds) {
3031                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3032            }
3033            mDexManager.load(userPackages);
3034            if (mIsUpgrade) {
3035                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3036                        (int) (SystemClock.uptimeMillis() - startTime));
3037            }
3038        } // synchronized (mPackages)
3039        } // synchronized (mInstallLock)
3040
3041        // Now after opening every single application zip, make sure they
3042        // are all flushed.  Not really needed, but keeps things nice and
3043        // tidy.
3044        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3045        Runtime.getRuntime().gc();
3046        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3047
3048        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3049        FallbackCategoryProvider.loadFallbacks();
3050        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3051
3052        // The initial scanning above does many calls into installd while
3053        // holding the mPackages lock, but we're mostly interested in yelling
3054        // once we have a booted system.
3055        mInstaller.setWarnIfHeld(mPackages);
3056
3057        // Expose private service for system components to use.
3058        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3059        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3060    }
3061
3062    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3063        // we're only interested in updating the installer appliction when 1) it's not
3064        // already set or 2) the modified package is the installer
3065        if (mInstantAppInstallerActivity != null
3066                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3067                        .equals(modifiedPackage)) {
3068            return;
3069        }
3070        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3071    }
3072
3073    private static File preparePackageParserCache(boolean isUpgrade) {
3074        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3075            return null;
3076        }
3077
3078        // Disable package parsing on eng builds to allow for faster incremental development.
3079        if (Build.IS_ENG) {
3080            return null;
3081        }
3082
3083        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3084            Slog.i(TAG, "Disabling package parser cache due to system property.");
3085            return null;
3086        }
3087
3088        // The base directory for the package parser cache lives under /data/system/.
3089        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3090                "package_cache");
3091        if (cacheBaseDir == null) {
3092            return null;
3093        }
3094
3095        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3096        // This also serves to "GC" unused entries when the package cache version changes (which
3097        // can only happen during upgrades).
3098        if (isUpgrade) {
3099            FileUtils.deleteContents(cacheBaseDir);
3100        }
3101
3102
3103        // Return the versioned package cache directory. This is something like
3104        // "/data/system/package_cache/1"
3105        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3106
3107        // The following is a workaround to aid development on non-numbered userdebug
3108        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3109        // the system partition is newer.
3110        //
3111        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3112        // that starts with "eng." to signify that this is an engineering build and not
3113        // destined for release.
3114        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3115            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3116
3117            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3118            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3119            // in general and should not be used for production changes. In this specific case,
3120            // we know that they will work.
3121            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3122            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3123                FileUtils.deleteContents(cacheBaseDir);
3124                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3125            }
3126        }
3127
3128        return cacheDir;
3129    }
3130
3131    @Override
3132    public boolean isFirstBoot() {
3133        // allow instant applications
3134        return mFirstBoot;
3135    }
3136
3137    @Override
3138    public boolean isOnlyCoreApps() {
3139        // allow instant applications
3140        return mOnlyCore;
3141    }
3142
3143    @Override
3144    public boolean isUpgrade() {
3145        // allow instant applications
3146        return mIsUpgrade;
3147    }
3148
3149    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3150        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3151
3152        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3153                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3154                UserHandle.USER_SYSTEM);
3155        if (matches.size() == 1) {
3156            return matches.get(0).getComponentInfo().packageName;
3157        } else if (matches.size() == 0) {
3158            Log.e(TAG, "There should probably be a verifier, but, none were found");
3159            return null;
3160        }
3161        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3162    }
3163
3164    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3165        synchronized (mPackages) {
3166            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3167            if (libraryEntry == null) {
3168                throw new IllegalStateException("Missing required shared library:" + name);
3169            }
3170            return libraryEntry.apk;
3171        }
3172    }
3173
3174    private @NonNull String getRequiredInstallerLPr() {
3175        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3176        intent.addCategory(Intent.CATEGORY_DEFAULT);
3177        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3178
3179        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3180                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3181                UserHandle.USER_SYSTEM);
3182        if (matches.size() == 1) {
3183            ResolveInfo resolveInfo = matches.get(0);
3184            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3185                throw new RuntimeException("The installer must be a privileged app");
3186            }
3187            return matches.get(0).getComponentInfo().packageName;
3188        } else {
3189            throw new RuntimeException("There must be exactly one installer; found " + matches);
3190        }
3191    }
3192
3193    private @NonNull String getRequiredUninstallerLPr() {
3194        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3195        intent.addCategory(Intent.CATEGORY_DEFAULT);
3196        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3197
3198        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3199                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3200                UserHandle.USER_SYSTEM);
3201        if (resolveInfo == null ||
3202                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3203            throw new RuntimeException("There must be exactly one uninstaller; found "
3204                    + resolveInfo);
3205        }
3206        return resolveInfo.getComponentInfo().packageName;
3207    }
3208
3209    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3210        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3211
3212        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3213                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3214                UserHandle.USER_SYSTEM);
3215        ResolveInfo best = null;
3216        final int N = matches.size();
3217        for (int i = 0; i < N; i++) {
3218            final ResolveInfo cur = matches.get(i);
3219            final String packageName = cur.getComponentInfo().packageName;
3220            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3221                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3222                continue;
3223            }
3224
3225            if (best == null || cur.priority > best.priority) {
3226                best = cur;
3227            }
3228        }
3229
3230        if (best != null) {
3231            return best.getComponentInfo().getComponentName();
3232        }
3233        Slog.w(TAG, "Intent filter verifier not found");
3234        return null;
3235    }
3236
3237    @Override
3238    public @Nullable ComponentName getInstantAppResolverComponent() {
3239        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3240            return null;
3241        }
3242        synchronized (mPackages) {
3243            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3244            if (instantAppResolver == null) {
3245                return null;
3246            }
3247            return instantAppResolver.first;
3248        }
3249    }
3250
3251    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3252        final String[] packageArray =
3253                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3254        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3255            if (DEBUG_EPHEMERAL) {
3256                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3257            }
3258            return null;
3259        }
3260
3261        final int callingUid = Binder.getCallingUid();
3262        final int resolveFlags =
3263                MATCH_DIRECT_BOOT_AWARE
3264                | MATCH_DIRECT_BOOT_UNAWARE
3265                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3266        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3267        final Intent resolverIntent = new Intent(actionName);
3268        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3269                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3270        // temporarily look for the old action
3271        if (resolvers.size() == 0) {
3272            if (DEBUG_EPHEMERAL) {
3273                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3274            }
3275            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3276            resolverIntent.setAction(actionName);
3277            resolvers = queryIntentServicesInternal(resolverIntent, null,
3278                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3279        }
3280        final int N = resolvers.size();
3281        if (N == 0) {
3282            if (DEBUG_EPHEMERAL) {
3283                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3284            }
3285            return null;
3286        }
3287
3288        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3289        for (int i = 0; i < N; i++) {
3290            final ResolveInfo info = resolvers.get(i);
3291
3292            if (info.serviceInfo == null) {
3293                continue;
3294            }
3295
3296            final String packageName = info.serviceInfo.packageName;
3297            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3298                if (DEBUG_EPHEMERAL) {
3299                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3300                            + " pkg: " + packageName + ", info:" + info);
3301                }
3302                continue;
3303            }
3304
3305            if (DEBUG_EPHEMERAL) {
3306                Slog.v(TAG, "Ephemeral resolver found;"
3307                        + " pkg: " + packageName + ", info:" + info);
3308            }
3309            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3310        }
3311        if (DEBUG_EPHEMERAL) {
3312            Slog.v(TAG, "Ephemeral resolver NOT found");
3313        }
3314        return null;
3315    }
3316
3317    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3318        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3319        intent.addCategory(Intent.CATEGORY_DEFAULT);
3320        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3321
3322        final int resolveFlags =
3323                MATCH_DIRECT_BOOT_AWARE
3324                | MATCH_DIRECT_BOOT_UNAWARE
3325                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3326        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3327                resolveFlags, UserHandle.USER_SYSTEM);
3328        // temporarily look for the old action
3329        if (matches.isEmpty()) {
3330            if (DEBUG_EPHEMERAL) {
3331                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3332            }
3333            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3334            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3335                    resolveFlags, UserHandle.USER_SYSTEM);
3336        }
3337        Iterator<ResolveInfo> iter = matches.iterator();
3338        while (iter.hasNext()) {
3339            final ResolveInfo rInfo = iter.next();
3340            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3341            if (ps != null) {
3342                final PermissionsState permissionsState = ps.getPermissionsState();
3343                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3344                    continue;
3345                }
3346            }
3347            iter.remove();
3348        }
3349        if (matches.size() == 0) {
3350            return null;
3351        } else if (matches.size() == 1) {
3352            return (ActivityInfo) matches.get(0).getComponentInfo();
3353        } else {
3354            throw new RuntimeException(
3355                    "There must be at most one ephemeral installer; found " + matches);
3356        }
3357    }
3358
3359    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3360            @NonNull ComponentName resolver) {
3361        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3362                .addCategory(Intent.CATEGORY_DEFAULT)
3363                .setPackage(resolver.getPackageName());
3364        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3365        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3366                UserHandle.USER_SYSTEM);
3367        // temporarily look for the old action
3368        if (matches.isEmpty()) {
3369            if (DEBUG_EPHEMERAL) {
3370                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3371            }
3372            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3373            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3374                    UserHandle.USER_SYSTEM);
3375        }
3376        if (matches.isEmpty()) {
3377            return null;
3378        }
3379        return matches.get(0).getComponentInfo().getComponentName();
3380    }
3381
3382    private void primeDomainVerificationsLPw(int userId) {
3383        if (DEBUG_DOMAIN_VERIFICATION) {
3384            Slog.d(TAG, "Priming domain verifications in user " + userId);
3385        }
3386
3387        SystemConfig systemConfig = SystemConfig.getInstance();
3388        ArraySet<String> packages = systemConfig.getLinkedApps();
3389
3390        for (String packageName : packages) {
3391            PackageParser.Package pkg = mPackages.get(packageName);
3392            if (pkg != null) {
3393                if (!pkg.isSystemApp()) {
3394                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3395                    continue;
3396                }
3397
3398                ArraySet<String> domains = null;
3399                for (PackageParser.Activity a : pkg.activities) {
3400                    for (ActivityIntentInfo filter : a.intents) {
3401                        if (hasValidDomains(filter)) {
3402                            if (domains == null) {
3403                                domains = new ArraySet<String>();
3404                            }
3405                            domains.addAll(filter.getHostsList());
3406                        }
3407                    }
3408                }
3409
3410                if (domains != null && domains.size() > 0) {
3411                    if (DEBUG_DOMAIN_VERIFICATION) {
3412                        Slog.v(TAG, "      + " + packageName);
3413                    }
3414                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3415                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3416                    // and then 'always' in the per-user state actually used for intent resolution.
3417                    final IntentFilterVerificationInfo ivi;
3418                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3419                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3420                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3421                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3422                } else {
3423                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3424                            + "' does not handle web links");
3425                }
3426            } else {
3427                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3428            }
3429        }
3430
3431        scheduleWritePackageRestrictionsLocked(userId);
3432        scheduleWriteSettingsLocked();
3433    }
3434
3435    private void applyFactoryDefaultBrowserLPw(int userId) {
3436        // The default browser app's package name is stored in a string resource,
3437        // with a product-specific overlay used for vendor customization.
3438        String browserPkg = mContext.getResources().getString(
3439                com.android.internal.R.string.default_browser);
3440        if (!TextUtils.isEmpty(browserPkg)) {
3441            // non-empty string => required to be a known package
3442            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3443            if (ps == null) {
3444                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3445                browserPkg = null;
3446            } else {
3447                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3448            }
3449        }
3450
3451        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3452        // default.  If there's more than one, just leave everything alone.
3453        if (browserPkg == null) {
3454            calculateDefaultBrowserLPw(userId);
3455        }
3456    }
3457
3458    private void calculateDefaultBrowserLPw(int userId) {
3459        List<String> allBrowsers = resolveAllBrowserApps(userId);
3460        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3461        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3462    }
3463
3464    private List<String> resolveAllBrowserApps(int userId) {
3465        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3466        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3467                PackageManager.MATCH_ALL, userId);
3468
3469        final int count = list.size();
3470        List<String> result = new ArrayList<String>(count);
3471        for (int i=0; i<count; i++) {
3472            ResolveInfo info = list.get(i);
3473            if (info.activityInfo == null
3474                    || !info.handleAllWebDataURI
3475                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3476                    || result.contains(info.activityInfo.packageName)) {
3477                continue;
3478            }
3479            result.add(info.activityInfo.packageName);
3480        }
3481
3482        return result;
3483    }
3484
3485    private boolean packageIsBrowser(String packageName, int userId) {
3486        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3487                PackageManager.MATCH_ALL, userId);
3488        final int N = list.size();
3489        for (int i = 0; i < N; i++) {
3490            ResolveInfo info = list.get(i);
3491            if (packageName.equals(info.activityInfo.packageName)) {
3492                return true;
3493            }
3494        }
3495        return false;
3496    }
3497
3498    private void checkDefaultBrowser() {
3499        final int myUserId = UserHandle.myUserId();
3500        final String packageName = getDefaultBrowserPackageName(myUserId);
3501        if (packageName != null) {
3502            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3503            if (info == null) {
3504                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3505                synchronized (mPackages) {
3506                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3507                }
3508            }
3509        }
3510    }
3511
3512    @Override
3513    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3514            throws RemoteException {
3515        try {
3516            return super.onTransact(code, data, reply, flags);
3517        } catch (RuntimeException e) {
3518            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3519                Slog.wtf(TAG, "Package Manager Crash", e);
3520            }
3521            throw e;
3522        }
3523    }
3524
3525    static int[] appendInts(int[] cur, int[] add) {
3526        if (add == null) return cur;
3527        if (cur == null) return add;
3528        final int N = add.length;
3529        for (int i=0; i<N; i++) {
3530            cur = appendInt(cur, add[i]);
3531        }
3532        return cur;
3533    }
3534
3535    /**
3536     * Returns whether or not a full application can see an instant application.
3537     * <p>
3538     * Currently, there are three cases in which this can occur:
3539     * <ol>
3540     * <li>The calling application is a "special" process. The special
3541     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3542     *     and {@code 0}</li>
3543     * <li>The calling application has the permission
3544     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3545     * <li>The calling application is the default launcher on the
3546     *     system partition.</li>
3547     * </ol>
3548     */
3549    private boolean canViewInstantApps(int callingUid, int userId) {
3550        if (callingUid == Process.SYSTEM_UID
3551                || callingUid == Process.SHELL_UID
3552                || callingUid == Process.ROOT_UID) {
3553            return true;
3554        }
3555        if (mContext.checkCallingOrSelfPermission(
3556                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3557            return true;
3558        }
3559        if (mContext.checkCallingOrSelfPermission(
3560                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3561            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3562            if (homeComponent != null
3563                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3564                return true;
3565            }
3566        }
3567        return false;
3568    }
3569
3570    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3571        if (!sUserManager.exists(userId)) return null;
3572        if (ps == null) {
3573            return null;
3574        }
3575        PackageParser.Package p = ps.pkg;
3576        if (p == null) {
3577            return null;
3578        }
3579        final int callingUid = Binder.getCallingUid();
3580        // Filter out ephemeral app metadata:
3581        //   * The system/shell/root can see metadata for any app
3582        //   * An installed app can see metadata for 1) other installed apps
3583        //     and 2) ephemeral apps that have explicitly interacted with it
3584        //   * Ephemeral apps can only see their own data and exposed installed apps
3585        //   * Holding a signature permission allows seeing instant apps
3586        if (filterAppAccessLPr(ps, callingUid, userId)) {
3587            return null;
3588        }
3589
3590        final PermissionsState permissionsState = ps.getPermissionsState();
3591
3592        // Compute GIDs only if requested
3593        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3594                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3595        // Compute granted permissions only if package has requested permissions
3596        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3597                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3598        final PackageUserState state = ps.readUserState(userId);
3599
3600        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3601                && ps.isSystem()) {
3602            flags |= MATCH_ANY_USER;
3603        }
3604
3605        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3606                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3607
3608        if (packageInfo == null) {
3609            return null;
3610        }
3611
3612        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3613                resolveExternalPackageNameLPr(p);
3614
3615        return packageInfo;
3616    }
3617
3618    @Override
3619    public void checkPackageStartable(String packageName, int userId) {
3620        final int callingUid = Binder.getCallingUid();
3621        if (getInstantAppPackageName(callingUid) != null) {
3622            throw new SecurityException("Instant applications don't have access to this method");
3623        }
3624        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3625        synchronized (mPackages) {
3626            final PackageSetting ps = mSettings.mPackages.get(packageName);
3627            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3628                throw new SecurityException("Package " + packageName + " was not found!");
3629            }
3630
3631            if (!ps.getInstalled(userId)) {
3632                throw new SecurityException(
3633                        "Package " + packageName + " was not installed for user " + userId + "!");
3634            }
3635
3636            if (mSafeMode && !ps.isSystem()) {
3637                throw new SecurityException("Package " + packageName + " not a system app!");
3638            }
3639
3640            if (mFrozenPackages.contains(packageName)) {
3641                throw new SecurityException("Package " + packageName + " is currently frozen!");
3642            }
3643
3644            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3645                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3646                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3647            }
3648        }
3649    }
3650
3651    @Override
3652    public boolean isPackageAvailable(String packageName, int userId) {
3653        if (!sUserManager.exists(userId)) return false;
3654        final int callingUid = Binder.getCallingUid();
3655        enforceCrossUserPermission(callingUid, userId,
3656                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3657        synchronized (mPackages) {
3658            PackageParser.Package p = mPackages.get(packageName);
3659            if (p != null) {
3660                final PackageSetting ps = (PackageSetting) p.mExtras;
3661                if (filterAppAccessLPr(ps, callingUid, userId)) {
3662                    return false;
3663                }
3664                if (ps != null) {
3665                    final PackageUserState state = ps.readUserState(userId);
3666                    if (state != null) {
3667                        return PackageParser.isAvailable(state);
3668                    }
3669                }
3670            }
3671        }
3672        return false;
3673    }
3674
3675    @Override
3676    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3677        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3678                flags, Binder.getCallingUid(), userId);
3679    }
3680
3681    @Override
3682    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3683            int flags, int userId) {
3684        return getPackageInfoInternal(versionedPackage.getPackageName(),
3685                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3686    }
3687
3688    /**
3689     * Important: The provided filterCallingUid is used exclusively to filter out packages
3690     * that can be seen based on user state. It's typically the original caller uid prior
3691     * to clearing. Because it can only be provided by trusted code, it's value can be
3692     * trusted and will be used as-is; unlike userId which will be validated by this method.
3693     */
3694    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3695            int flags, int filterCallingUid, int userId) {
3696        if (!sUserManager.exists(userId)) return null;
3697        flags = updateFlagsForPackage(flags, userId, packageName);
3698        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3699                false /* requireFullPermission */, false /* checkShell */, "get package info");
3700
3701        // reader
3702        synchronized (mPackages) {
3703            // Normalize package name to handle renamed packages and static libs
3704            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3705
3706            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3707            if (matchFactoryOnly) {
3708                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3709                if (ps != null) {
3710                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3711                        return null;
3712                    }
3713                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3714                        return null;
3715                    }
3716                    return generatePackageInfo(ps, flags, userId);
3717                }
3718            }
3719
3720            PackageParser.Package p = mPackages.get(packageName);
3721            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3722                return null;
3723            }
3724            if (DEBUG_PACKAGE_INFO)
3725                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3726            if (p != null) {
3727                final PackageSetting ps = (PackageSetting) p.mExtras;
3728                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3729                    return null;
3730                }
3731                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3732                    return null;
3733                }
3734                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3735            }
3736            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3737                final PackageSetting ps = mSettings.mPackages.get(packageName);
3738                if (ps == null) return null;
3739                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3740                    return null;
3741                }
3742                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3743                    return null;
3744                }
3745                return generatePackageInfo(ps, flags, userId);
3746            }
3747        }
3748        return null;
3749    }
3750
3751    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3752        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3753            return true;
3754        }
3755        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3756            return true;
3757        }
3758        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3759            return true;
3760        }
3761        return false;
3762    }
3763
3764    private boolean isComponentVisibleToInstantApp(
3765            @Nullable ComponentName component, @ComponentType int type) {
3766        if (type == TYPE_ACTIVITY) {
3767            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3768            return activity != null
3769                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3770                    : false;
3771        } else if (type == TYPE_RECEIVER) {
3772            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3773            return activity != null
3774                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3775                    : false;
3776        } else if (type == TYPE_SERVICE) {
3777            final PackageParser.Service service = mServices.mServices.get(component);
3778            return service != null
3779                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3780                    : false;
3781        } else if (type == TYPE_PROVIDER) {
3782            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3783            return provider != null
3784                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3785                    : false;
3786        } else if (type == TYPE_UNKNOWN) {
3787            return isComponentVisibleToInstantApp(component);
3788        }
3789        return false;
3790    }
3791
3792    /**
3793     * Returns whether or not access to the application should be filtered.
3794     * <p>
3795     * Access may be limited based upon whether the calling or target applications
3796     * are instant applications.
3797     *
3798     * @see #canAccessInstantApps(int)
3799     */
3800    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3801            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3802        // if we're in an isolated process, get the real calling UID
3803        if (Process.isIsolated(callingUid)) {
3804            callingUid = mIsolatedOwners.get(callingUid);
3805        }
3806        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3807        final boolean callerIsInstantApp = instantAppPkgName != null;
3808        if (ps == null) {
3809            if (callerIsInstantApp) {
3810                // pretend the application exists, but, needs to be filtered
3811                return true;
3812            }
3813            return false;
3814        }
3815        // if the target and caller are the same application, don't filter
3816        if (isCallerSameApp(ps.name, callingUid)) {
3817            return false;
3818        }
3819        if (callerIsInstantApp) {
3820            // request for a specific component; if it hasn't been explicitly exposed, filter
3821            if (component != null) {
3822                return !isComponentVisibleToInstantApp(component, componentType);
3823            }
3824            // request for application; if no components have been explicitly exposed, filter
3825            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3826        }
3827        if (ps.getInstantApp(userId)) {
3828            // caller can see all components of all instant applications, don't filter
3829            if (canViewInstantApps(callingUid, userId)) {
3830                return false;
3831            }
3832            // request for a specific instant application component, filter
3833            if (component != null) {
3834                return true;
3835            }
3836            // request for an instant application; if the caller hasn't been granted access, filter
3837            return !mInstantAppRegistry.isInstantAccessGranted(
3838                    userId, UserHandle.getAppId(callingUid), ps.appId);
3839        }
3840        return false;
3841    }
3842
3843    /**
3844     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3845     */
3846    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3847        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3848    }
3849
3850    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3851            int flags) {
3852        // Callers can access only the libs they depend on, otherwise they need to explicitly
3853        // ask for the shared libraries given the caller is allowed to access all static libs.
3854        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3855            // System/shell/root get to see all static libs
3856            final int appId = UserHandle.getAppId(uid);
3857            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3858                    || appId == Process.ROOT_UID) {
3859                return false;
3860            }
3861        }
3862
3863        // No package means no static lib as it is always on internal storage
3864        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3865            return false;
3866        }
3867
3868        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3869                ps.pkg.staticSharedLibVersion);
3870        if (libEntry == null) {
3871            return false;
3872        }
3873
3874        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3875        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3876        if (uidPackageNames == null) {
3877            return true;
3878        }
3879
3880        for (String uidPackageName : uidPackageNames) {
3881            if (ps.name.equals(uidPackageName)) {
3882                return false;
3883            }
3884            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3885            if (uidPs != null) {
3886                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3887                        libEntry.info.getName());
3888                if (index < 0) {
3889                    continue;
3890                }
3891                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3892                    return false;
3893                }
3894            }
3895        }
3896        return true;
3897    }
3898
3899    @Override
3900    public String[] currentToCanonicalPackageNames(String[] names) {
3901        final int callingUid = Binder.getCallingUid();
3902        if (getInstantAppPackageName(callingUid) != null) {
3903            return names;
3904        }
3905        final String[] out = new String[names.length];
3906        // reader
3907        synchronized (mPackages) {
3908            final int callingUserId = UserHandle.getUserId(callingUid);
3909            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3910            for (int i=names.length-1; i>=0; i--) {
3911                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3912                boolean translateName = false;
3913                if (ps != null && ps.realName != null) {
3914                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3915                    translateName = !targetIsInstantApp
3916                            || canViewInstantApps
3917                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3918                                    UserHandle.getAppId(callingUid), ps.appId);
3919                }
3920                out[i] = translateName ? ps.realName : names[i];
3921            }
3922        }
3923        return out;
3924    }
3925
3926    @Override
3927    public String[] canonicalToCurrentPackageNames(String[] names) {
3928        final int callingUid = Binder.getCallingUid();
3929        if (getInstantAppPackageName(callingUid) != null) {
3930            return names;
3931        }
3932        final String[] out = new String[names.length];
3933        // reader
3934        synchronized (mPackages) {
3935            final int callingUserId = UserHandle.getUserId(callingUid);
3936            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3937            for (int i=names.length-1; i>=0; i--) {
3938                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3939                boolean translateName = false;
3940                if (cur != null) {
3941                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3942                    final boolean targetIsInstantApp =
3943                            ps != null && ps.getInstantApp(callingUserId);
3944                    translateName = !targetIsInstantApp
3945                            || canViewInstantApps
3946                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3947                                    UserHandle.getAppId(callingUid), ps.appId);
3948                }
3949                out[i] = translateName ? cur : names[i];
3950            }
3951        }
3952        return out;
3953    }
3954
3955    @Override
3956    public int getPackageUid(String packageName, int flags, int userId) {
3957        if (!sUserManager.exists(userId)) return -1;
3958        final int callingUid = Binder.getCallingUid();
3959        flags = updateFlagsForPackage(flags, userId, packageName);
3960        enforceCrossUserPermission(callingUid, userId,
3961                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3962
3963        // reader
3964        synchronized (mPackages) {
3965            final PackageParser.Package p = mPackages.get(packageName);
3966            if (p != null && p.isMatch(flags)) {
3967                PackageSetting ps = (PackageSetting) p.mExtras;
3968                if (filterAppAccessLPr(ps, callingUid, userId)) {
3969                    return -1;
3970                }
3971                return UserHandle.getUid(userId, p.applicationInfo.uid);
3972            }
3973            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3974                final PackageSetting ps = mSettings.mPackages.get(packageName);
3975                if (ps != null && ps.isMatch(flags)
3976                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3977                    return UserHandle.getUid(userId, ps.appId);
3978                }
3979            }
3980        }
3981
3982        return -1;
3983    }
3984
3985    @Override
3986    public int[] getPackageGids(String packageName, int flags, int userId) {
3987        if (!sUserManager.exists(userId)) return null;
3988        final int callingUid = Binder.getCallingUid();
3989        flags = updateFlagsForPackage(flags, userId, packageName);
3990        enforceCrossUserPermission(callingUid, userId,
3991                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3992
3993        // reader
3994        synchronized (mPackages) {
3995            final PackageParser.Package p = mPackages.get(packageName);
3996            if (p != null && p.isMatch(flags)) {
3997                PackageSetting ps = (PackageSetting) p.mExtras;
3998                if (filterAppAccessLPr(ps, callingUid, userId)) {
3999                    return null;
4000                }
4001                // TODO: Shouldn't this be checking for package installed state for userId and
4002                // return null?
4003                return ps.getPermissionsState().computeGids(userId);
4004            }
4005            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4006                final PackageSetting ps = mSettings.mPackages.get(packageName);
4007                if (ps != null && ps.isMatch(flags)
4008                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4009                    return ps.getPermissionsState().computeGids(userId);
4010                }
4011            }
4012        }
4013
4014        return null;
4015    }
4016
4017    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4018        if (bp.perm != null) {
4019            return PackageParser.generatePermissionInfo(bp.perm, flags);
4020        }
4021        PermissionInfo pi = new PermissionInfo();
4022        pi.name = bp.name;
4023        pi.packageName = bp.sourcePackage;
4024        pi.nonLocalizedLabel = bp.name;
4025        pi.protectionLevel = bp.protectionLevel;
4026        return pi;
4027    }
4028
4029    @Override
4030    public PermissionInfo getPermissionInfo(String name, int flags) {
4031        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4032            return null;
4033        }
4034        // reader
4035        synchronized (mPackages) {
4036            final BasePermission p = mSettings.mPermissions.get(name);
4037            if (p != null) {
4038                return generatePermissionInfo(p, flags);
4039            }
4040            return null;
4041        }
4042    }
4043
4044    @Override
4045    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4046            int flags) {
4047        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4048            return null;
4049        }
4050        // reader
4051        synchronized (mPackages) {
4052            if (group != null && !mPermissionGroups.containsKey(group)) {
4053                // This is thrown as NameNotFoundException
4054                return null;
4055            }
4056
4057            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4058            for (BasePermission p : mSettings.mPermissions.values()) {
4059                if (group == null) {
4060                    if (p.perm == null || p.perm.info.group == null) {
4061                        out.add(generatePermissionInfo(p, flags));
4062                    }
4063                } else {
4064                    if (p.perm != null && group.equals(p.perm.info.group)) {
4065                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4066                    }
4067                }
4068            }
4069            return new ParceledListSlice<>(out);
4070        }
4071    }
4072
4073    @Override
4074    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4075        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4076            return null;
4077        }
4078        // reader
4079        synchronized (mPackages) {
4080            return PackageParser.generatePermissionGroupInfo(
4081                    mPermissionGroups.get(name), flags);
4082        }
4083    }
4084
4085    @Override
4086    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4087        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4088            return ParceledListSlice.emptyList();
4089        }
4090        // reader
4091        synchronized (mPackages) {
4092            final int N = mPermissionGroups.size();
4093            ArrayList<PermissionGroupInfo> out
4094                    = new ArrayList<PermissionGroupInfo>(N);
4095            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4096                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4097            }
4098            return new ParceledListSlice<>(out);
4099        }
4100    }
4101
4102    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4103            int filterCallingUid, int userId) {
4104        if (!sUserManager.exists(userId)) return null;
4105        PackageSetting ps = mSettings.mPackages.get(packageName);
4106        if (ps != null) {
4107            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4108                return null;
4109            }
4110            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4111                return null;
4112            }
4113            if (ps.pkg == null) {
4114                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4115                if (pInfo != null) {
4116                    return pInfo.applicationInfo;
4117                }
4118                return null;
4119            }
4120            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4121                    ps.readUserState(userId), userId);
4122            if (ai != null) {
4123                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4124            }
4125            return ai;
4126        }
4127        return null;
4128    }
4129
4130    @Override
4131    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4132        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4133    }
4134
4135    /**
4136     * Important: The provided filterCallingUid is used exclusively to filter out applications
4137     * that can be seen based on user state. It's typically the original caller uid prior
4138     * to clearing. Because it can only be provided by trusted code, it's value can be
4139     * trusted and will be used as-is; unlike userId which will be validated by this method.
4140     */
4141    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4142            int filterCallingUid, int userId) {
4143        if (!sUserManager.exists(userId)) return null;
4144        flags = updateFlagsForApplication(flags, userId, packageName);
4145        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4146                false /* requireFullPermission */, false /* checkShell */, "get application info");
4147
4148        // writer
4149        synchronized (mPackages) {
4150            // Normalize package name to handle renamed packages and static libs
4151            packageName = resolveInternalPackageNameLPr(packageName,
4152                    PackageManager.VERSION_CODE_HIGHEST);
4153
4154            PackageParser.Package p = mPackages.get(packageName);
4155            if (DEBUG_PACKAGE_INFO) Log.v(
4156                    TAG, "getApplicationInfo " + packageName
4157                    + ": " + p);
4158            if (p != null) {
4159                PackageSetting ps = mSettings.mPackages.get(packageName);
4160                if (ps == null) return null;
4161                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4162                    return null;
4163                }
4164                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4165                    return null;
4166                }
4167                // Note: isEnabledLP() does not apply here - always return info
4168                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4169                        p, flags, ps.readUserState(userId), userId);
4170                if (ai != null) {
4171                    ai.packageName = resolveExternalPackageNameLPr(p);
4172                }
4173                return ai;
4174            }
4175            if ("android".equals(packageName)||"system".equals(packageName)) {
4176                return mAndroidApplication;
4177            }
4178            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4179                // Already generates the external package name
4180                return generateApplicationInfoFromSettingsLPw(packageName,
4181                        flags, filterCallingUid, userId);
4182            }
4183        }
4184        return null;
4185    }
4186
4187    private String normalizePackageNameLPr(String packageName) {
4188        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4189        return normalizedPackageName != null ? normalizedPackageName : packageName;
4190    }
4191
4192    @Override
4193    public void deletePreloadsFileCache() {
4194        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4195            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4196        }
4197        File dir = Environment.getDataPreloadsFileCacheDirectory();
4198        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4199        FileUtils.deleteContents(dir);
4200    }
4201
4202    @Override
4203    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4204            final int storageFlags, final IPackageDataObserver observer) {
4205        mContext.enforceCallingOrSelfPermission(
4206                android.Manifest.permission.CLEAR_APP_CACHE, null);
4207        mHandler.post(() -> {
4208            boolean success = false;
4209            try {
4210                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4211                success = true;
4212            } catch (IOException e) {
4213                Slog.w(TAG, e);
4214            }
4215            if (observer != null) {
4216                try {
4217                    observer.onRemoveCompleted(null, success);
4218                } catch (RemoteException e) {
4219                    Slog.w(TAG, e);
4220                }
4221            }
4222        });
4223    }
4224
4225    @Override
4226    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4227            final int storageFlags, final IntentSender pi) {
4228        mContext.enforceCallingOrSelfPermission(
4229                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4230        mHandler.post(() -> {
4231            boolean success = false;
4232            try {
4233                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4234                success = true;
4235            } catch (IOException e) {
4236                Slog.w(TAG, e);
4237            }
4238            if (pi != null) {
4239                try {
4240                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4241                } catch (SendIntentException e) {
4242                    Slog.w(TAG, e);
4243                }
4244            }
4245        });
4246    }
4247
4248    /**
4249     * Blocking call to clear various types of cached data across the system
4250     * until the requested bytes are available.
4251     */
4252    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4253        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4254        final File file = storage.findPathForUuid(volumeUuid);
4255        if (file.getUsableSpace() >= bytes) return;
4256
4257        if (ENABLE_FREE_CACHE_V2) {
4258            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4259                    volumeUuid);
4260            final boolean aggressive = (storageFlags
4261                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4262            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4263
4264            // 1. Pre-flight to determine if we have any chance to succeed
4265            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4266            if (internalVolume && (aggressive || SystemProperties
4267                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4268                deletePreloadsFileCache();
4269                if (file.getUsableSpace() >= bytes) return;
4270            }
4271
4272            // 3. Consider parsed APK data (aggressive only)
4273            if (internalVolume && aggressive) {
4274                FileUtils.deleteContents(mCacheDir);
4275                if (file.getUsableSpace() >= bytes) return;
4276            }
4277
4278            // 4. Consider cached app data (above quotas)
4279            try {
4280                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4281                        Installer.FLAG_FREE_CACHE_V2);
4282            } catch (InstallerException ignored) {
4283            }
4284            if (file.getUsableSpace() >= bytes) return;
4285
4286            // 5. Consider shared libraries with refcount=0 and age>min cache period
4287            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4288                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4289                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4290                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4291                return;
4292            }
4293
4294            // 6. Consider dexopt output (aggressive only)
4295            // TODO: Implement
4296
4297            // 7. Consider installed instant apps unused longer than min cache period
4298            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4299                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4300                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4301                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4302                return;
4303            }
4304
4305            // 8. Consider cached app data (below quotas)
4306            try {
4307                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4308                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4309            } catch (InstallerException ignored) {
4310            }
4311            if (file.getUsableSpace() >= bytes) return;
4312
4313            // 9. Consider DropBox entries
4314            // TODO: Implement
4315
4316            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4317            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4318                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4319                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4320                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4321                return;
4322            }
4323        } else {
4324            try {
4325                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4326            } catch (InstallerException ignored) {
4327            }
4328            if (file.getUsableSpace() >= bytes) return;
4329        }
4330
4331        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4332    }
4333
4334    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4335            throws IOException {
4336        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4337        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4338
4339        List<VersionedPackage> packagesToDelete = null;
4340        final long now = System.currentTimeMillis();
4341
4342        synchronized (mPackages) {
4343            final int[] allUsers = sUserManager.getUserIds();
4344            final int libCount = mSharedLibraries.size();
4345            for (int i = 0; i < libCount; i++) {
4346                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4347                if (versionedLib == null) {
4348                    continue;
4349                }
4350                final int versionCount = versionedLib.size();
4351                for (int j = 0; j < versionCount; j++) {
4352                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4353                    // Skip packages that are not static shared libs.
4354                    if (!libInfo.isStatic()) {
4355                        break;
4356                    }
4357                    // Important: We skip static shared libs used for some user since
4358                    // in such a case we need to keep the APK on the device. The check for
4359                    // a lib being used for any user is performed by the uninstall call.
4360                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4361                    // Resolve the package name - we use synthetic package names internally
4362                    final String internalPackageName = resolveInternalPackageNameLPr(
4363                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4364                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4365                    // Skip unused static shared libs cached less than the min period
4366                    // to prevent pruning a lib needed by a subsequently installed package.
4367                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4368                        continue;
4369                    }
4370                    if (packagesToDelete == null) {
4371                        packagesToDelete = new ArrayList<>();
4372                    }
4373                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4374                            declaringPackage.getVersionCode()));
4375                }
4376            }
4377        }
4378
4379        if (packagesToDelete != null) {
4380            final int packageCount = packagesToDelete.size();
4381            for (int i = 0; i < packageCount; i++) {
4382                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4383                // Delete the package synchronously (will fail of the lib used for any user).
4384                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4385                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4386                                == PackageManager.DELETE_SUCCEEDED) {
4387                    if (volume.getUsableSpace() >= neededSpace) {
4388                        return true;
4389                    }
4390                }
4391            }
4392        }
4393
4394        return false;
4395    }
4396
4397    /**
4398     * Update given flags based on encryption status of current user.
4399     */
4400    private int updateFlags(int flags, int userId) {
4401        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4402                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4403            // Caller expressed an explicit opinion about what encryption
4404            // aware/unaware components they want to see, so fall through and
4405            // give them what they want
4406        } else {
4407            // Caller expressed no opinion, so match based on user state
4408            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4409                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4410            } else {
4411                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4412            }
4413        }
4414        return flags;
4415    }
4416
4417    private UserManagerInternal getUserManagerInternal() {
4418        if (mUserManagerInternal == null) {
4419            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4420        }
4421        return mUserManagerInternal;
4422    }
4423
4424    private DeviceIdleController.LocalService getDeviceIdleController() {
4425        if (mDeviceIdleController == null) {
4426            mDeviceIdleController =
4427                    LocalServices.getService(DeviceIdleController.LocalService.class);
4428        }
4429        return mDeviceIdleController;
4430    }
4431
4432    /**
4433     * Update given flags when being used to request {@link PackageInfo}.
4434     */
4435    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4436        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4437        boolean triaged = true;
4438        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4439                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4440            // Caller is asking for component details, so they'd better be
4441            // asking for specific encryption matching behavior, or be triaged
4442            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4443                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4444                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4445                triaged = false;
4446            }
4447        }
4448        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4449                | PackageManager.MATCH_SYSTEM_ONLY
4450                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4451            triaged = false;
4452        }
4453        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4454            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4455                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4456                    + Debug.getCallers(5));
4457        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4458                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4459            // If the caller wants all packages and has a restricted profile associated with it,
4460            // then match all users. This is to make sure that launchers that need to access work
4461            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4462            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4463            flags |= PackageManager.MATCH_ANY_USER;
4464        }
4465        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4466            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4467                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4468        }
4469        return updateFlags(flags, userId);
4470    }
4471
4472    /**
4473     * Update given flags when being used to request {@link ApplicationInfo}.
4474     */
4475    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4476        return updateFlagsForPackage(flags, userId, cookie);
4477    }
4478
4479    /**
4480     * Update given flags when being used to request {@link ComponentInfo}.
4481     */
4482    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4483        if (cookie instanceof Intent) {
4484            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4485                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4486            }
4487        }
4488
4489        boolean triaged = true;
4490        // Caller is asking for component details, so they'd better be
4491        // asking for specific encryption matching behavior, or be triaged
4492        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4493                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4494                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4495            triaged = false;
4496        }
4497        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4498            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4499                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4500        }
4501
4502        return updateFlags(flags, userId);
4503    }
4504
4505    /**
4506     * Update given intent when being used to request {@link ResolveInfo}.
4507     */
4508    private Intent updateIntentForResolve(Intent intent) {
4509        if (intent.getSelector() != null) {
4510            intent = intent.getSelector();
4511        }
4512        if (DEBUG_PREFERRED) {
4513            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4514        }
4515        return intent;
4516    }
4517
4518    /**
4519     * Update given flags when being used to request {@link ResolveInfo}.
4520     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4521     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4522     * flag set. However, this flag is only honoured in three circumstances:
4523     * <ul>
4524     * <li>when called from a system process</li>
4525     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4526     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4527     * action and a {@code android.intent.category.BROWSABLE} category</li>
4528     * </ul>
4529     */
4530    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4531        return updateFlagsForResolve(flags, userId, intent, callingUid,
4532                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4533    }
4534    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4535            boolean wantInstantApps) {
4536        return updateFlagsForResolve(flags, userId, intent, callingUid,
4537                wantInstantApps, false /*onlyExposedExplicitly*/);
4538    }
4539    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4540            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4541        // Safe mode means we shouldn't match any third-party components
4542        if (mSafeMode) {
4543            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4544        }
4545        if (getInstantAppPackageName(callingUid) != null) {
4546            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4547            if (onlyExposedExplicitly) {
4548                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4549            }
4550            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4551            flags |= PackageManager.MATCH_INSTANT;
4552        } else {
4553            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4554            final boolean allowMatchInstant =
4555                    (wantInstantApps
4556                            && Intent.ACTION_VIEW.equals(intent.getAction())
4557                            && hasWebURI(intent))
4558                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4559            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4560                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4561            if (!allowMatchInstant) {
4562                flags &= ~PackageManager.MATCH_INSTANT;
4563            }
4564        }
4565        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4566    }
4567
4568    @Override
4569    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4570        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4571    }
4572
4573    /**
4574     * Important: The provided filterCallingUid is used exclusively to filter out activities
4575     * that can be seen based on user state. It's typically the original caller uid prior
4576     * to clearing. Because it can only be provided by trusted code, it's value can be
4577     * trusted and will be used as-is; unlike userId which will be validated by this method.
4578     */
4579    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4580            int filterCallingUid, int userId) {
4581        if (!sUserManager.exists(userId)) return null;
4582        flags = updateFlagsForComponent(flags, userId, component);
4583        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4584                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4585        synchronized (mPackages) {
4586            PackageParser.Activity a = mActivities.mActivities.get(component);
4587
4588            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4589            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4590                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4591                if (ps == null) return null;
4592                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4593                    return null;
4594                }
4595                return PackageParser.generateActivityInfo(
4596                        a, flags, ps.readUserState(userId), userId);
4597            }
4598            if (mResolveComponentName.equals(component)) {
4599                return PackageParser.generateActivityInfo(
4600                        mResolveActivity, flags, new PackageUserState(), userId);
4601            }
4602        }
4603        return null;
4604    }
4605
4606    @Override
4607    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4608            String resolvedType) {
4609        synchronized (mPackages) {
4610            if (component.equals(mResolveComponentName)) {
4611                // The resolver supports EVERYTHING!
4612                return true;
4613            }
4614            final int callingUid = Binder.getCallingUid();
4615            final int callingUserId = UserHandle.getUserId(callingUid);
4616            PackageParser.Activity a = mActivities.mActivities.get(component);
4617            if (a == null) {
4618                return false;
4619            }
4620            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4621            if (ps == null) {
4622                return false;
4623            }
4624            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4625                return false;
4626            }
4627            for (int i=0; i<a.intents.size(); i++) {
4628                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4629                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4630                    return true;
4631                }
4632            }
4633            return false;
4634        }
4635    }
4636
4637    @Override
4638    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4639        if (!sUserManager.exists(userId)) return null;
4640        final int callingUid = Binder.getCallingUid();
4641        flags = updateFlagsForComponent(flags, userId, component);
4642        enforceCrossUserPermission(callingUid, userId,
4643                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4644        synchronized (mPackages) {
4645            PackageParser.Activity a = mReceivers.mActivities.get(component);
4646            if (DEBUG_PACKAGE_INFO) Log.v(
4647                TAG, "getReceiverInfo " + component + ": " + a);
4648            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4649                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4650                if (ps == null) return null;
4651                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4652                    return null;
4653                }
4654                return PackageParser.generateActivityInfo(
4655                        a, flags, ps.readUserState(userId), userId);
4656            }
4657        }
4658        return null;
4659    }
4660
4661    @Override
4662    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4663            int flags, int userId) {
4664        if (!sUserManager.exists(userId)) return null;
4665        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4666        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4667            return null;
4668        }
4669
4670        flags = updateFlagsForPackage(flags, userId, null);
4671
4672        final boolean canSeeStaticLibraries =
4673                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4674                        == PERMISSION_GRANTED
4675                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4676                        == PERMISSION_GRANTED
4677                || canRequestPackageInstallsInternal(packageName,
4678                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4679                        false  /* throwIfPermNotDeclared*/)
4680                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4681                        == PERMISSION_GRANTED;
4682
4683        synchronized (mPackages) {
4684            List<SharedLibraryInfo> result = null;
4685
4686            final int libCount = mSharedLibraries.size();
4687            for (int i = 0; i < libCount; i++) {
4688                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4689                if (versionedLib == null) {
4690                    continue;
4691                }
4692
4693                final int versionCount = versionedLib.size();
4694                for (int j = 0; j < versionCount; j++) {
4695                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4696                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4697                        break;
4698                    }
4699                    final long identity = Binder.clearCallingIdentity();
4700                    try {
4701                        PackageInfo packageInfo = getPackageInfoVersioned(
4702                                libInfo.getDeclaringPackage(), flags
4703                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4704                        if (packageInfo == null) {
4705                            continue;
4706                        }
4707                    } finally {
4708                        Binder.restoreCallingIdentity(identity);
4709                    }
4710
4711                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4712                            libInfo.getVersion(), libInfo.getType(),
4713                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4714                            flags, userId));
4715
4716                    if (result == null) {
4717                        result = new ArrayList<>();
4718                    }
4719                    result.add(resLibInfo);
4720                }
4721            }
4722
4723            return result != null ? new ParceledListSlice<>(result) : null;
4724        }
4725    }
4726
4727    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4728            SharedLibraryInfo libInfo, int flags, int userId) {
4729        List<VersionedPackage> versionedPackages = null;
4730        final int packageCount = mSettings.mPackages.size();
4731        for (int i = 0; i < packageCount; i++) {
4732            PackageSetting ps = mSettings.mPackages.valueAt(i);
4733
4734            if (ps == null) {
4735                continue;
4736            }
4737
4738            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4739                continue;
4740            }
4741
4742            final String libName = libInfo.getName();
4743            if (libInfo.isStatic()) {
4744                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4745                if (libIdx < 0) {
4746                    continue;
4747                }
4748                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4749                    continue;
4750                }
4751                if (versionedPackages == null) {
4752                    versionedPackages = new ArrayList<>();
4753                }
4754                // If the dependent is a static shared lib, use the public package name
4755                String dependentPackageName = ps.name;
4756                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4757                    dependentPackageName = ps.pkg.manifestPackageName;
4758                }
4759                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4760            } else if (ps.pkg != null) {
4761                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4762                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4763                    if (versionedPackages == null) {
4764                        versionedPackages = new ArrayList<>();
4765                    }
4766                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4767                }
4768            }
4769        }
4770
4771        return versionedPackages;
4772    }
4773
4774    @Override
4775    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4776        if (!sUserManager.exists(userId)) return null;
4777        final int callingUid = Binder.getCallingUid();
4778        flags = updateFlagsForComponent(flags, userId, component);
4779        enforceCrossUserPermission(callingUid, userId,
4780                false /* requireFullPermission */, false /* checkShell */, "get service info");
4781        synchronized (mPackages) {
4782            PackageParser.Service s = mServices.mServices.get(component);
4783            if (DEBUG_PACKAGE_INFO) Log.v(
4784                TAG, "getServiceInfo " + component + ": " + s);
4785            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4786                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4787                if (ps == null) return null;
4788                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4789                    return null;
4790                }
4791                return PackageParser.generateServiceInfo(
4792                        s, flags, ps.readUserState(userId), userId);
4793            }
4794        }
4795        return null;
4796    }
4797
4798    @Override
4799    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4800        if (!sUserManager.exists(userId)) return null;
4801        final int callingUid = Binder.getCallingUid();
4802        flags = updateFlagsForComponent(flags, userId, component);
4803        enforceCrossUserPermission(callingUid, userId,
4804                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4805        synchronized (mPackages) {
4806            PackageParser.Provider p = mProviders.mProviders.get(component);
4807            if (DEBUG_PACKAGE_INFO) Log.v(
4808                TAG, "getProviderInfo " + component + ": " + p);
4809            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4810                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4811                if (ps == null) return null;
4812                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4813                    return null;
4814                }
4815                return PackageParser.generateProviderInfo(
4816                        p, flags, ps.readUserState(userId), userId);
4817            }
4818        }
4819        return null;
4820    }
4821
4822    @Override
4823    public String[] getSystemSharedLibraryNames() {
4824        // allow instant applications
4825        synchronized (mPackages) {
4826            Set<String> libs = null;
4827            final int libCount = mSharedLibraries.size();
4828            for (int i = 0; i < libCount; i++) {
4829                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4830                if (versionedLib == null) {
4831                    continue;
4832                }
4833                final int versionCount = versionedLib.size();
4834                for (int j = 0; j < versionCount; j++) {
4835                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4836                    if (!libEntry.info.isStatic()) {
4837                        if (libs == null) {
4838                            libs = new ArraySet<>();
4839                        }
4840                        libs.add(libEntry.info.getName());
4841                        break;
4842                    }
4843                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4844                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4845                            UserHandle.getUserId(Binder.getCallingUid()),
4846                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4847                        if (libs == null) {
4848                            libs = new ArraySet<>();
4849                        }
4850                        libs.add(libEntry.info.getName());
4851                        break;
4852                    }
4853                }
4854            }
4855
4856            if (libs != null) {
4857                String[] libsArray = new String[libs.size()];
4858                libs.toArray(libsArray);
4859                return libsArray;
4860            }
4861
4862            return null;
4863        }
4864    }
4865
4866    @Override
4867    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4868        // allow instant applications
4869        synchronized (mPackages) {
4870            return mServicesSystemSharedLibraryPackageName;
4871        }
4872    }
4873
4874    @Override
4875    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4876        // allow instant applications
4877        synchronized (mPackages) {
4878            return mSharedSystemSharedLibraryPackageName;
4879        }
4880    }
4881
4882    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4883        for (int i = userList.length - 1; i >= 0; --i) {
4884            final int userId = userList[i];
4885            // don't add instant app to the list of updates
4886            if (pkgSetting.getInstantApp(userId)) {
4887                continue;
4888            }
4889            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4890            if (changedPackages == null) {
4891                changedPackages = new SparseArray<>();
4892                mChangedPackages.put(userId, changedPackages);
4893            }
4894            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4895            if (sequenceNumbers == null) {
4896                sequenceNumbers = new HashMap<>();
4897                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4898            }
4899            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4900            if (sequenceNumber != null) {
4901                changedPackages.remove(sequenceNumber);
4902            }
4903            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4904            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4905        }
4906        mChangedPackagesSequenceNumber++;
4907    }
4908
4909    @Override
4910    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4911        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4912            return null;
4913        }
4914        synchronized (mPackages) {
4915            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4916                return null;
4917            }
4918            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4919            if (changedPackages == null) {
4920                return null;
4921            }
4922            final List<String> packageNames =
4923                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4924            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4925                final String packageName = changedPackages.get(i);
4926                if (packageName != null) {
4927                    packageNames.add(packageName);
4928                }
4929            }
4930            return packageNames.isEmpty()
4931                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4932        }
4933    }
4934
4935    @Override
4936    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4937        // allow instant applications
4938        ArrayList<FeatureInfo> res;
4939        synchronized (mAvailableFeatures) {
4940            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4941            res.addAll(mAvailableFeatures.values());
4942        }
4943        final FeatureInfo fi = new FeatureInfo();
4944        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4945                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4946        res.add(fi);
4947
4948        return new ParceledListSlice<>(res);
4949    }
4950
4951    @Override
4952    public boolean hasSystemFeature(String name, int version) {
4953        // allow instant applications
4954        synchronized (mAvailableFeatures) {
4955            final FeatureInfo feat = mAvailableFeatures.get(name);
4956            if (feat == null) {
4957                return false;
4958            } else {
4959                return feat.version >= version;
4960            }
4961        }
4962    }
4963
4964    @Override
4965    public int checkPermission(String permName, String pkgName, int userId) {
4966        if (!sUserManager.exists(userId)) {
4967            return PackageManager.PERMISSION_DENIED;
4968        }
4969        final int callingUid = Binder.getCallingUid();
4970
4971        synchronized (mPackages) {
4972            final PackageParser.Package p = mPackages.get(pkgName);
4973            if (p != null && p.mExtras != null) {
4974                final PackageSetting ps = (PackageSetting) p.mExtras;
4975                if (filterAppAccessLPr(ps, callingUid, userId)) {
4976                    return PackageManager.PERMISSION_DENIED;
4977                }
4978                final boolean instantApp = ps.getInstantApp(userId);
4979                final PermissionsState permissionsState = ps.getPermissionsState();
4980                if (permissionsState.hasPermission(permName, userId)) {
4981                    if (instantApp) {
4982                        BasePermission bp = mSettings.mPermissions.get(permName);
4983                        if (bp != null && bp.isInstant()) {
4984                            return PackageManager.PERMISSION_GRANTED;
4985                        }
4986                    } else {
4987                        return PackageManager.PERMISSION_GRANTED;
4988                    }
4989                }
4990                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4991                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4992                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4993                    return PackageManager.PERMISSION_GRANTED;
4994                }
4995            }
4996        }
4997
4998        return PackageManager.PERMISSION_DENIED;
4999    }
5000
5001    @Override
5002    public int checkUidPermission(String permName, int uid) {
5003        final int callingUid = Binder.getCallingUid();
5004        final int callingUserId = UserHandle.getUserId(callingUid);
5005        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5006        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5007        final int userId = UserHandle.getUserId(uid);
5008        if (!sUserManager.exists(userId)) {
5009            return PackageManager.PERMISSION_DENIED;
5010        }
5011
5012        synchronized (mPackages) {
5013            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5014            if (obj != null) {
5015                if (obj instanceof SharedUserSetting) {
5016                    if (isCallerInstantApp) {
5017                        return PackageManager.PERMISSION_DENIED;
5018                    }
5019                } else if (obj instanceof PackageSetting) {
5020                    final PackageSetting ps = (PackageSetting) obj;
5021                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5022                        return PackageManager.PERMISSION_DENIED;
5023                    }
5024                }
5025                final SettingBase settingBase = (SettingBase) obj;
5026                final PermissionsState permissionsState = settingBase.getPermissionsState();
5027                if (permissionsState.hasPermission(permName, userId)) {
5028                    if (isUidInstantApp) {
5029                        BasePermission bp = mSettings.mPermissions.get(permName);
5030                        if (bp != null && bp.isInstant()) {
5031                            return PackageManager.PERMISSION_GRANTED;
5032                        }
5033                    } else {
5034                        return PackageManager.PERMISSION_GRANTED;
5035                    }
5036                }
5037                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5038                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5039                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5040                    return PackageManager.PERMISSION_GRANTED;
5041                }
5042            } else {
5043                ArraySet<String> perms = mSystemPermissions.get(uid);
5044                if (perms != null) {
5045                    if (perms.contains(permName)) {
5046                        return PackageManager.PERMISSION_GRANTED;
5047                    }
5048                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5049                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5050                        return PackageManager.PERMISSION_GRANTED;
5051                    }
5052                }
5053            }
5054        }
5055
5056        return PackageManager.PERMISSION_DENIED;
5057    }
5058
5059    @Override
5060    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5061        if (UserHandle.getCallingUserId() != userId) {
5062            mContext.enforceCallingPermission(
5063                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5064                    "isPermissionRevokedByPolicy for user " + userId);
5065        }
5066
5067        if (checkPermission(permission, packageName, userId)
5068                == PackageManager.PERMISSION_GRANTED) {
5069            return false;
5070        }
5071
5072        final int callingUid = Binder.getCallingUid();
5073        if (getInstantAppPackageName(callingUid) != null) {
5074            if (!isCallerSameApp(packageName, callingUid)) {
5075                return false;
5076            }
5077        } else {
5078            if (isInstantApp(packageName, userId)) {
5079                return false;
5080            }
5081        }
5082
5083        final long identity = Binder.clearCallingIdentity();
5084        try {
5085            final int flags = getPermissionFlags(permission, packageName, userId);
5086            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5087        } finally {
5088            Binder.restoreCallingIdentity(identity);
5089        }
5090    }
5091
5092    @Override
5093    public String getPermissionControllerPackageName() {
5094        synchronized (mPackages) {
5095            return mRequiredInstallerPackage;
5096        }
5097    }
5098
5099    /**
5100     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5101     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5102     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5103     * @param message the message to log on security exception
5104     */
5105    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5106            boolean checkShell, String message) {
5107        if (userId < 0) {
5108            throw new IllegalArgumentException("Invalid userId " + userId);
5109        }
5110        if (checkShell) {
5111            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5112        }
5113        if (userId == UserHandle.getUserId(callingUid)) return;
5114        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5115            if (requireFullPermission) {
5116                mContext.enforceCallingOrSelfPermission(
5117                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5118            } else {
5119                try {
5120                    mContext.enforceCallingOrSelfPermission(
5121                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5122                } catch (SecurityException se) {
5123                    mContext.enforceCallingOrSelfPermission(
5124                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5125                }
5126            }
5127        }
5128    }
5129
5130    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5131        if (callingUid == Process.SHELL_UID) {
5132            if (userHandle >= 0
5133                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5134                throw new SecurityException("Shell does not have permission to access user "
5135                        + userHandle);
5136            } else if (userHandle < 0) {
5137                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5138                        + Debug.getCallers(3));
5139            }
5140        }
5141    }
5142
5143    private BasePermission findPermissionTreeLP(String permName) {
5144        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5145            if (permName.startsWith(bp.name) &&
5146                    permName.length() > bp.name.length() &&
5147                    permName.charAt(bp.name.length()) == '.') {
5148                return bp;
5149            }
5150        }
5151        return null;
5152    }
5153
5154    private BasePermission checkPermissionTreeLP(String permName) {
5155        if (permName != null) {
5156            BasePermission bp = findPermissionTreeLP(permName);
5157            if (bp != null) {
5158                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5159                    return bp;
5160                }
5161                throw new SecurityException("Calling uid "
5162                        + Binder.getCallingUid()
5163                        + " is not allowed to add to permission tree "
5164                        + bp.name + " owned by uid " + bp.uid);
5165            }
5166        }
5167        throw new SecurityException("No permission tree found for " + permName);
5168    }
5169
5170    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5171        if (s1 == null) {
5172            return s2 == null;
5173        }
5174        if (s2 == null) {
5175            return false;
5176        }
5177        if (s1.getClass() != s2.getClass()) {
5178            return false;
5179        }
5180        return s1.equals(s2);
5181    }
5182
5183    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5184        if (pi1.icon != pi2.icon) return false;
5185        if (pi1.logo != pi2.logo) return false;
5186        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5187        if (!compareStrings(pi1.name, pi2.name)) return false;
5188        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5189        // We'll take care of setting this one.
5190        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5191        // These are not currently stored in settings.
5192        //if (!compareStrings(pi1.group, pi2.group)) return false;
5193        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5194        //if (pi1.labelRes != pi2.labelRes) return false;
5195        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5196        return true;
5197    }
5198
5199    int permissionInfoFootprint(PermissionInfo info) {
5200        int size = info.name.length();
5201        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5202        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5203        return size;
5204    }
5205
5206    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5207        int size = 0;
5208        for (BasePermission perm : mSettings.mPermissions.values()) {
5209            if (perm.uid == tree.uid) {
5210                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5211            }
5212        }
5213        return size;
5214    }
5215
5216    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5217        // We calculate the max size of permissions defined by this uid and throw
5218        // if that plus the size of 'info' would exceed our stated maximum.
5219        if (tree.uid != Process.SYSTEM_UID) {
5220            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5221            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5222                throw new SecurityException("Permission tree size cap exceeded");
5223            }
5224        }
5225    }
5226
5227    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5228        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5229            throw new SecurityException("Instant apps can't add permissions");
5230        }
5231        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5232            throw new SecurityException("Label must be specified in permission");
5233        }
5234        BasePermission tree = checkPermissionTreeLP(info.name);
5235        BasePermission bp = mSettings.mPermissions.get(info.name);
5236        boolean added = bp == null;
5237        boolean changed = true;
5238        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5239        if (added) {
5240            enforcePermissionCapLocked(info, tree);
5241            bp = new BasePermission(info.name, tree.sourcePackage,
5242                    BasePermission.TYPE_DYNAMIC);
5243        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5244            throw new SecurityException(
5245                    "Not allowed to modify non-dynamic permission "
5246                    + info.name);
5247        } else {
5248            if (bp.protectionLevel == fixedLevel
5249                    && bp.perm.owner.equals(tree.perm.owner)
5250                    && bp.uid == tree.uid
5251                    && comparePermissionInfos(bp.perm.info, info)) {
5252                changed = false;
5253            }
5254        }
5255        bp.protectionLevel = fixedLevel;
5256        info = new PermissionInfo(info);
5257        info.protectionLevel = fixedLevel;
5258        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5259        bp.perm.info.packageName = tree.perm.info.packageName;
5260        bp.uid = tree.uid;
5261        if (added) {
5262            mSettings.mPermissions.put(info.name, bp);
5263        }
5264        if (changed) {
5265            if (!async) {
5266                mSettings.writeLPr();
5267            } else {
5268                scheduleWriteSettingsLocked();
5269            }
5270        }
5271        return added;
5272    }
5273
5274    @Override
5275    public boolean addPermission(PermissionInfo info) {
5276        synchronized (mPackages) {
5277            return addPermissionLocked(info, false);
5278        }
5279    }
5280
5281    @Override
5282    public boolean addPermissionAsync(PermissionInfo info) {
5283        synchronized (mPackages) {
5284            return addPermissionLocked(info, true);
5285        }
5286    }
5287
5288    @Override
5289    public void removePermission(String name) {
5290        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5291            throw new SecurityException("Instant applications don't have access to this method");
5292        }
5293        synchronized (mPackages) {
5294            checkPermissionTreeLP(name);
5295            BasePermission bp = mSettings.mPermissions.get(name);
5296            if (bp != null) {
5297                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5298                    throw new SecurityException(
5299                            "Not allowed to modify non-dynamic permission "
5300                            + name);
5301                }
5302                mSettings.mPermissions.remove(name);
5303                mSettings.writeLPr();
5304            }
5305        }
5306    }
5307
5308    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5309            PackageParser.Package pkg, BasePermission bp) {
5310        int index = pkg.requestedPermissions.indexOf(bp.name);
5311        if (index == -1) {
5312            throw new SecurityException("Package " + pkg.packageName
5313                    + " has not requested permission " + bp.name);
5314        }
5315        if (!bp.isRuntime() && !bp.isDevelopment()) {
5316            throw new SecurityException("Permission " + bp.name
5317                    + " is not a changeable permission type");
5318        }
5319    }
5320
5321    @Override
5322    public void grantRuntimePermission(String packageName, String name, final int userId) {
5323        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5324    }
5325
5326    private void grantRuntimePermission(String packageName, String name, final int userId,
5327            boolean overridePolicy) {
5328        if (!sUserManager.exists(userId)) {
5329            Log.e(TAG, "No such user:" + userId);
5330            return;
5331        }
5332        final int callingUid = Binder.getCallingUid();
5333
5334        mContext.enforceCallingOrSelfPermission(
5335                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5336                "grantRuntimePermission");
5337
5338        enforceCrossUserPermission(callingUid, userId,
5339                true /* requireFullPermission */, true /* checkShell */,
5340                "grantRuntimePermission");
5341
5342        final int uid;
5343        final PackageSetting ps;
5344
5345        synchronized (mPackages) {
5346            final PackageParser.Package pkg = mPackages.get(packageName);
5347            if (pkg == null) {
5348                throw new IllegalArgumentException("Unknown package: " + packageName);
5349            }
5350            final BasePermission bp = mSettings.mPermissions.get(name);
5351            if (bp == null) {
5352                throw new IllegalArgumentException("Unknown permission: " + name);
5353            }
5354            ps = (PackageSetting) pkg.mExtras;
5355            if (ps == null
5356                    || filterAppAccessLPr(ps, callingUid, userId)) {
5357                throw new IllegalArgumentException("Unknown package: " + packageName);
5358            }
5359
5360            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5361
5362            // If a permission review is required for legacy apps we represent
5363            // their permissions as always granted runtime ones since we need
5364            // to keep the review required permission flag per user while an
5365            // install permission's state is shared across all users.
5366            if (mPermissionReviewRequired
5367                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5368                    && bp.isRuntime()) {
5369                return;
5370            }
5371
5372            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5373
5374            final PermissionsState permissionsState = ps.getPermissionsState();
5375
5376            final int flags = permissionsState.getPermissionFlags(name, userId);
5377            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5378                throw new SecurityException("Cannot grant system fixed permission "
5379                        + name + " for package " + packageName);
5380            }
5381            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5382                throw new SecurityException("Cannot grant policy fixed permission "
5383                        + name + " for package " + packageName);
5384            }
5385
5386            if (bp.isDevelopment()) {
5387                // Development permissions must be handled specially, since they are not
5388                // normal runtime permissions.  For now they apply to all users.
5389                if (permissionsState.grantInstallPermission(bp) !=
5390                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5391                    scheduleWriteSettingsLocked();
5392                }
5393                return;
5394            }
5395
5396            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5397                throw new SecurityException("Cannot grant non-ephemeral permission"
5398                        + name + " for package " + packageName);
5399            }
5400
5401            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5402                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5403                return;
5404            }
5405
5406            final int result = permissionsState.grantRuntimePermission(bp, userId);
5407            switch (result) {
5408                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5409                    return;
5410                }
5411
5412                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5413                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5414                    mHandler.post(new Runnable() {
5415                        @Override
5416                        public void run() {
5417                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5418                        }
5419                    });
5420                }
5421                break;
5422            }
5423
5424            if (bp.isRuntime()) {
5425                logPermissionGranted(mContext, name, packageName);
5426            }
5427
5428            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5429
5430            // Not critical if that is lost - app has to request again.
5431            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5432        }
5433
5434        // Only need to do this if user is initialized. Otherwise it's a new user
5435        // and there are no processes running as the user yet and there's no need
5436        // to make an expensive call to remount processes for the changed permissions.
5437        if (READ_EXTERNAL_STORAGE.equals(name)
5438                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5439            final long token = Binder.clearCallingIdentity();
5440            try {
5441                if (sUserManager.isInitialized(userId)) {
5442                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5443                            StorageManagerInternal.class);
5444                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5445                }
5446            } finally {
5447                Binder.restoreCallingIdentity(token);
5448            }
5449        }
5450    }
5451
5452    @Override
5453    public void revokeRuntimePermission(String packageName, String name, int userId) {
5454        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5455    }
5456
5457    private void revokeRuntimePermission(String packageName, String name, int userId,
5458            boolean overridePolicy) {
5459        if (!sUserManager.exists(userId)) {
5460            Log.e(TAG, "No such user:" + userId);
5461            return;
5462        }
5463
5464        mContext.enforceCallingOrSelfPermission(
5465                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5466                "revokeRuntimePermission");
5467
5468        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5469                true /* requireFullPermission */, true /* checkShell */,
5470                "revokeRuntimePermission");
5471
5472        final int appId;
5473
5474        synchronized (mPackages) {
5475            final PackageParser.Package pkg = mPackages.get(packageName);
5476            if (pkg == null) {
5477                throw new IllegalArgumentException("Unknown package: " + packageName);
5478            }
5479            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5480            if (ps == null
5481                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5482                throw new IllegalArgumentException("Unknown package: " + packageName);
5483            }
5484            final BasePermission bp = mSettings.mPermissions.get(name);
5485            if (bp == null) {
5486                throw new IllegalArgumentException("Unknown permission: " + name);
5487            }
5488
5489            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5490
5491            // If a permission review is required for legacy apps we represent
5492            // their permissions as always granted runtime ones since we need
5493            // to keep the review required permission flag per user while an
5494            // install permission's state is shared across all users.
5495            if (mPermissionReviewRequired
5496                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5497                    && bp.isRuntime()) {
5498                return;
5499            }
5500
5501            final PermissionsState permissionsState = ps.getPermissionsState();
5502
5503            final int flags = permissionsState.getPermissionFlags(name, userId);
5504            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5505                throw new SecurityException("Cannot revoke system fixed permission "
5506                        + name + " for package " + packageName);
5507            }
5508            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5509                throw new SecurityException("Cannot revoke policy fixed permission "
5510                        + name + " for package " + packageName);
5511            }
5512
5513            if (bp.isDevelopment()) {
5514                // Development permissions must be handled specially, since they are not
5515                // normal runtime permissions.  For now they apply to all users.
5516                if (permissionsState.revokeInstallPermission(bp) !=
5517                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5518                    scheduleWriteSettingsLocked();
5519                }
5520                return;
5521            }
5522
5523            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5524                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5525                return;
5526            }
5527
5528            if (bp.isRuntime()) {
5529                logPermissionRevoked(mContext, name, packageName);
5530            }
5531
5532            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5533
5534            // Critical, after this call app should never have the permission.
5535            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5536
5537            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5538        }
5539
5540        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5541    }
5542
5543    /**
5544     * Get the first event id for the permission.
5545     *
5546     * <p>There are four events for each permission: <ul>
5547     *     <li>Request permission: first id + 0</li>
5548     *     <li>Grant permission: first id + 1</li>
5549     *     <li>Request for permission denied: first id + 2</li>
5550     *     <li>Revoke permission: first id + 3</li>
5551     * </ul></p>
5552     *
5553     * @param name name of the permission
5554     *
5555     * @return The first event id for the permission
5556     */
5557    private static int getBaseEventId(@NonNull String name) {
5558        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5559
5560        if (eventIdIndex == -1) {
5561            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5562                    || Build.IS_USER) {
5563                Log.i(TAG, "Unknown permission " + name);
5564
5565                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5566            } else {
5567                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5568                //
5569                // Also update
5570                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5571                // - metrics_constants.proto
5572                throw new IllegalStateException("Unknown permission " + name);
5573            }
5574        }
5575
5576        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5577    }
5578
5579    /**
5580     * Log that a permission was revoked.
5581     *
5582     * @param context Context of the caller
5583     * @param name name of the permission
5584     * @param packageName package permission if for
5585     */
5586    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5587            @NonNull String packageName) {
5588        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5589    }
5590
5591    /**
5592     * Log that a permission request was granted.
5593     *
5594     * @param context Context of the caller
5595     * @param name name of the permission
5596     * @param packageName package permission if for
5597     */
5598    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5599            @NonNull String packageName) {
5600        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5601    }
5602
5603    @Override
5604    public void resetRuntimePermissions() {
5605        mContext.enforceCallingOrSelfPermission(
5606                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5607                "revokeRuntimePermission");
5608
5609        int callingUid = Binder.getCallingUid();
5610        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5611            mContext.enforceCallingOrSelfPermission(
5612                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5613                    "resetRuntimePermissions");
5614        }
5615
5616        synchronized (mPackages) {
5617            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5618            for (int userId : UserManagerService.getInstance().getUserIds()) {
5619                final int packageCount = mPackages.size();
5620                for (int i = 0; i < packageCount; i++) {
5621                    PackageParser.Package pkg = mPackages.valueAt(i);
5622                    if (!(pkg.mExtras instanceof PackageSetting)) {
5623                        continue;
5624                    }
5625                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5626                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5627                }
5628            }
5629        }
5630    }
5631
5632    @Override
5633    public int getPermissionFlags(String name, String packageName, int userId) {
5634        if (!sUserManager.exists(userId)) {
5635            return 0;
5636        }
5637
5638        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5639
5640        final int callingUid = Binder.getCallingUid();
5641        enforceCrossUserPermission(callingUid, userId,
5642                true /* requireFullPermission */, false /* checkShell */,
5643                "getPermissionFlags");
5644
5645        synchronized (mPackages) {
5646            final PackageParser.Package pkg = mPackages.get(packageName);
5647            if (pkg == null) {
5648                return 0;
5649            }
5650            final BasePermission bp = mSettings.mPermissions.get(name);
5651            if (bp == null) {
5652                return 0;
5653            }
5654            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5655            if (ps == null
5656                    || filterAppAccessLPr(ps, callingUid, userId)) {
5657                return 0;
5658            }
5659            PermissionsState permissionsState = ps.getPermissionsState();
5660            return permissionsState.getPermissionFlags(name, userId);
5661        }
5662    }
5663
5664    @Override
5665    public void updatePermissionFlags(String name, String packageName, int flagMask,
5666            int flagValues, int userId) {
5667        if (!sUserManager.exists(userId)) {
5668            return;
5669        }
5670
5671        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5672
5673        final int callingUid = Binder.getCallingUid();
5674        enforceCrossUserPermission(callingUid, userId,
5675                true /* requireFullPermission */, true /* checkShell */,
5676                "updatePermissionFlags");
5677
5678        // Only the system can change these flags and nothing else.
5679        if (getCallingUid() != Process.SYSTEM_UID) {
5680            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5681            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5682            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5683            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5684            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5685        }
5686
5687        synchronized (mPackages) {
5688            final PackageParser.Package pkg = mPackages.get(packageName);
5689            if (pkg == null) {
5690                throw new IllegalArgumentException("Unknown package: " + packageName);
5691            }
5692            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5693            if (ps == null
5694                    || filterAppAccessLPr(ps, callingUid, userId)) {
5695                throw new IllegalArgumentException("Unknown package: " + packageName);
5696            }
5697
5698            final BasePermission bp = mSettings.mPermissions.get(name);
5699            if (bp == null) {
5700                throw new IllegalArgumentException("Unknown permission: " + name);
5701            }
5702
5703            PermissionsState permissionsState = ps.getPermissionsState();
5704
5705            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5706
5707            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5708                // Install and runtime permissions are stored in different places,
5709                // so figure out what permission changed and persist the change.
5710                if (permissionsState.getInstallPermissionState(name) != null) {
5711                    scheduleWriteSettingsLocked();
5712                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5713                        || hadState) {
5714                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5715                }
5716            }
5717        }
5718    }
5719
5720    /**
5721     * Update the permission flags for all packages and runtime permissions of a user in order
5722     * to allow device or profile owner to remove POLICY_FIXED.
5723     */
5724    @Override
5725    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5726        if (!sUserManager.exists(userId)) {
5727            return;
5728        }
5729
5730        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5731
5732        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5733                true /* requireFullPermission */, true /* checkShell */,
5734                "updatePermissionFlagsForAllApps");
5735
5736        // Only the system can change system fixed flags.
5737        if (getCallingUid() != Process.SYSTEM_UID) {
5738            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5739            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5740        }
5741
5742        synchronized (mPackages) {
5743            boolean changed = false;
5744            final int packageCount = mPackages.size();
5745            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5746                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5747                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5748                if (ps == null) {
5749                    continue;
5750                }
5751                PermissionsState permissionsState = ps.getPermissionsState();
5752                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5753                        userId, flagMask, flagValues);
5754            }
5755            if (changed) {
5756                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5757            }
5758        }
5759    }
5760
5761    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5762        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5763                != PackageManager.PERMISSION_GRANTED
5764            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5765                != PackageManager.PERMISSION_GRANTED) {
5766            throw new SecurityException(message + " requires "
5767                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5768                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5769        }
5770    }
5771
5772    @Override
5773    public boolean shouldShowRequestPermissionRationale(String permissionName,
5774            String packageName, int userId) {
5775        if (UserHandle.getCallingUserId() != userId) {
5776            mContext.enforceCallingPermission(
5777                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5778                    "canShowRequestPermissionRationale for user " + userId);
5779        }
5780
5781        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5782        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5783            return false;
5784        }
5785
5786        if (checkPermission(permissionName, packageName, userId)
5787                == PackageManager.PERMISSION_GRANTED) {
5788            return false;
5789        }
5790
5791        final int flags;
5792
5793        final long identity = Binder.clearCallingIdentity();
5794        try {
5795            flags = getPermissionFlags(permissionName,
5796                    packageName, userId);
5797        } finally {
5798            Binder.restoreCallingIdentity(identity);
5799        }
5800
5801        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5802                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5803                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5804
5805        if ((flags & fixedFlags) != 0) {
5806            return false;
5807        }
5808
5809        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5810    }
5811
5812    @Override
5813    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5814        mContext.enforceCallingOrSelfPermission(
5815                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5816                "addOnPermissionsChangeListener");
5817
5818        synchronized (mPackages) {
5819            mOnPermissionChangeListeners.addListenerLocked(listener);
5820        }
5821    }
5822
5823    @Override
5824    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5825        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5826            throw new SecurityException("Instant applications don't have access to this method");
5827        }
5828        synchronized (mPackages) {
5829            mOnPermissionChangeListeners.removeListenerLocked(listener);
5830        }
5831    }
5832
5833    @Override
5834    public boolean isProtectedBroadcast(String actionName) {
5835        // allow instant applications
5836        synchronized (mProtectedBroadcasts) {
5837            if (mProtectedBroadcasts.contains(actionName)) {
5838                return true;
5839            } else if (actionName != null) {
5840                // TODO: remove these terrible hacks
5841                if (actionName.startsWith("android.net.netmon.lingerExpired")
5842                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5843                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5844                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5845                    return true;
5846                }
5847            }
5848        }
5849        return false;
5850    }
5851
5852    @Override
5853    public int checkSignatures(String pkg1, String pkg2) {
5854        synchronized (mPackages) {
5855            final PackageParser.Package p1 = mPackages.get(pkg1);
5856            final PackageParser.Package p2 = mPackages.get(pkg2);
5857            if (p1 == null || p1.mExtras == null
5858                    || p2 == null || p2.mExtras == null) {
5859                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5860            }
5861            final int callingUid = Binder.getCallingUid();
5862            final int callingUserId = UserHandle.getUserId(callingUid);
5863            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5864            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5865            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5866                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5867                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5868            }
5869            return compareSignatures(p1.mSignatures, p2.mSignatures);
5870        }
5871    }
5872
5873    @Override
5874    public int checkUidSignatures(int uid1, int uid2) {
5875        final int callingUid = Binder.getCallingUid();
5876        final int callingUserId = UserHandle.getUserId(callingUid);
5877        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5878        // Map to base uids.
5879        uid1 = UserHandle.getAppId(uid1);
5880        uid2 = UserHandle.getAppId(uid2);
5881        // reader
5882        synchronized (mPackages) {
5883            Signature[] s1;
5884            Signature[] s2;
5885            Object obj = mSettings.getUserIdLPr(uid1);
5886            if (obj != null) {
5887                if (obj instanceof SharedUserSetting) {
5888                    if (isCallerInstantApp) {
5889                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5890                    }
5891                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5892                } else if (obj instanceof PackageSetting) {
5893                    final PackageSetting ps = (PackageSetting) obj;
5894                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5895                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5896                    }
5897                    s1 = ps.signatures.mSignatures;
5898                } else {
5899                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5900                }
5901            } else {
5902                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5903            }
5904            obj = mSettings.getUserIdLPr(uid2);
5905            if (obj != null) {
5906                if (obj instanceof SharedUserSetting) {
5907                    if (isCallerInstantApp) {
5908                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5909                    }
5910                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5911                } else if (obj instanceof PackageSetting) {
5912                    final PackageSetting ps = (PackageSetting) obj;
5913                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5914                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5915                    }
5916                    s2 = ps.signatures.mSignatures;
5917                } else {
5918                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5919                }
5920            } else {
5921                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5922            }
5923            return compareSignatures(s1, s2);
5924        }
5925    }
5926
5927    /**
5928     * This method should typically only be used when granting or revoking
5929     * permissions, since the app may immediately restart after this call.
5930     * <p>
5931     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5932     * guard your work against the app being relaunched.
5933     */
5934    private void killUid(int appId, int userId, String reason) {
5935        final long identity = Binder.clearCallingIdentity();
5936        try {
5937            IActivityManager am = ActivityManager.getService();
5938            if (am != null) {
5939                try {
5940                    am.killUid(appId, userId, reason);
5941                } catch (RemoteException e) {
5942                    /* ignore - same process */
5943                }
5944            }
5945        } finally {
5946            Binder.restoreCallingIdentity(identity);
5947        }
5948    }
5949
5950    /**
5951     * Compares two sets of signatures. Returns:
5952     * <br />
5953     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5954     * <br />
5955     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5956     * <br />
5957     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5958     * <br />
5959     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5960     * <br />
5961     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5962     */
5963    static int compareSignatures(Signature[] s1, Signature[] s2) {
5964        if (s1 == null) {
5965            return s2 == null
5966                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5967                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5968        }
5969
5970        if (s2 == null) {
5971            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5972        }
5973
5974        if (s1.length != s2.length) {
5975            return PackageManager.SIGNATURE_NO_MATCH;
5976        }
5977
5978        // Since both signature sets are of size 1, we can compare without HashSets.
5979        if (s1.length == 1) {
5980            return s1[0].equals(s2[0]) ?
5981                    PackageManager.SIGNATURE_MATCH :
5982                    PackageManager.SIGNATURE_NO_MATCH;
5983        }
5984
5985        ArraySet<Signature> set1 = new ArraySet<Signature>();
5986        for (Signature sig : s1) {
5987            set1.add(sig);
5988        }
5989        ArraySet<Signature> set2 = new ArraySet<Signature>();
5990        for (Signature sig : s2) {
5991            set2.add(sig);
5992        }
5993        // Make sure s2 contains all signatures in s1.
5994        if (set1.equals(set2)) {
5995            return PackageManager.SIGNATURE_MATCH;
5996        }
5997        return PackageManager.SIGNATURE_NO_MATCH;
5998    }
5999
6000    /**
6001     * If the database version for this type of package (internal storage or
6002     * external storage) is less than the version where package signatures
6003     * were updated, return true.
6004     */
6005    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6006        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6007        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6008    }
6009
6010    /**
6011     * Used for backward compatibility to make sure any packages with
6012     * certificate chains get upgraded to the new style. {@code existingSigs}
6013     * will be in the old format (since they were stored on disk from before the
6014     * system upgrade) and {@code scannedSigs} will be in the newer format.
6015     */
6016    private int compareSignaturesCompat(PackageSignatures existingSigs,
6017            PackageParser.Package scannedPkg) {
6018        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6019            return PackageManager.SIGNATURE_NO_MATCH;
6020        }
6021
6022        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6023        for (Signature sig : existingSigs.mSignatures) {
6024            existingSet.add(sig);
6025        }
6026        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6027        for (Signature sig : scannedPkg.mSignatures) {
6028            try {
6029                Signature[] chainSignatures = sig.getChainSignatures();
6030                for (Signature chainSig : chainSignatures) {
6031                    scannedCompatSet.add(chainSig);
6032                }
6033            } catch (CertificateEncodingException e) {
6034                scannedCompatSet.add(sig);
6035            }
6036        }
6037        /*
6038         * Make sure the expanded scanned set contains all signatures in the
6039         * existing one.
6040         */
6041        if (scannedCompatSet.equals(existingSet)) {
6042            // Migrate the old signatures to the new scheme.
6043            existingSigs.assignSignatures(scannedPkg.mSignatures);
6044            // The new KeySets will be re-added later in the scanning process.
6045            synchronized (mPackages) {
6046                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6047            }
6048            return PackageManager.SIGNATURE_MATCH;
6049        }
6050        return PackageManager.SIGNATURE_NO_MATCH;
6051    }
6052
6053    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6054        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6055        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6056    }
6057
6058    private int compareSignaturesRecover(PackageSignatures existingSigs,
6059            PackageParser.Package scannedPkg) {
6060        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6061            return PackageManager.SIGNATURE_NO_MATCH;
6062        }
6063
6064        String msg = null;
6065        try {
6066            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6067                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6068                        + scannedPkg.packageName);
6069                return PackageManager.SIGNATURE_MATCH;
6070            }
6071        } catch (CertificateException e) {
6072            msg = e.getMessage();
6073        }
6074
6075        logCriticalInfo(Log.INFO,
6076                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6077        return PackageManager.SIGNATURE_NO_MATCH;
6078    }
6079
6080    @Override
6081    public List<String> getAllPackages() {
6082        final int callingUid = Binder.getCallingUid();
6083        final int callingUserId = UserHandle.getUserId(callingUid);
6084        synchronized (mPackages) {
6085            if (canViewInstantApps(callingUid, callingUserId)) {
6086                return new ArrayList<String>(mPackages.keySet());
6087            }
6088            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6089            final List<String> result = new ArrayList<>();
6090            if (instantAppPkgName != null) {
6091                // caller is an instant application; filter unexposed applications
6092                for (PackageParser.Package pkg : mPackages.values()) {
6093                    if (!pkg.visibleToInstantApps) {
6094                        continue;
6095                    }
6096                    result.add(pkg.packageName);
6097                }
6098            } else {
6099                // caller is a normal application; filter instant applications
6100                for (PackageParser.Package pkg : mPackages.values()) {
6101                    final PackageSetting ps =
6102                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6103                    if (ps != null
6104                            && ps.getInstantApp(callingUserId)
6105                            && !mInstantAppRegistry.isInstantAccessGranted(
6106                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6107                        continue;
6108                    }
6109                    result.add(pkg.packageName);
6110                }
6111            }
6112            return result;
6113        }
6114    }
6115
6116    @Override
6117    public String[] getPackagesForUid(int uid) {
6118        final int callingUid = Binder.getCallingUid();
6119        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6120        final int userId = UserHandle.getUserId(uid);
6121        uid = UserHandle.getAppId(uid);
6122        // reader
6123        synchronized (mPackages) {
6124            Object obj = mSettings.getUserIdLPr(uid);
6125            if (obj instanceof SharedUserSetting) {
6126                if (isCallerInstantApp) {
6127                    return null;
6128                }
6129                final SharedUserSetting sus = (SharedUserSetting) obj;
6130                final int N = sus.packages.size();
6131                String[] res = new String[N];
6132                final Iterator<PackageSetting> it = sus.packages.iterator();
6133                int i = 0;
6134                while (it.hasNext()) {
6135                    PackageSetting ps = it.next();
6136                    if (ps.getInstalled(userId)) {
6137                        res[i++] = ps.name;
6138                    } else {
6139                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6140                    }
6141                }
6142                return res;
6143            } else if (obj instanceof PackageSetting) {
6144                final PackageSetting ps = (PackageSetting) obj;
6145                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6146                    return new String[]{ps.name};
6147                }
6148            }
6149        }
6150        return null;
6151    }
6152
6153    @Override
6154    public String getNameForUid(int uid) {
6155        final int callingUid = Binder.getCallingUid();
6156        if (getInstantAppPackageName(callingUid) != null) {
6157            return null;
6158        }
6159        synchronized (mPackages) {
6160            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6161            if (obj instanceof SharedUserSetting) {
6162                final SharedUserSetting sus = (SharedUserSetting) obj;
6163                return sus.name + ":" + sus.userId;
6164            } else if (obj instanceof PackageSetting) {
6165                final PackageSetting ps = (PackageSetting) obj;
6166                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6167                    return null;
6168                }
6169                return ps.name;
6170            }
6171        }
6172        return null;
6173    }
6174
6175    @Override
6176    public int getUidForSharedUser(String sharedUserName) {
6177        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6178            return -1;
6179        }
6180        if (sharedUserName == null) {
6181            return -1;
6182        }
6183        // reader
6184        synchronized (mPackages) {
6185            SharedUserSetting suid;
6186            try {
6187                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6188                if (suid != null) {
6189                    return suid.userId;
6190                }
6191            } catch (PackageManagerException ignore) {
6192                // can't happen, but, still need to catch it
6193            }
6194            return -1;
6195        }
6196    }
6197
6198    @Override
6199    public int getFlagsForUid(int uid) {
6200        final int callingUid = Binder.getCallingUid();
6201        if (getInstantAppPackageName(callingUid) != null) {
6202            return 0;
6203        }
6204        synchronized (mPackages) {
6205            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6206            if (obj instanceof SharedUserSetting) {
6207                final SharedUserSetting sus = (SharedUserSetting) obj;
6208                return sus.pkgFlags;
6209            } else if (obj instanceof PackageSetting) {
6210                final PackageSetting ps = (PackageSetting) obj;
6211                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6212                    return 0;
6213                }
6214                return ps.pkgFlags;
6215            }
6216        }
6217        return 0;
6218    }
6219
6220    @Override
6221    public int getPrivateFlagsForUid(int uid) {
6222        final int callingUid = Binder.getCallingUid();
6223        if (getInstantAppPackageName(callingUid) != null) {
6224            return 0;
6225        }
6226        synchronized (mPackages) {
6227            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6228            if (obj instanceof SharedUserSetting) {
6229                final SharedUserSetting sus = (SharedUserSetting) obj;
6230                return sus.pkgPrivateFlags;
6231            } else if (obj instanceof PackageSetting) {
6232                final PackageSetting ps = (PackageSetting) obj;
6233                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6234                    return 0;
6235                }
6236                return ps.pkgPrivateFlags;
6237            }
6238        }
6239        return 0;
6240    }
6241
6242    @Override
6243    public boolean isUidPrivileged(int uid) {
6244        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6245            return false;
6246        }
6247        uid = UserHandle.getAppId(uid);
6248        // reader
6249        synchronized (mPackages) {
6250            Object obj = mSettings.getUserIdLPr(uid);
6251            if (obj instanceof SharedUserSetting) {
6252                final SharedUserSetting sus = (SharedUserSetting) obj;
6253                final Iterator<PackageSetting> it = sus.packages.iterator();
6254                while (it.hasNext()) {
6255                    if (it.next().isPrivileged()) {
6256                        return true;
6257                    }
6258                }
6259            } else if (obj instanceof PackageSetting) {
6260                final PackageSetting ps = (PackageSetting) obj;
6261                return ps.isPrivileged();
6262            }
6263        }
6264        return false;
6265    }
6266
6267    @Override
6268    public String[] getAppOpPermissionPackages(String permissionName) {
6269        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6270            return null;
6271        }
6272        synchronized (mPackages) {
6273            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6274            if (pkgs == null) {
6275                return null;
6276            }
6277            return pkgs.toArray(new String[pkgs.size()]);
6278        }
6279    }
6280
6281    @Override
6282    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6283            int flags, int userId) {
6284        return resolveIntentInternal(
6285                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6286    }
6287
6288    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6289            int flags, int userId, boolean resolveForStart) {
6290        try {
6291            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6292
6293            if (!sUserManager.exists(userId)) return null;
6294            final int callingUid = Binder.getCallingUid();
6295            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6296            enforceCrossUserPermission(callingUid, userId,
6297                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6298
6299            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6300            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6301                    flags, callingUid, userId, resolveForStart);
6302            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6303
6304            final ResolveInfo bestChoice =
6305                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6306            return bestChoice;
6307        } finally {
6308            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6309        }
6310    }
6311
6312    @Override
6313    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6314        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6315            throw new SecurityException(
6316                    "findPersistentPreferredActivity can only be run by the system");
6317        }
6318        if (!sUserManager.exists(userId)) {
6319            return null;
6320        }
6321        final int callingUid = Binder.getCallingUid();
6322        intent = updateIntentForResolve(intent);
6323        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6324        final int flags = updateFlagsForResolve(
6325                0, userId, intent, callingUid, false /*includeInstantApps*/);
6326        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6327                userId);
6328        synchronized (mPackages) {
6329            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6330                    userId);
6331        }
6332    }
6333
6334    @Override
6335    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6336            IntentFilter filter, int match, ComponentName activity) {
6337        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6338            return;
6339        }
6340        final int userId = UserHandle.getCallingUserId();
6341        if (DEBUG_PREFERRED) {
6342            Log.v(TAG, "setLastChosenActivity intent=" + intent
6343                + " resolvedType=" + resolvedType
6344                + " flags=" + flags
6345                + " filter=" + filter
6346                + " match=" + match
6347                + " activity=" + activity);
6348            filter.dump(new PrintStreamPrinter(System.out), "    ");
6349        }
6350        intent.setComponent(null);
6351        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6352                userId);
6353        // Find any earlier preferred or last chosen entries and nuke them
6354        findPreferredActivity(intent, resolvedType,
6355                flags, query, 0, false, true, false, userId);
6356        // Add the new activity as the last chosen for this filter
6357        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6358                "Setting last chosen");
6359    }
6360
6361    @Override
6362    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6363        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6364            return null;
6365        }
6366        final int userId = UserHandle.getCallingUserId();
6367        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6368        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6369                userId);
6370        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6371                false, false, false, userId);
6372    }
6373
6374    /**
6375     * Returns whether or not instant apps have been disabled remotely.
6376     */
6377    private boolean isEphemeralDisabled() {
6378        return mEphemeralAppsDisabled;
6379    }
6380
6381    private boolean isInstantAppAllowed(
6382            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6383            boolean skipPackageCheck) {
6384        if (mInstantAppResolverConnection == null) {
6385            return false;
6386        }
6387        if (mInstantAppInstallerActivity == null) {
6388            return false;
6389        }
6390        if (intent.getComponent() != null) {
6391            return false;
6392        }
6393        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6394            return false;
6395        }
6396        if (!skipPackageCheck && intent.getPackage() != null) {
6397            return false;
6398        }
6399        final boolean isWebUri = hasWebURI(intent);
6400        if (!isWebUri || intent.getData().getHost() == null) {
6401            return false;
6402        }
6403        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6404        // Or if there's already an ephemeral app installed that handles the action
6405        synchronized (mPackages) {
6406            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6407            for (int n = 0; n < count; n++) {
6408                final ResolveInfo info = resolvedActivities.get(n);
6409                final String packageName = info.activityInfo.packageName;
6410                final PackageSetting ps = mSettings.mPackages.get(packageName);
6411                if (ps != null) {
6412                    // only check domain verification status if the app is not a browser
6413                    if (!info.handleAllWebDataURI) {
6414                        // Try to get the status from User settings first
6415                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6416                        final int status = (int) (packedStatus >> 32);
6417                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6418                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6419                            if (DEBUG_EPHEMERAL) {
6420                                Slog.v(TAG, "DENY instant app;"
6421                                    + " pkg: " + packageName + ", status: " + status);
6422                            }
6423                            return false;
6424                        }
6425                    }
6426                    if (ps.getInstantApp(userId)) {
6427                        if (DEBUG_EPHEMERAL) {
6428                            Slog.v(TAG, "DENY instant app installed;"
6429                                    + " pkg: " + packageName);
6430                        }
6431                        return false;
6432                    }
6433                }
6434            }
6435        }
6436        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6437        return true;
6438    }
6439
6440    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6441            Intent origIntent, String resolvedType, String callingPackage,
6442            Bundle verificationBundle, int userId) {
6443        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6444                new InstantAppRequest(responseObj, origIntent, resolvedType,
6445                        callingPackage, userId, verificationBundle));
6446        mHandler.sendMessage(msg);
6447    }
6448
6449    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6450            int flags, List<ResolveInfo> query, int userId) {
6451        if (query != null) {
6452            final int N = query.size();
6453            if (N == 1) {
6454                return query.get(0);
6455            } else if (N > 1) {
6456                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6457                // If there is more than one activity with the same priority,
6458                // then let the user decide between them.
6459                ResolveInfo r0 = query.get(0);
6460                ResolveInfo r1 = query.get(1);
6461                if (DEBUG_INTENT_MATCHING || debug) {
6462                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6463                            + r1.activityInfo.name + "=" + r1.priority);
6464                }
6465                // If the first activity has a higher priority, or a different
6466                // default, then it is always desirable to pick it.
6467                if (r0.priority != r1.priority
6468                        || r0.preferredOrder != r1.preferredOrder
6469                        || r0.isDefault != r1.isDefault) {
6470                    return query.get(0);
6471                }
6472                // If we have saved a preference for a preferred activity for
6473                // this Intent, use that.
6474                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6475                        flags, query, r0.priority, true, false, debug, userId);
6476                if (ri != null) {
6477                    return ri;
6478                }
6479                // If we have an ephemeral app, use it
6480                for (int i = 0; i < N; i++) {
6481                    ri = query.get(i);
6482                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6483                        final String packageName = ri.activityInfo.packageName;
6484                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6485                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6486                        final int status = (int)(packedStatus >> 32);
6487                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6488                            return ri;
6489                        }
6490                    }
6491                }
6492                ri = new ResolveInfo(mResolveInfo);
6493                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6494                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6495                // If all of the options come from the same package, show the application's
6496                // label and icon instead of the generic resolver's.
6497                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6498                // and then throw away the ResolveInfo itself, meaning that the caller loses
6499                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6500                // a fallback for this case; we only set the target package's resources on
6501                // the ResolveInfo, not the ActivityInfo.
6502                final String intentPackage = intent.getPackage();
6503                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6504                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6505                    ri.resolvePackageName = intentPackage;
6506                    if (userNeedsBadging(userId)) {
6507                        ri.noResourceId = true;
6508                    } else {
6509                        ri.icon = appi.icon;
6510                    }
6511                    ri.iconResourceId = appi.icon;
6512                    ri.labelRes = appi.labelRes;
6513                }
6514                ri.activityInfo.applicationInfo = new ApplicationInfo(
6515                        ri.activityInfo.applicationInfo);
6516                if (userId != 0) {
6517                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6518                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6519                }
6520                // Make sure that the resolver is displayable in car mode
6521                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6522                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6523                return ri;
6524            }
6525        }
6526        return null;
6527    }
6528
6529    /**
6530     * Return true if the given list is not empty and all of its contents have
6531     * an activityInfo with the given package name.
6532     */
6533    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6534        if (ArrayUtils.isEmpty(list)) {
6535            return false;
6536        }
6537        for (int i = 0, N = list.size(); i < N; i++) {
6538            final ResolveInfo ri = list.get(i);
6539            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6540            if (ai == null || !packageName.equals(ai.packageName)) {
6541                return false;
6542            }
6543        }
6544        return true;
6545    }
6546
6547    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6548            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6549        final int N = query.size();
6550        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6551                .get(userId);
6552        // Get the list of persistent preferred activities that handle the intent
6553        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6554        List<PersistentPreferredActivity> pprefs = ppir != null
6555                ? ppir.queryIntent(intent, resolvedType,
6556                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6557                        userId)
6558                : null;
6559        if (pprefs != null && pprefs.size() > 0) {
6560            final int M = pprefs.size();
6561            for (int i=0; i<M; i++) {
6562                final PersistentPreferredActivity ppa = pprefs.get(i);
6563                if (DEBUG_PREFERRED || debug) {
6564                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6565                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6566                            + "\n  component=" + ppa.mComponent);
6567                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6568                }
6569                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6570                        flags | MATCH_DISABLED_COMPONENTS, userId);
6571                if (DEBUG_PREFERRED || debug) {
6572                    Slog.v(TAG, "Found persistent preferred activity:");
6573                    if (ai != null) {
6574                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6575                    } else {
6576                        Slog.v(TAG, "  null");
6577                    }
6578                }
6579                if (ai == null) {
6580                    // This previously registered persistent preferred activity
6581                    // component is no longer known. Ignore it and do NOT remove it.
6582                    continue;
6583                }
6584                for (int j=0; j<N; j++) {
6585                    final ResolveInfo ri = query.get(j);
6586                    if (!ri.activityInfo.applicationInfo.packageName
6587                            .equals(ai.applicationInfo.packageName)) {
6588                        continue;
6589                    }
6590                    if (!ri.activityInfo.name.equals(ai.name)) {
6591                        continue;
6592                    }
6593                    //  Found a persistent preference that can handle the intent.
6594                    if (DEBUG_PREFERRED || debug) {
6595                        Slog.v(TAG, "Returning persistent preferred activity: " +
6596                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6597                    }
6598                    return ri;
6599                }
6600            }
6601        }
6602        return null;
6603    }
6604
6605    // TODO: handle preferred activities missing while user has amnesia
6606    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6607            List<ResolveInfo> query, int priority, boolean always,
6608            boolean removeMatches, boolean debug, int userId) {
6609        if (!sUserManager.exists(userId)) return null;
6610        final int callingUid = Binder.getCallingUid();
6611        flags = updateFlagsForResolve(
6612                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6613        intent = updateIntentForResolve(intent);
6614        // writer
6615        synchronized (mPackages) {
6616            // Try to find a matching persistent preferred activity.
6617            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6618                    debug, userId);
6619
6620            // If a persistent preferred activity matched, use it.
6621            if (pri != null) {
6622                return pri;
6623            }
6624
6625            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6626            // Get the list of preferred activities that handle the intent
6627            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6628            List<PreferredActivity> prefs = pir != null
6629                    ? pir.queryIntent(intent, resolvedType,
6630                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6631                            userId)
6632                    : null;
6633            if (prefs != null && prefs.size() > 0) {
6634                boolean changed = false;
6635                try {
6636                    // First figure out how good the original match set is.
6637                    // We will only allow preferred activities that came
6638                    // from the same match quality.
6639                    int match = 0;
6640
6641                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6642
6643                    final int N = query.size();
6644                    for (int j=0; j<N; j++) {
6645                        final ResolveInfo ri = query.get(j);
6646                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6647                                + ": 0x" + Integer.toHexString(match));
6648                        if (ri.match > match) {
6649                            match = ri.match;
6650                        }
6651                    }
6652
6653                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6654                            + Integer.toHexString(match));
6655
6656                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6657                    final int M = prefs.size();
6658                    for (int i=0; i<M; i++) {
6659                        final PreferredActivity pa = prefs.get(i);
6660                        if (DEBUG_PREFERRED || debug) {
6661                            Slog.v(TAG, "Checking PreferredActivity ds="
6662                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6663                                    + "\n  component=" + pa.mPref.mComponent);
6664                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6665                        }
6666                        if (pa.mPref.mMatch != match) {
6667                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6668                                    + Integer.toHexString(pa.mPref.mMatch));
6669                            continue;
6670                        }
6671                        // If it's not an "always" type preferred activity and that's what we're
6672                        // looking for, skip it.
6673                        if (always && !pa.mPref.mAlways) {
6674                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6675                            continue;
6676                        }
6677                        final ActivityInfo ai = getActivityInfo(
6678                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6679                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6680                                userId);
6681                        if (DEBUG_PREFERRED || debug) {
6682                            Slog.v(TAG, "Found preferred activity:");
6683                            if (ai != null) {
6684                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6685                            } else {
6686                                Slog.v(TAG, "  null");
6687                            }
6688                        }
6689                        if (ai == null) {
6690                            // This previously registered preferred activity
6691                            // component is no longer known.  Most likely an update
6692                            // to the app was installed and in the new version this
6693                            // component no longer exists.  Clean it up by removing
6694                            // it from the preferred activities list, and skip it.
6695                            Slog.w(TAG, "Removing dangling preferred activity: "
6696                                    + pa.mPref.mComponent);
6697                            pir.removeFilter(pa);
6698                            changed = true;
6699                            continue;
6700                        }
6701                        for (int j=0; j<N; j++) {
6702                            final ResolveInfo ri = query.get(j);
6703                            if (!ri.activityInfo.applicationInfo.packageName
6704                                    .equals(ai.applicationInfo.packageName)) {
6705                                continue;
6706                            }
6707                            if (!ri.activityInfo.name.equals(ai.name)) {
6708                                continue;
6709                            }
6710
6711                            if (removeMatches) {
6712                                pir.removeFilter(pa);
6713                                changed = true;
6714                                if (DEBUG_PREFERRED) {
6715                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6716                                }
6717                                break;
6718                            }
6719
6720                            // Okay we found a previously set preferred or last chosen app.
6721                            // If the result set is different from when this
6722                            // was created, we need to clear it and re-ask the
6723                            // user their preference, if we're looking for an "always" type entry.
6724                            if (always && !pa.mPref.sameSet(query)) {
6725                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6726                                        + intent + " type " + resolvedType);
6727                                if (DEBUG_PREFERRED) {
6728                                    Slog.v(TAG, "Removing preferred activity since set changed "
6729                                            + pa.mPref.mComponent);
6730                                }
6731                                pir.removeFilter(pa);
6732                                // Re-add the filter as a "last chosen" entry (!always)
6733                                PreferredActivity lastChosen = new PreferredActivity(
6734                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6735                                pir.addFilter(lastChosen);
6736                                changed = true;
6737                                return null;
6738                            }
6739
6740                            // Yay! Either the set matched or we're looking for the last chosen
6741                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6742                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6743                            return ri;
6744                        }
6745                    }
6746                } finally {
6747                    if (changed) {
6748                        if (DEBUG_PREFERRED) {
6749                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6750                        }
6751                        scheduleWritePackageRestrictionsLocked(userId);
6752                    }
6753                }
6754            }
6755        }
6756        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6757        return null;
6758    }
6759
6760    /*
6761     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6762     */
6763    @Override
6764    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6765            int targetUserId) {
6766        mContext.enforceCallingOrSelfPermission(
6767                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6768        List<CrossProfileIntentFilter> matches =
6769                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6770        if (matches != null) {
6771            int size = matches.size();
6772            for (int i = 0; i < size; i++) {
6773                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6774            }
6775        }
6776        if (hasWebURI(intent)) {
6777            // cross-profile app linking works only towards the parent.
6778            final int callingUid = Binder.getCallingUid();
6779            final UserInfo parent = getProfileParent(sourceUserId);
6780            synchronized(mPackages) {
6781                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6782                        false /*includeInstantApps*/);
6783                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6784                        intent, resolvedType, flags, sourceUserId, parent.id);
6785                return xpDomainInfo != null;
6786            }
6787        }
6788        return false;
6789    }
6790
6791    private UserInfo getProfileParent(int userId) {
6792        final long identity = Binder.clearCallingIdentity();
6793        try {
6794            return sUserManager.getProfileParent(userId);
6795        } finally {
6796            Binder.restoreCallingIdentity(identity);
6797        }
6798    }
6799
6800    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6801            String resolvedType, int userId) {
6802        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6803        if (resolver != null) {
6804            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6805        }
6806        return null;
6807    }
6808
6809    @Override
6810    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6811            String resolvedType, int flags, int userId) {
6812        try {
6813            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6814
6815            return new ParceledListSlice<>(
6816                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6817        } finally {
6818            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6819        }
6820    }
6821
6822    /**
6823     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6824     * instant, returns {@code null}.
6825     */
6826    private String getInstantAppPackageName(int callingUid) {
6827        synchronized (mPackages) {
6828            // If the caller is an isolated app use the owner's uid for the lookup.
6829            if (Process.isIsolated(callingUid)) {
6830                callingUid = mIsolatedOwners.get(callingUid);
6831            }
6832            final int appId = UserHandle.getAppId(callingUid);
6833            final Object obj = mSettings.getUserIdLPr(appId);
6834            if (obj instanceof PackageSetting) {
6835                final PackageSetting ps = (PackageSetting) obj;
6836                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6837                return isInstantApp ? ps.pkg.packageName : null;
6838            }
6839        }
6840        return null;
6841    }
6842
6843    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6844            String resolvedType, int flags, int userId) {
6845        return queryIntentActivitiesInternal(
6846                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6847    }
6848
6849    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6850            String resolvedType, int flags, int filterCallingUid, int userId,
6851            boolean resolveForStart) {
6852        if (!sUserManager.exists(userId)) return Collections.emptyList();
6853        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6854        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6855                false /* requireFullPermission */, false /* checkShell */,
6856                "query intent activities");
6857        final String pkgName = intent.getPackage();
6858        ComponentName comp = intent.getComponent();
6859        if (comp == null) {
6860            if (intent.getSelector() != null) {
6861                intent = intent.getSelector();
6862                comp = intent.getComponent();
6863            }
6864        }
6865
6866        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6867                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6868        if (comp != null) {
6869            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6870            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6871            if (ai != null) {
6872                // When specifying an explicit component, we prevent the activity from being
6873                // used when either 1) the calling package is normal and the activity is within
6874                // an ephemeral application or 2) the calling package is ephemeral and the
6875                // activity is not visible to ephemeral applications.
6876                final boolean matchInstantApp =
6877                        (flags & PackageManager.MATCH_INSTANT) != 0;
6878                final boolean matchVisibleToInstantAppOnly =
6879                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6880                final boolean matchExplicitlyVisibleOnly =
6881                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6882                final boolean isCallerInstantApp =
6883                        instantAppPkgName != null;
6884                final boolean isTargetSameInstantApp =
6885                        comp.getPackageName().equals(instantAppPkgName);
6886                final boolean isTargetInstantApp =
6887                        (ai.applicationInfo.privateFlags
6888                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6889                final boolean isTargetVisibleToInstantApp =
6890                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6891                final boolean isTargetExplicitlyVisibleToInstantApp =
6892                        isTargetVisibleToInstantApp
6893                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6894                final boolean isTargetHiddenFromInstantApp =
6895                        !isTargetVisibleToInstantApp
6896                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6897                final boolean blockResolution =
6898                        !isTargetSameInstantApp
6899                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6900                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6901                                        && isTargetHiddenFromInstantApp));
6902                if (!blockResolution) {
6903                    final ResolveInfo ri = new ResolveInfo();
6904                    ri.activityInfo = ai;
6905                    list.add(ri);
6906                }
6907            }
6908            return applyPostResolutionFilter(list, instantAppPkgName);
6909        }
6910
6911        // reader
6912        boolean sortResult = false;
6913        boolean addEphemeral = false;
6914        List<ResolveInfo> result;
6915        final boolean ephemeralDisabled = isEphemeralDisabled();
6916        synchronized (mPackages) {
6917            if (pkgName == null) {
6918                List<CrossProfileIntentFilter> matchingFilters =
6919                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6920                // Check for results that need to skip the current profile.
6921                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6922                        resolvedType, flags, userId);
6923                if (xpResolveInfo != null) {
6924                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6925                    xpResult.add(xpResolveInfo);
6926                    return applyPostResolutionFilter(
6927                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6928                }
6929
6930                // Check for results in the current profile.
6931                result = filterIfNotSystemUser(mActivities.queryIntent(
6932                        intent, resolvedType, flags, userId), userId);
6933                addEphemeral = !ephemeralDisabled
6934                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6935                // Check for cross profile results.
6936                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6937                xpResolveInfo = queryCrossProfileIntents(
6938                        matchingFilters, intent, resolvedType, flags, userId,
6939                        hasNonNegativePriorityResult);
6940                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6941                    boolean isVisibleToUser = filterIfNotSystemUser(
6942                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6943                    if (isVisibleToUser) {
6944                        result.add(xpResolveInfo);
6945                        sortResult = true;
6946                    }
6947                }
6948                if (hasWebURI(intent)) {
6949                    CrossProfileDomainInfo xpDomainInfo = null;
6950                    final UserInfo parent = getProfileParent(userId);
6951                    if (parent != null) {
6952                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6953                                flags, userId, parent.id);
6954                    }
6955                    if (xpDomainInfo != null) {
6956                        if (xpResolveInfo != null) {
6957                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6958                            // in the result.
6959                            result.remove(xpResolveInfo);
6960                        }
6961                        if (result.size() == 0 && !addEphemeral) {
6962                            // No result in current profile, but found candidate in parent user.
6963                            // And we are not going to add emphemeral app, so we can return the
6964                            // result straight away.
6965                            result.add(xpDomainInfo.resolveInfo);
6966                            return applyPostResolutionFilter(result, instantAppPkgName);
6967                        }
6968                    } else if (result.size() <= 1 && !addEphemeral) {
6969                        // No result in parent user and <= 1 result in current profile, and we
6970                        // are not going to add emphemeral app, so we can return the result without
6971                        // further processing.
6972                        return applyPostResolutionFilter(result, instantAppPkgName);
6973                    }
6974                    // We have more than one candidate (combining results from current and parent
6975                    // profile), so we need filtering and sorting.
6976                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6977                            intent, flags, result, xpDomainInfo, userId);
6978                    sortResult = true;
6979                }
6980            } else {
6981                final PackageParser.Package pkg = mPackages.get(pkgName);
6982                result = null;
6983                if (pkg != null) {
6984                    result = filterIfNotSystemUser(
6985                            mActivities.queryIntentForPackage(
6986                                    intent, resolvedType, flags, pkg.activities, userId),
6987                            userId);
6988                }
6989                if (result == null || result.size() == 0) {
6990                    // the caller wants to resolve for a particular package; however, there
6991                    // were no installed results, so, try to find an ephemeral result
6992                    addEphemeral = !ephemeralDisabled
6993                            && isInstantAppAllowed(
6994                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6995                    if (result == null) {
6996                        result = new ArrayList<>();
6997                    }
6998                }
6999            }
7000        }
7001        if (addEphemeral) {
7002            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7003        }
7004        if (sortResult) {
7005            Collections.sort(result, mResolvePrioritySorter);
7006        }
7007        return applyPostResolutionFilter(result, instantAppPkgName);
7008    }
7009
7010    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7011            String resolvedType, int flags, int userId) {
7012        // first, check to see if we've got an instant app already installed
7013        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7014        ResolveInfo localInstantApp = null;
7015        boolean blockResolution = false;
7016        if (!alreadyResolvedLocally) {
7017            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7018                    flags
7019                        | PackageManager.GET_RESOLVED_FILTER
7020                        | PackageManager.MATCH_INSTANT
7021                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7022                    userId);
7023            for (int i = instantApps.size() - 1; i >= 0; --i) {
7024                final ResolveInfo info = instantApps.get(i);
7025                final String packageName = info.activityInfo.packageName;
7026                final PackageSetting ps = mSettings.mPackages.get(packageName);
7027                if (ps.getInstantApp(userId)) {
7028                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7029                    final int status = (int)(packedStatus >> 32);
7030                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7031                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7032                        // there's a local instant application installed, but, the user has
7033                        // chosen to never use it; skip resolution and don't acknowledge
7034                        // an instant application is even available
7035                        if (DEBUG_EPHEMERAL) {
7036                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7037                        }
7038                        blockResolution = true;
7039                        break;
7040                    } else {
7041                        // we have a locally installed instant application; skip resolution
7042                        // but acknowledge there's an instant application available
7043                        if (DEBUG_EPHEMERAL) {
7044                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7045                        }
7046                        localInstantApp = info;
7047                        break;
7048                    }
7049                }
7050            }
7051        }
7052        // no app installed, let's see if one's available
7053        AuxiliaryResolveInfo auxiliaryResponse = null;
7054        if (!blockResolution) {
7055            if (localInstantApp == null) {
7056                // we don't have an instant app locally, resolve externally
7057                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7058                final InstantAppRequest requestObject = new InstantAppRequest(
7059                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7060                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7061                auxiliaryResponse =
7062                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7063                                mContext, mInstantAppResolverConnection, requestObject);
7064                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7065            } else {
7066                // we have an instant application locally, but, we can't admit that since
7067                // callers shouldn't be able to determine prior browsing. create a dummy
7068                // auxiliary response so the downstream code behaves as if there's an
7069                // instant application available externally. when it comes time to start
7070                // the instant application, we'll do the right thing.
7071                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7072                auxiliaryResponse = new AuxiliaryResolveInfo(
7073                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7074            }
7075        }
7076        if (auxiliaryResponse != null) {
7077            if (DEBUG_EPHEMERAL) {
7078                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7079            }
7080            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7081            final PackageSetting ps =
7082                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7083            if (ps != null) {
7084                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7085                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7086                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7087                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7088                // make sure this resolver is the default
7089                ephemeralInstaller.isDefault = true;
7090                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7091                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7092                // add a non-generic filter
7093                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7094                ephemeralInstaller.filter.addDataPath(
7095                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7096                ephemeralInstaller.isInstantAppAvailable = true;
7097                result.add(ephemeralInstaller);
7098            }
7099        }
7100        return result;
7101    }
7102
7103    private static class CrossProfileDomainInfo {
7104        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7105        ResolveInfo resolveInfo;
7106        /* Best domain verification status of the activities found in the other profile */
7107        int bestDomainVerificationStatus;
7108    }
7109
7110    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7111            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7112        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7113                sourceUserId)) {
7114            return null;
7115        }
7116        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7117                resolvedType, flags, parentUserId);
7118
7119        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7120            return null;
7121        }
7122        CrossProfileDomainInfo result = null;
7123        int size = resultTargetUser.size();
7124        for (int i = 0; i < size; i++) {
7125            ResolveInfo riTargetUser = resultTargetUser.get(i);
7126            // Intent filter verification is only for filters that specify a host. So don't return
7127            // those that handle all web uris.
7128            if (riTargetUser.handleAllWebDataURI) {
7129                continue;
7130            }
7131            String packageName = riTargetUser.activityInfo.packageName;
7132            PackageSetting ps = mSettings.mPackages.get(packageName);
7133            if (ps == null) {
7134                continue;
7135            }
7136            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7137            int status = (int)(verificationState >> 32);
7138            if (result == null) {
7139                result = new CrossProfileDomainInfo();
7140                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7141                        sourceUserId, parentUserId);
7142                result.bestDomainVerificationStatus = status;
7143            } else {
7144                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7145                        result.bestDomainVerificationStatus);
7146            }
7147        }
7148        // Don't consider matches with status NEVER across profiles.
7149        if (result != null && result.bestDomainVerificationStatus
7150                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7151            return null;
7152        }
7153        return result;
7154    }
7155
7156    /**
7157     * Verification statuses are ordered from the worse to the best, except for
7158     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7159     */
7160    private int bestDomainVerificationStatus(int status1, int status2) {
7161        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7162            return status2;
7163        }
7164        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7165            return status1;
7166        }
7167        return (int) MathUtils.max(status1, status2);
7168    }
7169
7170    private boolean isUserEnabled(int userId) {
7171        long callingId = Binder.clearCallingIdentity();
7172        try {
7173            UserInfo userInfo = sUserManager.getUserInfo(userId);
7174            return userInfo != null && userInfo.isEnabled();
7175        } finally {
7176            Binder.restoreCallingIdentity(callingId);
7177        }
7178    }
7179
7180    /**
7181     * Filter out activities with systemUserOnly flag set, when current user is not System.
7182     *
7183     * @return filtered list
7184     */
7185    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7186        if (userId == UserHandle.USER_SYSTEM) {
7187            return resolveInfos;
7188        }
7189        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7190            ResolveInfo info = resolveInfos.get(i);
7191            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7192                resolveInfos.remove(i);
7193            }
7194        }
7195        return resolveInfos;
7196    }
7197
7198    /**
7199     * Filters out ephemeral activities.
7200     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7201     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7202     *
7203     * @param resolveInfos The pre-filtered list of resolved activities
7204     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7205     *          is performed.
7206     * @return A filtered list of resolved activities.
7207     */
7208    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7209            String ephemeralPkgName) {
7210        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7211            final ResolveInfo info = resolveInfos.get(i);
7212            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7213            // TODO: When adding on-demand split support for non-instant apps, remove this check
7214            // and always apply post filtering
7215            // allow activities that are defined in the provided package
7216            if (isEphemeralApp) {
7217                if (info.activityInfo.splitName != null
7218                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7219                                info.activityInfo.splitName)) {
7220                    // requested activity is defined in a split that hasn't been installed yet.
7221                    // add the installer to the resolve list
7222                    if (DEBUG_EPHEMERAL) {
7223                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7224                    }
7225                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7226                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7227                            info.activityInfo.packageName, info.activityInfo.splitName,
7228                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7229                    // make sure this resolver is the default
7230                    installerInfo.isDefault = true;
7231                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7232                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7233                    // add a non-generic filter
7234                    installerInfo.filter = new IntentFilter();
7235                    // load resources from the correct package
7236                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7237                    resolveInfos.set(i, installerInfo);
7238                    continue;
7239                }
7240            }
7241            // caller is a full app, don't need to apply any other filtering
7242            if (ephemeralPkgName == null) {
7243                continue;
7244            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7245                // caller is same app; don't need to apply any other filtering
7246                continue;
7247            }
7248            // allow activities that have been explicitly exposed to ephemeral apps
7249            if (!isEphemeralApp
7250                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7251                continue;
7252            }
7253            resolveInfos.remove(i);
7254        }
7255        return resolveInfos;
7256    }
7257
7258    /**
7259     * @param resolveInfos list of resolve infos in descending priority order
7260     * @return if the list contains a resolve info with non-negative priority
7261     */
7262    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7263        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7264    }
7265
7266    private static boolean hasWebURI(Intent intent) {
7267        if (intent.getData() == null) {
7268            return false;
7269        }
7270        final String scheme = intent.getScheme();
7271        if (TextUtils.isEmpty(scheme)) {
7272            return false;
7273        }
7274        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7275    }
7276
7277    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7278            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7279            int userId) {
7280        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7281
7282        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7283            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7284                    candidates.size());
7285        }
7286
7287        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7288        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7289        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7290        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7291        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7292        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7293
7294        synchronized (mPackages) {
7295            final int count = candidates.size();
7296            // First, try to use linked apps. Partition the candidates into four lists:
7297            // one for the final results, one for the "do not use ever", one for "undefined status"
7298            // and finally one for "browser app type".
7299            for (int n=0; n<count; n++) {
7300                ResolveInfo info = candidates.get(n);
7301                String packageName = info.activityInfo.packageName;
7302                PackageSetting ps = mSettings.mPackages.get(packageName);
7303                if (ps != null) {
7304                    // Add to the special match all list (Browser use case)
7305                    if (info.handleAllWebDataURI) {
7306                        matchAllList.add(info);
7307                        continue;
7308                    }
7309                    // Try to get the status from User settings first
7310                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7311                    int status = (int)(packedStatus >> 32);
7312                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7313                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7314                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7315                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7316                                    + " : linkgen=" + linkGeneration);
7317                        }
7318                        // Use link-enabled generation as preferredOrder, i.e.
7319                        // prefer newly-enabled over earlier-enabled.
7320                        info.preferredOrder = linkGeneration;
7321                        alwaysList.add(info);
7322                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7323                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7324                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7325                        }
7326                        neverList.add(info);
7327                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7328                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7329                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7330                        }
7331                        alwaysAskList.add(info);
7332                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7333                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7334                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7335                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7336                        }
7337                        undefinedList.add(info);
7338                    }
7339                }
7340            }
7341
7342            // We'll want to include browser possibilities in a few cases
7343            boolean includeBrowser = false;
7344
7345            // First try to add the "always" resolution(s) for the current user, if any
7346            if (alwaysList.size() > 0) {
7347                result.addAll(alwaysList);
7348            } else {
7349                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7350                result.addAll(undefinedList);
7351                // Maybe add one for the other profile.
7352                if (xpDomainInfo != null && (
7353                        xpDomainInfo.bestDomainVerificationStatus
7354                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7355                    result.add(xpDomainInfo.resolveInfo);
7356                }
7357                includeBrowser = true;
7358            }
7359
7360            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7361            // If there were 'always' entries their preferred order has been set, so we also
7362            // back that off to make the alternatives equivalent
7363            if (alwaysAskList.size() > 0) {
7364                for (ResolveInfo i : result) {
7365                    i.preferredOrder = 0;
7366                }
7367                result.addAll(alwaysAskList);
7368                includeBrowser = true;
7369            }
7370
7371            if (includeBrowser) {
7372                // Also add browsers (all of them or only the default one)
7373                if (DEBUG_DOMAIN_VERIFICATION) {
7374                    Slog.v(TAG, "   ...including browsers in candidate set");
7375                }
7376                if ((matchFlags & MATCH_ALL) != 0) {
7377                    result.addAll(matchAllList);
7378                } else {
7379                    // Browser/generic handling case.  If there's a default browser, go straight
7380                    // to that (but only if there is no other higher-priority match).
7381                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7382                    int maxMatchPrio = 0;
7383                    ResolveInfo defaultBrowserMatch = null;
7384                    final int numCandidates = matchAllList.size();
7385                    for (int n = 0; n < numCandidates; n++) {
7386                        ResolveInfo info = matchAllList.get(n);
7387                        // track the highest overall match priority...
7388                        if (info.priority > maxMatchPrio) {
7389                            maxMatchPrio = info.priority;
7390                        }
7391                        // ...and the highest-priority default browser match
7392                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7393                            if (defaultBrowserMatch == null
7394                                    || (defaultBrowserMatch.priority < info.priority)) {
7395                                if (debug) {
7396                                    Slog.v(TAG, "Considering default browser match " + info);
7397                                }
7398                                defaultBrowserMatch = info;
7399                            }
7400                        }
7401                    }
7402                    if (defaultBrowserMatch != null
7403                            && defaultBrowserMatch.priority >= maxMatchPrio
7404                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7405                    {
7406                        if (debug) {
7407                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7408                        }
7409                        result.add(defaultBrowserMatch);
7410                    } else {
7411                        result.addAll(matchAllList);
7412                    }
7413                }
7414
7415                // If there is nothing selected, add all candidates and remove the ones that the user
7416                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7417                if (result.size() == 0) {
7418                    result.addAll(candidates);
7419                    result.removeAll(neverList);
7420                }
7421            }
7422        }
7423        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7424            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7425                    result.size());
7426            for (ResolveInfo info : result) {
7427                Slog.v(TAG, "  + " + info.activityInfo);
7428            }
7429        }
7430        return result;
7431    }
7432
7433    // Returns a packed value as a long:
7434    //
7435    // high 'int'-sized word: link status: undefined/ask/never/always.
7436    // low 'int'-sized word: relative priority among 'always' results.
7437    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7438        long result = ps.getDomainVerificationStatusForUser(userId);
7439        // if none available, get the master status
7440        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7441            if (ps.getIntentFilterVerificationInfo() != null) {
7442                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7443            }
7444        }
7445        return result;
7446    }
7447
7448    private ResolveInfo querySkipCurrentProfileIntents(
7449            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7450            int flags, int sourceUserId) {
7451        if (matchingFilters != null) {
7452            int size = matchingFilters.size();
7453            for (int i = 0; i < size; i ++) {
7454                CrossProfileIntentFilter filter = matchingFilters.get(i);
7455                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7456                    // Checking if there are activities in the target user that can handle the
7457                    // intent.
7458                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7459                            resolvedType, flags, sourceUserId);
7460                    if (resolveInfo != null) {
7461                        return resolveInfo;
7462                    }
7463                }
7464            }
7465        }
7466        return null;
7467    }
7468
7469    // Return matching ResolveInfo in target user if any.
7470    private ResolveInfo queryCrossProfileIntents(
7471            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7472            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7473        if (matchingFilters != null) {
7474            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7475            // match the same intent. For performance reasons, it is better not to
7476            // run queryIntent twice for the same userId
7477            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7478            int size = matchingFilters.size();
7479            for (int i = 0; i < size; i++) {
7480                CrossProfileIntentFilter filter = matchingFilters.get(i);
7481                int targetUserId = filter.getTargetUserId();
7482                boolean skipCurrentProfile =
7483                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7484                boolean skipCurrentProfileIfNoMatchFound =
7485                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7486                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7487                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7488                    // Checking if there are activities in the target user that can handle the
7489                    // intent.
7490                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7491                            resolvedType, flags, sourceUserId);
7492                    if (resolveInfo != null) return resolveInfo;
7493                    alreadyTriedUserIds.put(targetUserId, true);
7494                }
7495            }
7496        }
7497        return null;
7498    }
7499
7500    /**
7501     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7502     * will forward the intent to the filter's target user.
7503     * Otherwise, returns null.
7504     */
7505    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7506            String resolvedType, int flags, int sourceUserId) {
7507        int targetUserId = filter.getTargetUserId();
7508        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7509                resolvedType, flags, targetUserId);
7510        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7511            // If all the matches in the target profile are suspended, return null.
7512            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7513                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7514                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7515                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7516                            targetUserId);
7517                }
7518            }
7519        }
7520        return null;
7521    }
7522
7523    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7524            int sourceUserId, int targetUserId) {
7525        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7526        long ident = Binder.clearCallingIdentity();
7527        boolean targetIsProfile;
7528        try {
7529            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7530        } finally {
7531            Binder.restoreCallingIdentity(ident);
7532        }
7533        String className;
7534        if (targetIsProfile) {
7535            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7536        } else {
7537            className = FORWARD_INTENT_TO_PARENT;
7538        }
7539        ComponentName forwardingActivityComponentName = new ComponentName(
7540                mAndroidApplication.packageName, className);
7541        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7542                sourceUserId);
7543        if (!targetIsProfile) {
7544            forwardingActivityInfo.showUserIcon = targetUserId;
7545            forwardingResolveInfo.noResourceId = true;
7546        }
7547        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7548        forwardingResolveInfo.priority = 0;
7549        forwardingResolveInfo.preferredOrder = 0;
7550        forwardingResolveInfo.match = 0;
7551        forwardingResolveInfo.isDefault = true;
7552        forwardingResolveInfo.filter = filter;
7553        forwardingResolveInfo.targetUserId = targetUserId;
7554        return forwardingResolveInfo;
7555    }
7556
7557    @Override
7558    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7559            Intent[] specifics, String[] specificTypes, Intent intent,
7560            String resolvedType, int flags, int userId) {
7561        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7562                specificTypes, intent, resolvedType, flags, userId));
7563    }
7564
7565    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7566            Intent[] specifics, String[] specificTypes, Intent intent,
7567            String resolvedType, int flags, int userId) {
7568        if (!sUserManager.exists(userId)) return Collections.emptyList();
7569        final int callingUid = Binder.getCallingUid();
7570        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7571                false /*includeInstantApps*/);
7572        enforceCrossUserPermission(callingUid, userId,
7573                false /*requireFullPermission*/, false /*checkShell*/,
7574                "query intent activity options");
7575        final String resultsAction = intent.getAction();
7576
7577        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7578                | PackageManager.GET_RESOLVED_FILTER, userId);
7579
7580        if (DEBUG_INTENT_MATCHING) {
7581            Log.v(TAG, "Query " + intent + ": " + results);
7582        }
7583
7584        int specificsPos = 0;
7585        int N;
7586
7587        // todo: note that the algorithm used here is O(N^2).  This
7588        // isn't a problem in our current environment, but if we start running
7589        // into situations where we have more than 5 or 10 matches then this
7590        // should probably be changed to something smarter...
7591
7592        // First we go through and resolve each of the specific items
7593        // that were supplied, taking care of removing any corresponding
7594        // duplicate items in the generic resolve list.
7595        if (specifics != null) {
7596            for (int i=0; i<specifics.length; i++) {
7597                final Intent sintent = specifics[i];
7598                if (sintent == null) {
7599                    continue;
7600                }
7601
7602                if (DEBUG_INTENT_MATCHING) {
7603                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7604                }
7605
7606                String action = sintent.getAction();
7607                if (resultsAction != null && resultsAction.equals(action)) {
7608                    // If this action was explicitly requested, then don't
7609                    // remove things that have it.
7610                    action = null;
7611                }
7612
7613                ResolveInfo ri = null;
7614                ActivityInfo ai = null;
7615
7616                ComponentName comp = sintent.getComponent();
7617                if (comp == null) {
7618                    ri = resolveIntent(
7619                        sintent,
7620                        specificTypes != null ? specificTypes[i] : null,
7621                            flags, userId);
7622                    if (ri == null) {
7623                        continue;
7624                    }
7625                    if (ri == mResolveInfo) {
7626                        // ACK!  Must do something better with this.
7627                    }
7628                    ai = ri.activityInfo;
7629                    comp = new ComponentName(ai.applicationInfo.packageName,
7630                            ai.name);
7631                } else {
7632                    ai = getActivityInfo(comp, flags, userId);
7633                    if (ai == null) {
7634                        continue;
7635                    }
7636                }
7637
7638                // Look for any generic query activities that are duplicates
7639                // of this specific one, and remove them from the results.
7640                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7641                N = results.size();
7642                int j;
7643                for (j=specificsPos; j<N; j++) {
7644                    ResolveInfo sri = results.get(j);
7645                    if ((sri.activityInfo.name.equals(comp.getClassName())
7646                            && sri.activityInfo.applicationInfo.packageName.equals(
7647                                    comp.getPackageName()))
7648                        || (action != null && sri.filter.matchAction(action))) {
7649                        results.remove(j);
7650                        if (DEBUG_INTENT_MATCHING) Log.v(
7651                            TAG, "Removing duplicate item from " + j
7652                            + " due to specific " + specificsPos);
7653                        if (ri == null) {
7654                            ri = sri;
7655                        }
7656                        j--;
7657                        N--;
7658                    }
7659                }
7660
7661                // Add this specific item to its proper place.
7662                if (ri == null) {
7663                    ri = new ResolveInfo();
7664                    ri.activityInfo = ai;
7665                }
7666                results.add(specificsPos, ri);
7667                ri.specificIndex = i;
7668                specificsPos++;
7669            }
7670        }
7671
7672        // Now we go through the remaining generic results and remove any
7673        // duplicate actions that are found here.
7674        N = results.size();
7675        for (int i=specificsPos; i<N-1; i++) {
7676            final ResolveInfo rii = results.get(i);
7677            if (rii.filter == null) {
7678                continue;
7679            }
7680
7681            // Iterate over all of the actions of this result's intent
7682            // filter...  typically this should be just one.
7683            final Iterator<String> it = rii.filter.actionsIterator();
7684            if (it == null) {
7685                continue;
7686            }
7687            while (it.hasNext()) {
7688                final String action = it.next();
7689                if (resultsAction != null && resultsAction.equals(action)) {
7690                    // If this action was explicitly requested, then don't
7691                    // remove things that have it.
7692                    continue;
7693                }
7694                for (int j=i+1; j<N; j++) {
7695                    final ResolveInfo rij = results.get(j);
7696                    if (rij.filter != null && rij.filter.hasAction(action)) {
7697                        results.remove(j);
7698                        if (DEBUG_INTENT_MATCHING) Log.v(
7699                            TAG, "Removing duplicate item from " + j
7700                            + " due to action " + action + " at " + i);
7701                        j--;
7702                        N--;
7703                    }
7704                }
7705            }
7706
7707            // If the caller didn't request filter information, drop it now
7708            // so we don't have to marshall/unmarshall it.
7709            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7710                rii.filter = null;
7711            }
7712        }
7713
7714        // Filter out the caller activity if so requested.
7715        if (caller != null) {
7716            N = results.size();
7717            for (int i=0; i<N; i++) {
7718                ActivityInfo ainfo = results.get(i).activityInfo;
7719                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7720                        && caller.getClassName().equals(ainfo.name)) {
7721                    results.remove(i);
7722                    break;
7723                }
7724            }
7725        }
7726
7727        // If the caller didn't request filter information,
7728        // drop them now so we don't have to
7729        // marshall/unmarshall it.
7730        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7731            N = results.size();
7732            for (int i=0; i<N; i++) {
7733                results.get(i).filter = null;
7734            }
7735        }
7736
7737        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7738        return results;
7739    }
7740
7741    @Override
7742    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7743            String resolvedType, int flags, int userId) {
7744        return new ParceledListSlice<>(
7745                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7746    }
7747
7748    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7749            String resolvedType, int flags, int userId) {
7750        if (!sUserManager.exists(userId)) return Collections.emptyList();
7751        final int callingUid = Binder.getCallingUid();
7752        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7753        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7754                false /*includeInstantApps*/);
7755        ComponentName comp = intent.getComponent();
7756        if (comp == null) {
7757            if (intent.getSelector() != null) {
7758                intent = intent.getSelector();
7759                comp = intent.getComponent();
7760            }
7761        }
7762        if (comp != null) {
7763            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7764            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7765            if (ai != null) {
7766                // When specifying an explicit component, we prevent the activity from being
7767                // used when either 1) the calling package is normal and the activity is within
7768                // an instant application or 2) the calling package is ephemeral and the
7769                // activity is not visible to instant applications.
7770                final boolean matchInstantApp =
7771                        (flags & PackageManager.MATCH_INSTANT) != 0;
7772                final boolean matchVisibleToInstantAppOnly =
7773                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7774                final boolean matchExplicitlyVisibleOnly =
7775                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7776                final boolean isCallerInstantApp =
7777                        instantAppPkgName != null;
7778                final boolean isTargetSameInstantApp =
7779                        comp.getPackageName().equals(instantAppPkgName);
7780                final boolean isTargetInstantApp =
7781                        (ai.applicationInfo.privateFlags
7782                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7783                final boolean isTargetVisibleToInstantApp =
7784                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7785                final boolean isTargetExplicitlyVisibleToInstantApp =
7786                        isTargetVisibleToInstantApp
7787                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7788                final boolean isTargetHiddenFromInstantApp =
7789                        !isTargetVisibleToInstantApp
7790                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7791                final boolean blockResolution =
7792                        !isTargetSameInstantApp
7793                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7794                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7795                                        && isTargetHiddenFromInstantApp));
7796                if (!blockResolution) {
7797                    ResolveInfo ri = new ResolveInfo();
7798                    ri.activityInfo = ai;
7799                    list.add(ri);
7800                }
7801            }
7802            return applyPostResolutionFilter(list, instantAppPkgName);
7803        }
7804
7805        // reader
7806        synchronized (mPackages) {
7807            String pkgName = intent.getPackage();
7808            if (pkgName == null) {
7809                final List<ResolveInfo> result =
7810                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7811                return applyPostResolutionFilter(result, instantAppPkgName);
7812            }
7813            final PackageParser.Package pkg = mPackages.get(pkgName);
7814            if (pkg != null) {
7815                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7816                        intent, resolvedType, flags, pkg.receivers, userId);
7817                return applyPostResolutionFilter(result, instantAppPkgName);
7818            }
7819            return Collections.emptyList();
7820        }
7821    }
7822
7823    @Override
7824    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7825        final int callingUid = Binder.getCallingUid();
7826        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7827    }
7828
7829    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7830            int userId, int callingUid) {
7831        if (!sUserManager.exists(userId)) return null;
7832        flags = updateFlagsForResolve(
7833                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7834        List<ResolveInfo> query = queryIntentServicesInternal(
7835                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7836        if (query != null) {
7837            if (query.size() >= 1) {
7838                // If there is more than one service with the same priority,
7839                // just arbitrarily pick the first one.
7840                return query.get(0);
7841            }
7842        }
7843        return null;
7844    }
7845
7846    @Override
7847    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7848            String resolvedType, int flags, int userId) {
7849        final int callingUid = Binder.getCallingUid();
7850        return new ParceledListSlice<>(queryIntentServicesInternal(
7851                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7852    }
7853
7854    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7855            String resolvedType, int flags, int userId, int callingUid,
7856            boolean includeInstantApps) {
7857        if (!sUserManager.exists(userId)) return Collections.emptyList();
7858        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7859        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7860        ComponentName comp = intent.getComponent();
7861        if (comp == null) {
7862            if (intent.getSelector() != null) {
7863                intent = intent.getSelector();
7864                comp = intent.getComponent();
7865            }
7866        }
7867        if (comp != null) {
7868            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7869            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7870            if (si != null) {
7871                // When specifying an explicit component, we prevent the service from being
7872                // used when either 1) the service is in an instant application and the
7873                // caller is not the same instant application or 2) the calling package is
7874                // ephemeral and the activity is not visible to ephemeral applications.
7875                final boolean matchInstantApp =
7876                        (flags & PackageManager.MATCH_INSTANT) != 0;
7877                final boolean matchVisibleToInstantAppOnly =
7878                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7879                final boolean isCallerInstantApp =
7880                        instantAppPkgName != null;
7881                final boolean isTargetSameInstantApp =
7882                        comp.getPackageName().equals(instantAppPkgName);
7883                final boolean isTargetInstantApp =
7884                        (si.applicationInfo.privateFlags
7885                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7886                final boolean isTargetHiddenFromInstantApp =
7887                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7888                final boolean blockResolution =
7889                        !isTargetSameInstantApp
7890                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7891                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7892                                        && isTargetHiddenFromInstantApp));
7893                if (!blockResolution) {
7894                    final ResolveInfo ri = new ResolveInfo();
7895                    ri.serviceInfo = si;
7896                    list.add(ri);
7897                }
7898            }
7899            return list;
7900        }
7901
7902        // reader
7903        synchronized (mPackages) {
7904            String pkgName = intent.getPackage();
7905            if (pkgName == null) {
7906                return applyPostServiceResolutionFilter(
7907                        mServices.queryIntent(intent, resolvedType, flags, userId),
7908                        instantAppPkgName);
7909            }
7910            final PackageParser.Package pkg = mPackages.get(pkgName);
7911            if (pkg != null) {
7912                return applyPostServiceResolutionFilter(
7913                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7914                                userId),
7915                        instantAppPkgName);
7916            }
7917            return Collections.emptyList();
7918        }
7919    }
7920
7921    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7922            String instantAppPkgName) {
7923        // TODO: When adding on-demand split support for non-instant apps, remove this check
7924        // and always apply post filtering
7925        if (instantAppPkgName == null) {
7926            return resolveInfos;
7927        }
7928        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7929            final ResolveInfo info = resolveInfos.get(i);
7930            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7931            // allow services that are defined in the provided package
7932            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7933                if (info.serviceInfo.splitName != null
7934                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7935                                info.serviceInfo.splitName)) {
7936                    // requested service is defined in a split that hasn't been installed yet.
7937                    // add the installer to the resolve list
7938                    if (DEBUG_EPHEMERAL) {
7939                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7940                    }
7941                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7942                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7943                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7944                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7945                    // make sure this resolver is the default
7946                    installerInfo.isDefault = true;
7947                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7948                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7949                    // add a non-generic filter
7950                    installerInfo.filter = new IntentFilter();
7951                    // load resources from the correct package
7952                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7953                    resolveInfos.set(i, installerInfo);
7954                }
7955                continue;
7956            }
7957            // allow services that have been explicitly exposed to ephemeral apps
7958            if (!isEphemeralApp
7959                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7960                continue;
7961            }
7962            resolveInfos.remove(i);
7963        }
7964        return resolveInfos;
7965    }
7966
7967    @Override
7968    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7969            String resolvedType, int flags, int userId) {
7970        return new ParceledListSlice<>(
7971                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7972    }
7973
7974    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7975            Intent intent, String resolvedType, int flags, int userId) {
7976        if (!sUserManager.exists(userId)) return Collections.emptyList();
7977        final int callingUid = Binder.getCallingUid();
7978        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7979        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7980                false /*includeInstantApps*/);
7981        ComponentName comp = intent.getComponent();
7982        if (comp == null) {
7983            if (intent.getSelector() != null) {
7984                intent = intent.getSelector();
7985                comp = intent.getComponent();
7986            }
7987        }
7988        if (comp != null) {
7989            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7990            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7991            if (pi != null) {
7992                // When specifying an explicit component, we prevent the provider from being
7993                // used when either 1) the provider is in an instant application and the
7994                // caller is not the same instant application or 2) the calling package is an
7995                // instant application and the provider is not visible to instant applications.
7996                final boolean matchInstantApp =
7997                        (flags & PackageManager.MATCH_INSTANT) != 0;
7998                final boolean matchVisibleToInstantAppOnly =
7999                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8000                final boolean isCallerInstantApp =
8001                        instantAppPkgName != null;
8002                final boolean isTargetSameInstantApp =
8003                        comp.getPackageName().equals(instantAppPkgName);
8004                final boolean isTargetInstantApp =
8005                        (pi.applicationInfo.privateFlags
8006                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8007                final boolean isTargetHiddenFromInstantApp =
8008                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8009                final boolean blockResolution =
8010                        !isTargetSameInstantApp
8011                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8012                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8013                                        && isTargetHiddenFromInstantApp));
8014                if (!blockResolution) {
8015                    final ResolveInfo ri = new ResolveInfo();
8016                    ri.providerInfo = pi;
8017                    list.add(ri);
8018                }
8019            }
8020            return list;
8021        }
8022
8023        // reader
8024        synchronized (mPackages) {
8025            String pkgName = intent.getPackage();
8026            if (pkgName == null) {
8027                return applyPostContentProviderResolutionFilter(
8028                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8029                        instantAppPkgName);
8030            }
8031            final PackageParser.Package pkg = mPackages.get(pkgName);
8032            if (pkg != null) {
8033                return applyPostContentProviderResolutionFilter(
8034                        mProviders.queryIntentForPackage(
8035                        intent, resolvedType, flags, pkg.providers, userId),
8036                        instantAppPkgName);
8037            }
8038            return Collections.emptyList();
8039        }
8040    }
8041
8042    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8043            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8044        // TODO: When adding on-demand split support for non-instant applications, remove
8045        // this check and always apply post filtering
8046        if (instantAppPkgName == null) {
8047            return resolveInfos;
8048        }
8049        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8050            final ResolveInfo info = resolveInfos.get(i);
8051            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8052            // allow providers that are defined in the provided package
8053            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8054                if (info.providerInfo.splitName != null
8055                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8056                                info.providerInfo.splitName)) {
8057                    // requested provider is defined in a split that hasn't been installed yet.
8058                    // add the installer to the resolve list
8059                    if (DEBUG_EPHEMERAL) {
8060                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8061                    }
8062                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8063                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8064                            info.providerInfo.packageName, info.providerInfo.splitName,
8065                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8066                    // make sure this resolver is the default
8067                    installerInfo.isDefault = true;
8068                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8069                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8070                    // add a non-generic filter
8071                    installerInfo.filter = new IntentFilter();
8072                    // load resources from the correct package
8073                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8074                    resolveInfos.set(i, installerInfo);
8075                }
8076                continue;
8077            }
8078            // allow providers that have been explicitly exposed to instant applications
8079            if (!isEphemeralApp
8080                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8081                continue;
8082            }
8083            resolveInfos.remove(i);
8084        }
8085        return resolveInfos;
8086    }
8087
8088    @Override
8089    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8090        final int callingUid = Binder.getCallingUid();
8091        if (getInstantAppPackageName(callingUid) != null) {
8092            return ParceledListSlice.emptyList();
8093        }
8094        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8095        flags = updateFlagsForPackage(flags, userId, null);
8096        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8097        enforceCrossUserPermission(callingUid, userId,
8098                true /* requireFullPermission */, false /* checkShell */,
8099                "get installed packages");
8100
8101        // writer
8102        synchronized (mPackages) {
8103            ArrayList<PackageInfo> list;
8104            if (listUninstalled) {
8105                list = new ArrayList<>(mSettings.mPackages.size());
8106                for (PackageSetting ps : mSettings.mPackages.values()) {
8107                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8108                        continue;
8109                    }
8110                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8111                        return null;
8112                    }
8113                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8114                    if (pi != null) {
8115                        list.add(pi);
8116                    }
8117                }
8118            } else {
8119                list = new ArrayList<>(mPackages.size());
8120                for (PackageParser.Package p : mPackages.values()) {
8121                    final PackageSetting ps = (PackageSetting) p.mExtras;
8122                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8123                        continue;
8124                    }
8125                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8126                        return null;
8127                    }
8128                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8129                            p.mExtras, flags, userId);
8130                    if (pi != null) {
8131                        list.add(pi);
8132                    }
8133                }
8134            }
8135
8136            return new ParceledListSlice<>(list);
8137        }
8138    }
8139
8140    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8141            String[] permissions, boolean[] tmp, int flags, int userId) {
8142        int numMatch = 0;
8143        final PermissionsState permissionsState = ps.getPermissionsState();
8144        for (int i=0; i<permissions.length; i++) {
8145            final String permission = permissions[i];
8146            if (permissionsState.hasPermission(permission, userId)) {
8147                tmp[i] = true;
8148                numMatch++;
8149            } else {
8150                tmp[i] = false;
8151            }
8152        }
8153        if (numMatch == 0) {
8154            return;
8155        }
8156        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8157
8158        // The above might return null in cases of uninstalled apps or install-state
8159        // skew across users/profiles.
8160        if (pi != null) {
8161            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8162                if (numMatch == permissions.length) {
8163                    pi.requestedPermissions = permissions;
8164                } else {
8165                    pi.requestedPermissions = new String[numMatch];
8166                    numMatch = 0;
8167                    for (int i=0; i<permissions.length; i++) {
8168                        if (tmp[i]) {
8169                            pi.requestedPermissions[numMatch] = permissions[i];
8170                            numMatch++;
8171                        }
8172                    }
8173                }
8174            }
8175            list.add(pi);
8176        }
8177    }
8178
8179    @Override
8180    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8181            String[] permissions, int flags, int userId) {
8182        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8183        flags = updateFlagsForPackage(flags, userId, permissions);
8184        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8185                true /* requireFullPermission */, false /* checkShell */,
8186                "get packages holding permissions");
8187        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8188
8189        // writer
8190        synchronized (mPackages) {
8191            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8192            boolean[] tmpBools = new boolean[permissions.length];
8193            if (listUninstalled) {
8194                for (PackageSetting ps : mSettings.mPackages.values()) {
8195                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8196                            userId);
8197                }
8198            } else {
8199                for (PackageParser.Package pkg : mPackages.values()) {
8200                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8201                    if (ps != null) {
8202                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8203                                userId);
8204                    }
8205                }
8206            }
8207
8208            return new ParceledListSlice<PackageInfo>(list);
8209        }
8210    }
8211
8212    @Override
8213    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8214        final int callingUid = Binder.getCallingUid();
8215        if (getInstantAppPackageName(callingUid) != null) {
8216            return ParceledListSlice.emptyList();
8217        }
8218        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8219        flags = updateFlagsForApplication(flags, userId, null);
8220        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8221
8222        // writer
8223        synchronized (mPackages) {
8224            ArrayList<ApplicationInfo> list;
8225            if (listUninstalled) {
8226                list = new ArrayList<>(mSettings.mPackages.size());
8227                for (PackageSetting ps : mSettings.mPackages.values()) {
8228                    ApplicationInfo ai;
8229                    int effectiveFlags = flags;
8230                    if (ps.isSystem()) {
8231                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8232                    }
8233                    if (ps.pkg != null) {
8234                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8235                            continue;
8236                        }
8237                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8238                            return null;
8239                        }
8240                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8241                                ps.readUserState(userId), userId);
8242                        if (ai != null) {
8243                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8244                        }
8245                    } else {
8246                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8247                        // and already converts to externally visible package name
8248                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8249                                callingUid, effectiveFlags, userId);
8250                    }
8251                    if (ai != null) {
8252                        list.add(ai);
8253                    }
8254                }
8255            } else {
8256                list = new ArrayList<>(mPackages.size());
8257                for (PackageParser.Package p : mPackages.values()) {
8258                    if (p.mExtras != null) {
8259                        PackageSetting ps = (PackageSetting) p.mExtras;
8260                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8261                            continue;
8262                        }
8263                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8264                            return null;
8265                        }
8266                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8267                                ps.readUserState(userId), userId);
8268                        if (ai != null) {
8269                            ai.packageName = resolveExternalPackageNameLPr(p);
8270                            list.add(ai);
8271                        }
8272                    }
8273                }
8274            }
8275
8276            return new ParceledListSlice<>(list);
8277        }
8278    }
8279
8280    @Override
8281    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8282        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8283            return null;
8284        }
8285        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8286                "getEphemeralApplications");
8287        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8288                true /* requireFullPermission */, false /* checkShell */,
8289                "getEphemeralApplications");
8290        synchronized (mPackages) {
8291            List<InstantAppInfo> instantApps = mInstantAppRegistry
8292                    .getInstantAppsLPr(userId);
8293            if (instantApps != null) {
8294                return new ParceledListSlice<>(instantApps);
8295            }
8296        }
8297        return null;
8298    }
8299
8300    @Override
8301    public boolean isInstantApp(String packageName, int userId) {
8302        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8303                true /* requireFullPermission */, false /* checkShell */,
8304                "isInstantApp");
8305        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8306            return false;
8307        }
8308
8309        synchronized (mPackages) {
8310            int callingUid = Binder.getCallingUid();
8311            if (Process.isIsolated(callingUid)) {
8312                callingUid = mIsolatedOwners.get(callingUid);
8313            }
8314            final PackageSetting ps = mSettings.mPackages.get(packageName);
8315            PackageParser.Package pkg = mPackages.get(packageName);
8316            final boolean returnAllowed =
8317                    ps != null
8318                    && (isCallerSameApp(packageName, callingUid)
8319                            || canViewInstantApps(callingUid, userId)
8320                            || mInstantAppRegistry.isInstantAccessGranted(
8321                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8322            if (returnAllowed) {
8323                return ps.getInstantApp(userId);
8324            }
8325        }
8326        return false;
8327    }
8328
8329    @Override
8330    public byte[] getInstantAppCookie(String packageName, int userId) {
8331        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8332            return null;
8333        }
8334
8335        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8336                true /* requireFullPermission */, false /* checkShell */,
8337                "getInstantAppCookie");
8338        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8339            return null;
8340        }
8341        synchronized (mPackages) {
8342            return mInstantAppRegistry.getInstantAppCookieLPw(
8343                    packageName, userId);
8344        }
8345    }
8346
8347    @Override
8348    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8349        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8350            return true;
8351        }
8352
8353        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8354                true /* requireFullPermission */, true /* checkShell */,
8355                "setInstantAppCookie");
8356        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8357            return false;
8358        }
8359        synchronized (mPackages) {
8360            return mInstantAppRegistry.setInstantAppCookieLPw(
8361                    packageName, cookie, userId);
8362        }
8363    }
8364
8365    @Override
8366    public Bitmap getInstantAppIcon(String packageName, int userId) {
8367        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8368            return null;
8369        }
8370
8371        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8372                "getInstantAppIcon");
8373
8374        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8375                true /* requireFullPermission */, false /* checkShell */,
8376                "getInstantAppIcon");
8377
8378        synchronized (mPackages) {
8379            return mInstantAppRegistry.getInstantAppIconLPw(
8380                    packageName, userId);
8381        }
8382    }
8383
8384    private boolean isCallerSameApp(String packageName, int uid) {
8385        PackageParser.Package pkg = mPackages.get(packageName);
8386        return pkg != null
8387                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8388    }
8389
8390    @Override
8391    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8392        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8393            return ParceledListSlice.emptyList();
8394        }
8395        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8396    }
8397
8398    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8399        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8400
8401        // reader
8402        synchronized (mPackages) {
8403            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8404            final int userId = UserHandle.getCallingUserId();
8405            while (i.hasNext()) {
8406                final PackageParser.Package p = i.next();
8407                if (p.applicationInfo == null) continue;
8408
8409                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8410                        && !p.applicationInfo.isDirectBootAware();
8411                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8412                        && p.applicationInfo.isDirectBootAware();
8413
8414                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8415                        && (!mSafeMode || isSystemApp(p))
8416                        && (matchesUnaware || matchesAware)) {
8417                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8418                    if (ps != null) {
8419                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8420                                ps.readUserState(userId), userId);
8421                        if (ai != null) {
8422                            finalList.add(ai);
8423                        }
8424                    }
8425                }
8426            }
8427        }
8428
8429        return finalList;
8430    }
8431
8432    @Override
8433    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8434        if (!sUserManager.exists(userId)) return null;
8435        flags = updateFlagsForComponent(flags, userId, name);
8436        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8437        // reader
8438        synchronized (mPackages) {
8439            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8440            PackageSetting ps = provider != null
8441                    ? mSettings.mPackages.get(provider.owner.packageName)
8442                    : null;
8443            if (ps != null) {
8444                final boolean isInstantApp = ps.getInstantApp(userId);
8445                // normal application; filter out instant application provider
8446                if (instantAppPkgName == null && isInstantApp) {
8447                    return null;
8448                }
8449                // instant application; filter out other instant applications
8450                if (instantAppPkgName != null
8451                        && isInstantApp
8452                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8453                    return null;
8454                }
8455                // instant application; filter out non-exposed provider
8456                if (instantAppPkgName != null
8457                        && !isInstantApp
8458                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8459                    return null;
8460                }
8461                // provider not enabled
8462                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8463                    return null;
8464                }
8465                return PackageParser.generateProviderInfo(
8466                        provider, flags, ps.readUserState(userId), userId);
8467            }
8468            return null;
8469        }
8470    }
8471
8472    /**
8473     * @deprecated
8474     */
8475    @Deprecated
8476    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8477        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8478            return;
8479        }
8480        // reader
8481        synchronized (mPackages) {
8482            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8483                    .entrySet().iterator();
8484            final int userId = UserHandle.getCallingUserId();
8485            while (i.hasNext()) {
8486                Map.Entry<String, PackageParser.Provider> entry = i.next();
8487                PackageParser.Provider p = entry.getValue();
8488                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8489
8490                if (ps != null && p.syncable
8491                        && (!mSafeMode || (p.info.applicationInfo.flags
8492                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8493                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8494                            ps.readUserState(userId), userId);
8495                    if (info != null) {
8496                        outNames.add(entry.getKey());
8497                        outInfo.add(info);
8498                    }
8499                }
8500            }
8501        }
8502    }
8503
8504    @Override
8505    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8506            int uid, int flags, String metaDataKey) {
8507        final int callingUid = Binder.getCallingUid();
8508        final int userId = processName != null ? UserHandle.getUserId(uid)
8509                : UserHandle.getCallingUserId();
8510        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8511        flags = updateFlagsForComponent(flags, userId, processName);
8512        ArrayList<ProviderInfo> finalList = null;
8513        // reader
8514        synchronized (mPackages) {
8515            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8516            while (i.hasNext()) {
8517                final PackageParser.Provider p = i.next();
8518                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8519                if (ps != null && p.info.authority != null
8520                        && (processName == null
8521                                || (p.info.processName.equals(processName)
8522                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8523                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8524
8525                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8526                    // parameter.
8527                    if (metaDataKey != null
8528                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8529                        continue;
8530                    }
8531                    final ComponentName component =
8532                            new ComponentName(p.info.packageName, p.info.name);
8533                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8534                        continue;
8535                    }
8536                    if (finalList == null) {
8537                        finalList = new ArrayList<ProviderInfo>(3);
8538                    }
8539                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8540                            ps.readUserState(userId), userId);
8541                    if (info != null) {
8542                        finalList.add(info);
8543                    }
8544                }
8545            }
8546        }
8547
8548        if (finalList != null) {
8549            Collections.sort(finalList, mProviderInitOrderSorter);
8550            return new ParceledListSlice<ProviderInfo>(finalList);
8551        }
8552
8553        return ParceledListSlice.emptyList();
8554    }
8555
8556    @Override
8557    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8558        // reader
8559        synchronized (mPackages) {
8560            final int callingUid = Binder.getCallingUid();
8561            final int callingUserId = UserHandle.getUserId(callingUid);
8562            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8563            if (ps == null) return null;
8564            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8565                return null;
8566            }
8567            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8568            return PackageParser.generateInstrumentationInfo(i, flags);
8569        }
8570    }
8571
8572    @Override
8573    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8574            String targetPackage, int flags) {
8575        final int callingUid = Binder.getCallingUid();
8576        final int callingUserId = UserHandle.getUserId(callingUid);
8577        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8578        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8579            return ParceledListSlice.emptyList();
8580        }
8581        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8582    }
8583
8584    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8585            int flags) {
8586        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8587
8588        // reader
8589        synchronized (mPackages) {
8590            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8591            while (i.hasNext()) {
8592                final PackageParser.Instrumentation p = i.next();
8593                if (targetPackage == null
8594                        || targetPackage.equals(p.info.targetPackage)) {
8595                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8596                            flags);
8597                    if (ii != null) {
8598                        finalList.add(ii);
8599                    }
8600                }
8601            }
8602        }
8603
8604        return finalList;
8605    }
8606
8607    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8608        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8609        try {
8610            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8611        } finally {
8612            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8613        }
8614    }
8615
8616    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8617        final File[] files = dir.listFiles();
8618        if (ArrayUtils.isEmpty(files)) {
8619            Log.d(TAG, "No files in app dir " + dir);
8620            return;
8621        }
8622
8623        if (DEBUG_PACKAGE_SCANNING) {
8624            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8625                    + " flags=0x" + Integer.toHexString(parseFlags));
8626        }
8627        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8628                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8629                mParallelPackageParserCallback);
8630
8631        // Submit files for parsing in parallel
8632        int fileCount = 0;
8633        for (File file : files) {
8634            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8635                    && !PackageInstallerService.isStageName(file.getName());
8636            if (!isPackage) {
8637                // Ignore entries which are not packages
8638                continue;
8639            }
8640            parallelPackageParser.submit(file, parseFlags);
8641            fileCount++;
8642        }
8643
8644        // Process results one by one
8645        for (; fileCount > 0; fileCount--) {
8646            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8647            Throwable throwable = parseResult.throwable;
8648            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8649
8650            if (throwable == null) {
8651                // Static shared libraries have synthetic package names
8652                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8653                    renameStaticSharedLibraryPackage(parseResult.pkg);
8654                }
8655                try {
8656                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8657                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8658                                currentTime, null);
8659                    }
8660                } catch (PackageManagerException e) {
8661                    errorCode = e.error;
8662                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8663                }
8664            } else if (throwable instanceof PackageParser.PackageParserException) {
8665                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8666                        throwable;
8667                errorCode = e.error;
8668                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8669            } else {
8670                throw new IllegalStateException("Unexpected exception occurred while parsing "
8671                        + parseResult.scanFile, throwable);
8672            }
8673
8674            // Delete invalid userdata apps
8675            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8676                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8677                logCriticalInfo(Log.WARN,
8678                        "Deleting invalid package at " + parseResult.scanFile);
8679                removeCodePathLI(parseResult.scanFile);
8680            }
8681        }
8682        parallelPackageParser.close();
8683    }
8684
8685    private static File getSettingsProblemFile() {
8686        File dataDir = Environment.getDataDirectory();
8687        File systemDir = new File(dataDir, "system");
8688        File fname = new File(systemDir, "uiderrors.txt");
8689        return fname;
8690    }
8691
8692    static void reportSettingsProblem(int priority, String msg) {
8693        logCriticalInfo(priority, msg);
8694    }
8695
8696    public static void logCriticalInfo(int priority, String msg) {
8697        Slog.println(priority, TAG, msg);
8698        EventLogTags.writePmCriticalInfo(msg);
8699        try {
8700            File fname = getSettingsProblemFile();
8701            FileOutputStream out = new FileOutputStream(fname, true);
8702            PrintWriter pw = new FastPrintWriter(out);
8703            SimpleDateFormat formatter = new SimpleDateFormat();
8704            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8705            pw.println(dateString + ": " + msg);
8706            pw.close();
8707            FileUtils.setPermissions(
8708                    fname.toString(),
8709                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8710                    -1, -1);
8711        } catch (java.io.IOException e) {
8712        }
8713    }
8714
8715    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8716        if (srcFile.isDirectory()) {
8717            final File baseFile = new File(pkg.baseCodePath);
8718            long maxModifiedTime = baseFile.lastModified();
8719            if (pkg.splitCodePaths != null) {
8720                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8721                    final File splitFile = new File(pkg.splitCodePaths[i]);
8722                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8723                }
8724            }
8725            return maxModifiedTime;
8726        }
8727        return srcFile.lastModified();
8728    }
8729
8730    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8731            final int policyFlags) throws PackageManagerException {
8732        // When upgrading from pre-N MR1, verify the package time stamp using the package
8733        // directory and not the APK file.
8734        final long lastModifiedTime = mIsPreNMR1Upgrade
8735                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8736        if (ps != null
8737                && ps.codePath.equals(srcFile)
8738                && ps.timeStamp == lastModifiedTime
8739                && !isCompatSignatureUpdateNeeded(pkg)
8740                && !isRecoverSignatureUpdateNeeded(pkg)) {
8741            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8742            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8743            ArraySet<PublicKey> signingKs;
8744            synchronized (mPackages) {
8745                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8746            }
8747            if (ps.signatures.mSignatures != null
8748                    && ps.signatures.mSignatures.length != 0
8749                    && signingKs != null) {
8750                // Optimization: reuse the existing cached certificates
8751                // if the package appears to be unchanged.
8752                pkg.mSignatures = ps.signatures.mSignatures;
8753                pkg.mSigningKeys = signingKs;
8754                return;
8755            }
8756
8757            Slog.w(TAG, "PackageSetting for " + ps.name
8758                    + " is missing signatures.  Collecting certs again to recover them.");
8759        } else {
8760            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8761        }
8762
8763        try {
8764            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8765            PackageParser.collectCertificates(pkg, policyFlags);
8766        } catch (PackageParserException e) {
8767            throw PackageManagerException.from(e);
8768        } finally {
8769            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8770        }
8771    }
8772
8773    /**
8774     *  Traces a package scan.
8775     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8776     */
8777    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8778            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8779        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8780        try {
8781            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8782        } finally {
8783            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8784        }
8785    }
8786
8787    /**
8788     *  Scans a package and returns the newly parsed package.
8789     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8790     */
8791    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8792            long currentTime, UserHandle user) throws PackageManagerException {
8793        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8794        PackageParser pp = new PackageParser();
8795        pp.setSeparateProcesses(mSeparateProcesses);
8796        pp.setOnlyCoreApps(mOnlyCore);
8797        pp.setDisplayMetrics(mMetrics);
8798        pp.setCallback(mPackageParserCallback);
8799
8800        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8801            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8802        }
8803
8804        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8805        final PackageParser.Package pkg;
8806        try {
8807            pkg = pp.parsePackage(scanFile, parseFlags);
8808        } catch (PackageParserException e) {
8809            throw PackageManagerException.from(e);
8810        } finally {
8811            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8812        }
8813
8814        // Static shared libraries have synthetic package names
8815        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8816            renameStaticSharedLibraryPackage(pkg);
8817        }
8818
8819        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8820    }
8821
8822    /**
8823     *  Scans a package and returns the newly parsed package.
8824     *  @throws PackageManagerException on a parse error.
8825     */
8826    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8827            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8828            throws PackageManagerException {
8829        // If the package has children and this is the first dive in the function
8830        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8831        // packages (parent and children) would be successfully scanned before the
8832        // actual scan since scanning mutates internal state and we want to atomically
8833        // install the package and its children.
8834        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8835            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8836                scanFlags |= SCAN_CHECK_ONLY;
8837            }
8838        } else {
8839            scanFlags &= ~SCAN_CHECK_ONLY;
8840        }
8841
8842        // Scan the parent
8843        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8844                scanFlags, currentTime, user);
8845
8846        // Scan the children
8847        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8848        for (int i = 0; i < childCount; i++) {
8849            PackageParser.Package childPackage = pkg.childPackages.get(i);
8850            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8851                    currentTime, user);
8852        }
8853
8854
8855        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8856            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8857        }
8858
8859        return scannedPkg;
8860    }
8861
8862    /**
8863     *  Scans a package and returns the newly parsed package.
8864     *  @throws PackageManagerException on a parse error.
8865     */
8866    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8867            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8868            throws PackageManagerException {
8869        PackageSetting ps = null;
8870        PackageSetting updatedPkg;
8871        // reader
8872        synchronized (mPackages) {
8873            // Look to see if we already know about this package.
8874            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8875            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8876                // This package has been renamed to its original name.  Let's
8877                // use that.
8878                ps = mSettings.getPackageLPr(oldName);
8879            }
8880            // If there was no original package, see one for the real package name.
8881            if (ps == null) {
8882                ps = mSettings.getPackageLPr(pkg.packageName);
8883            }
8884            // Check to see if this package could be hiding/updating a system
8885            // package.  Must look for it either under the original or real
8886            // package name depending on our state.
8887            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8888            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8889
8890            // If this is a package we don't know about on the system partition, we
8891            // may need to remove disabled child packages on the system partition
8892            // or may need to not add child packages if the parent apk is updated
8893            // on the data partition and no longer defines this child package.
8894            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8895                // If this is a parent package for an updated system app and this system
8896                // app got an OTA update which no longer defines some of the child packages
8897                // we have to prune them from the disabled system packages.
8898                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8899                if (disabledPs != null) {
8900                    final int scannedChildCount = (pkg.childPackages != null)
8901                            ? pkg.childPackages.size() : 0;
8902                    final int disabledChildCount = disabledPs.childPackageNames != null
8903                            ? disabledPs.childPackageNames.size() : 0;
8904                    for (int i = 0; i < disabledChildCount; i++) {
8905                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8906                        boolean disabledPackageAvailable = false;
8907                        for (int j = 0; j < scannedChildCount; j++) {
8908                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8909                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8910                                disabledPackageAvailable = true;
8911                                break;
8912                            }
8913                         }
8914                         if (!disabledPackageAvailable) {
8915                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8916                         }
8917                    }
8918                }
8919            }
8920        }
8921
8922        final boolean isUpdatedPkg = updatedPkg != null;
8923        final boolean isUpdatedSystemPkg = isUpdatedPkg
8924                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8925        boolean isUpdatedPkgBetter = false;
8926        // First check if this is a system package that may involve an update
8927        if (isUpdatedSystemPkg) {
8928            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8929            // it needs to drop FLAG_PRIVILEGED.
8930            if (locationIsPrivileged(scanFile)) {
8931                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8932            } else {
8933                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8934            }
8935
8936            if (ps != null && !ps.codePath.equals(scanFile)) {
8937                // The path has changed from what was last scanned...  check the
8938                // version of the new path against what we have stored to determine
8939                // what to do.
8940                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8941                if (pkg.mVersionCode <= ps.versionCode) {
8942                    // The system package has been updated and the code path does not match
8943                    // Ignore entry. Skip it.
8944                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8945                            + " ignored: updated version " + ps.versionCode
8946                            + " better than this " + pkg.mVersionCode);
8947                    if (!updatedPkg.codePath.equals(scanFile)) {
8948                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8949                                + ps.name + " changing from " + updatedPkg.codePathString
8950                                + " to " + scanFile);
8951                        updatedPkg.codePath = scanFile;
8952                        updatedPkg.codePathString = scanFile.toString();
8953                        updatedPkg.resourcePath = scanFile;
8954                        updatedPkg.resourcePathString = scanFile.toString();
8955                    }
8956                    updatedPkg.pkg = pkg;
8957                    updatedPkg.versionCode = pkg.mVersionCode;
8958
8959                    // Update the disabled system child packages to point to the package too.
8960                    final int childCount = updatedPkg.childPackageNames != null
8961                            ? updatedPkg.childPackageNames.size() : 0;
8962                    for (int i = 0; i < childCount; i++) {
8963                        String childPackageName = updatedPkg.childPackageNames.get(i);
8964                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8965                                childPackageName);
8966                        if (updatedChildPkg != null) {
8967                            updatedChildPkg.pkg = pkg;
8968                            updatedChildPkg.versionCode = pkg.mVersionCode;
8969                        }
8970                    }
8971                } else {
8972                    // The current app on the system partition is better than
8973                    // what we have updated to on the data partition; switch
8974                    // back to the system partition version.
8975                    // At this point, its safely assumed that package installation for
8976                    // apps in system partition will go through. If not there won't be a working
8977                    // version of the app
8978                    // writer
8979                    synchronized (mPackages) {
8980                        // Just remove the loaded entries from package lists.
8981                        mPackages.remove(ps.name);
8982                    }
8983
8984                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8985                            + " reverting from " + ps.codePathString
8986                            + ": new version " + pkg.mVersionCode
8987                            + " better than installed " + ps.versionCode);
8988
8989                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8990                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8991                    synchronized (mInstallLock) {
8992                        args.cleanUpResourcesLI();
8993                    }
8994                    synchronized (mPackages) {
8995                        mSettings.enableSystemPackageLPw(ps.name);
8996                    }
8997                    isUpdatedPkgBetter = true;
8998                }
8999            }
9000        }
9001
9002        String resourcePath = null;
9003        String baseResourcePath = null;
9004        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9005            if (ps != null && ps.resourcePathString != null) {
9006                resourcePath = ps.resourcePathString;
9007                baseResourcePath = ps.resourcePathString;
9008            } else {
9009                // Should not happen at all. Just log an error.
9010                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9011            }
9012        } else {
9013            resourcePath = pkg.codePath;
9014            baseResourcePath = pkg.baseCodePath;
9015        }
9016
9017        // Set application objects path explicitly.
9018        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9019        pkg.setApplicationInfoCodePath(pkg.codePath);
9020        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9021        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9022        pkg.setApplicationInfoResourcePath(resourcePath);
9023        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9024        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9025
9026        // throw an exception if we have an update to a system application, but, it's not more
9027        // recent than the package we've already scanned
9028        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9029            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9030                    + scanFile + " ignored: updated version " + ps.versionCode
9031                    + " better than this " + pkg.mVersionCode);
9032        }
9033
9034        if (isUpdatedPkg) {
9035            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9036            // initially
9037            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9038
9039            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9040            // flag set initially
9041            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9042                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9043            }
9044        }
9045
9046        // Verify certificates against what was last scanned
9047        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9048
9049        /*
9050         * A new system app appeared, but we already had a non-system one of the
9051         * same name installed earlier.
9052         */
9053        boolean shouldHideSystemApp = false;
9054        if (!isUpdatedPkg && ps != null
9055                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9056            /*
9057             * Check to make sure the signatures match first. If they don't,
9058             * wipe the installed application and its data.
9059             */
9060            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9061                    != PackageManager.SIGNATURE_MATCH) {
9062                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9063                        + " signatures don't match existing userdata copy; removing");
9064                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9065                        "scanPackageInternalLI")) {
9066                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9067                }
9068                ps = null;
9069            } else {
9070                /*
9071                 * If the newly-added system app is an older version than the
9072                 * already installed version, hide it. It will be scanned later
9073                 * and re-added like an update.
9074                 */
9075                if (pkg.mVersionCode <= ps.versionCode) {
9076                    shouldHideSystemApp = true;
9077                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9078                            + " but new version " + pkg.mVersionCode + " better than installed "
9079                            + ps.versionCode + "; hiding system");
9080                } else {
9081                    /*
9082                     * The newly found system app is a newer version that the
9083                     * one previously installed. Simply remove the
9084                     * already-installed application and replace it with our own
9085                     * while keeping the application data.
9086                     */
9087                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9088                            + " reverting from " + ps.codePathString + ": new version "
9089                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9090                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9091                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9092                    synchronized (mInstallLock) {
9093                        args.cleanUpResourcesLI();
9094                    }
9095                }
9096            }
9097        }
9098
9099        // The apk is forward locked (not public) if its code and resources
9100        // are kept in different files. (except for app in either system or
9101        // vendor path).
9102        // TODO grab this value from PackageSettings
9103        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9104            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9105                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9106            }
9107        }
9108
9109        final int userId = ((user == null) ? 0 : user.getIdentifier());
9110        if (ps != null && ps.getInstantApp(userId)) {
9111            scanFlags |= SCAN_AS_INSTANT_APP;
9112        }
9113
9114        // Note that we invoke the following method only if we are about to unpack an application
9115        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9116                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9117
9118        /*
9119         * If the system app should be overridden by a previously installed
9120         * data, hide the system app now and let the /data/app scan pick it up
9121         * again.
9122         */
9123        if (shouldHideSystemApp) {
9124            synchronized (mPackages) {
9125                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9126            }
9127        }
9128
9129        return scannedPkg;
9130    }
9131
9132    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9133        // Derive the new package synthetic package name
9134        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9135                + pkg.staticSharedLibVersion);
9136    }
9137
9138    private static String fixProcessName(String defProcessName,
9139            String processName) {
9140        if (processName == null) {
9141            return defProcessName;
9142        }
9143        return processName;
9144    }
9145
9146    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9147            throws PackageManagerException {
9148        if (pkgSetting.signatures.mSignatures != null) {
9149            // Already existing package. Make sure signatures match
9150            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9151                    == PackageManager.SIGNATURE_MATCH;
9152            if (!match) {
9153                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9154                        == PackageManager.SIGNATURE_MATCH;
9155            }
9156            if (!match) {
9157                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9158                        == PackageManager.SIGNATURE_MATCH;
9159            }
9160            if (!match) {
9161                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9162                        + pkg.packageName + " signatures do not match the "
9163                        + "previously installed version; ignoring!");
9164            }
9165        }
9166
9167        // Check for shared user signatures
9168        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9169            // Already existing package. Make sure signatures match
9170            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9171                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9172            if (!match) {
9173                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9174                        == PackageManager.SIGNATURE_MATCH;
9175            }
9176            if (!match) {
9177                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9178                        == PackageManager.SIGNATURE_MATCH;
9179            }
9180            if (!match) {
9181                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9182                        "Package " + pkg.packageName
9183                        + " has no signatures that match those in shared user "
9184                        + pkgSetting.sharedUser.name + "; ignoring!");
9185            }
9186        }
9187    }
9188
9189    /**
9190     * Enforces that only the system UID or root's UID can call a method exposed
9191     * via Binder.
9192     *
9193     * @param message used as message if SecurityException is thrown
9194     * @throws SecurityException if the caller is not system or root
9195     */
9196    private static final void enforceSystemOrRoot(String message) {
9197        final int uid = Binder.getCallingUid();
9198        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9199            throw new SecurityException(message);
9200        }
9201    }
9202
9203    @Override
9204    public void performFstrimIfNeeded() {
9205        enforceSystemOrRoot("Only the system can request fstrim");
9206
9207        // Before everything else, see whether we need to fstrim.
9208        try {
9209            IStorageManager sm = PackageHelper.getStorageManager();
9210            if (sm != null) {
9211                boolean doTrim = false;
9212                final long interval = android.provider.Settings.Global.getLong(
9213                        mContext.getContentResolver(),
9214                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9215                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9216                if (interval > 0) {
9217                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9218                    if (timeSinceLast > interval) {
9219                        doTrim = true;
9220                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9221                                + "; running immediately");
9222                    }
9223                }
9224                if (doTrim) {
9225                    final boolean dexOptDialogShown;
9226                    synchronized (mPackages) {
9227                        dexOptDialogShown = mDexOptDialogShown;
9228                    }
9229                    if (!isFirstBoot() && dexOptDialogShown) {
9230                        try {
9231                            ActivityManager.getService().showBootMessage(
9232                                    mContext.getResources().getString(
9233                                            R.string.android_upgrading_fstrim), true);
9234                        } catch (RemoteException e) {
9235                        }
9236                    }
9237                    sm.runMaintenance();
9238                }
9239            } else {
9240                Slog.e(TAG, "storageManager service unavailable!");
9241            }
9242        } catch (RemoteException e) {
9243            // Can't happen; StorageManagerService is local
9244        }
9245    }
9246
9247    @Override
9248    public void updatePackagesIfNeeded() {
9249        enforceSystemOrRoot("Only the system can request package update");
9250
9251        // We need to re-extract after an OTA.
9252        boolean causeUpgrade = isUpgrade();
9253
9254        // First boot or factory reset.
9255        // Note: we also handle devices that are upgrading to N right now as if it is their
9256        //       first boot, as they do not have profile data.
9257        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9258
9259        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9260        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9261
9262        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9263            return;
9264        }
9265
9266        List<PackageParser.Package> pkgs;
9267        synchronized (mPackages) {
9268            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9269        }
9270
9271        final long startTime = System.nanoTime();
9272        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9273                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9274                    false /* bootComplete */);
9275
9276        final int elapsedTimeSeconds =
9277                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9278
9279        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9280        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9281        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9282        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9283        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9284    }
9285
9286    /*
9287     * Return the prebuilt profile path given a package base code path.
9288     */
9289    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9290        return pkg.baseCodePath + ".prof";
9291    }
9292
9293    /**
9294     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9295     * containing statistics about the invocation. The array consists of three elements,
9296     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9297     * and {@code numberOfPackagesFailed}.
9298     */
9299    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9300            String compilerFilter, boolean bootComplete) {
9301
9302        int numberOfPackagesVisited = 0;
9303        int numberOfPackagesOptimized = 0;
9304        int numberOfPackagesSkipped = 0;
9305        int numberOfPackagesFailed = 0;
9306        final int numberOfPackagesToDexopt = pkgs.size();
9307
9308        for (PackageParser.Package pkg : pkgs) {
9309            numberOfPackagesVisited++;
9310
9311            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9312                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9313                // that are already compiled.
9314                File profileFile = new File(getPrebuildProfilePath(pkg));
9315                // Copy profile if it exists.
9316                if (profileFile.exists()) {
9317                    try {
9318                        // We could also do this lazily before calling dexopt in
9319                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9320                        // is that we don't have a good way to say "do this only once".
9321                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9322                                pkg.applicationInfo.uid, pkg.packageName)) {
9323                            Log.e(TAG, "Installer failed to copy system profile!");
9324                        }
9325                    } catch (Exception e) {
9326                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9327                                e);
9328                    }
9329                }
9330            }
9331
9332            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9333                if (DEBUG_DEXOPT) {
9334                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9335                }
9336                numberOfPackagesSkipped++;
9337                continue;
9338            }
9339
9340            if (DEBUG_DEXOPT) {
9341                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9342                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9343            }
9344
9345            if (showDialog) {
9346                try {
9347                    ActivityManager.getService().showBootMessage(
9348                            mContext.getResources().getString(R.string.android_upgrading_apk,
9349                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9350                } catch (RemoteException e) {
9351                }
9352                synchronized (mPackages) {
9353                    mDexOptDialogShown = true;
9354                }
9355            }
9356
9357            // If the OTA updates a system app which was previously preopted to a non-preopted state
9358            // the app might end up being verified at runtime. That's because by default the apps
9359            // are verify-profile but for preopted apps there's no profile.
9360            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9361            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9362            // filter (by default 'quicken').
9363            // Note that at this stage unused apps are already filtered.
9364            if (isSystemApp(pkg) &&
9365                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9366                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9367                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9368            }
9369
9370            // checkProfiles is false to avoid merging profiles during boot which
9371            // might interfere with background compilation (b/28612421).
9372            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9373            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9374            // trade-off worth doing to save boot time work.
9375            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9376            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9377                    pkg.packageName,
9378                    compilerFilter,
9379                    dexoptFlags));
9380
9381            if (pkg.isSystemApp()) {
9382                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9383                // too much boot after an OTA.
9384                int secondaryDexoptFlags = dexoptFlags |
9385                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9386                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9387                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9388                        pkg.packageName,
9389                        compilerFilter,
9390                        secondaryDexoptFlags));
9391            }
9392
9393            // TODO(shubhamajmera): Record secondary dexopt stats.
9394            switch (primaryDexOptStaus) {
9395                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9396                    numberOfPackagesOptimized++;
9397                    break;
9398                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9399                    numberOfPackagesSkipped++;
9400                    break;
9401                case PackageDexOptimizer.DEX_OPT_FAILED:
9402                    numberOfPackagesFailed++;
9403                    break;
9404                default:
9405                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9406                    break;
9407            }
9408        }
9409
9410        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9411                numberOfPackagesFailed };
9412    }
9413
9414    @Override
9415    public void notifyPackageUse(String packageName, int reason) {
9416        synchronized (mPackages) {
9417            final int callingUid = Binder.getCallingUid();
9418            final int callingUserId = UserHandle.getUserId(callingUid);
9419            if (getInstantAppPackageName(callingUid) != null) {
9420                if (!isCallerSameApp(packageName, callingUid)) {
9421                    return;
9422                }
9423            } else {
9424                if (isInstantApp(packageName, callingUserId)) {
9425                    return;
9426                }
9427            }
9428            final PackageParser.Package p = mPackages.get(packageName);
9429            if (p == null) {
9430                return;
9431            }
9432            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9433        }
9434    }
9435
9436    @Override
9437    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9438            List<String> classPaths, String loaderIsa) {
9439        int userId = UserHandle.getCallingUserId();
9440        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9441        if (ai == null) {
9442            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9443                + loadingPackageName + ", user=" + userId);
9444            return;
9445        }
9446        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9447    }
9448
9449    @Override
9450    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9451            IDexModuleRegisterCallback callback) {
9452        int userId = UserHandle.getCallingUserId();
9453        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9454        DexManager.RegisterDexModuleResult result;
9455        if (ai == null) {
9456            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9457                     " calling user. package=" + packageName + ", user=" + userId);
9458            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9459        } else {
9460            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9461        }
9462
9463        if (callback != null) {
9464            mHandler.post(() -> {
9465                try {
9466                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9467                } catch (RemoteException e) {
9468                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9469                }
9470            });
9471        }
9472    }
9473
9474    /**
9475     * Ask the package manager to perform a dex-opt with the given compiler filter.
9476     *
9477     * Note: exposed only for the shell command to allow moving packages explicitly to a
9478     *       definite state.
9479     */
9480    @Override
9481    public boolean performDexOptMode(String packageName,
9482            boolean checkProfiles, String targetCompilerFilter, boolean force,
9483            boolean bootComplete, String splitName) {
9484        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9485                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9486                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9487        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9488                splitName, flags));
9489    }
9490
9491    /**
9492     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9493     * secondary dex files belonging to the given package.
9494     *
9495     * Note: exposed only for the shell command to allow moving packages explicitly to a
9496     *       definite state.
9497     */
9498    @Override
9499    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9500            boolean force) {
9501        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9502                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9503                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9504                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9505        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9506    }
9507
9508    /*package*/ boolean performDexOpt(DexoptOptions options) {
9509        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9510            return false;
9511        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9512            return false;
9513        }
9514
9515        if (options.isDexoptOnlySecondaryDex()) {
9516            return mDexManager.dexoptSecondaryDex(options);
9517        } else {
9518            int dexoptStatus = performDexOptWithStatus(options);
9519            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9520        }
9521    }
9522
9523    /**
9524     * Perform dexopt on the given package and return one of following result:
9525     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9526     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9527     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9528     */
9529    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9530        return performDexOptTraced(options);
9531    }
9532
9533    private int performDexOptTraced(DexoptOptions options) {
9534        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9535        try {
9536            return performDexOptInternal(options);
9537        } finally {
9538            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9539        }
9540    }
9541
9542    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9543    // if the package can now be considered up to date for the given filter.
9544    private int performDexOptInternal(DexoptOptions options) {
9545        PackageParser.Package p;
9546        synchronized (mPackages) {
9547            p = mPackages.get(options.getPackageName());
9548            if (p == null) {
9549                // Package could not be found. Report failure.
9550                return PackageDexOptimizer.DEX_OPT_FAILED;
9551            }
9552            mPackageUsage.maybeWriteAsync(mPackages);
9553            mCompilerStats.maybeWriteAsync();
9554        }
9555        long callingId = Binder.clearCallingIdentity();
9556        try {
9557            synchronized (mInstallLock) {
9558                return performDexOptInternalWithDependenciesLI(p, options);
9559            }
9560        } finally {
9561            Binder.restoreCallingIdentity(callingId);
9562        }
9563    }
9564
9565    public ArraySet<String> getOptimizablePackages() {
9566        ArraySet<String> pkgs = new ArraySet<String>();
9567        synchronized (mPackages) {
9568            for (PackageParser.Package p : mPackages.values()) {
9569                if (PackageDexOptimizer.canOptimizePackage(p)) {
9570                    pkgs.add(p.packageName);
9571                }
9572            }
9573        }
9574        return pkgs;
9575    }
9576
9577    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9578            DexoptOptions options) {
9579        // Select the dex optimizer based on the force parameter.
9580        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9581        //       allocate an object here.
9582        PackageDexOptimizer pdo = options.isForce()
9583                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9584                : mPackageDexOptimizer;
9585
9586        // Dexopt all dependencies first. Note: we ignore the return value and march on
9587        // on errors.
9588        // Note that we are going to call performDexOpt on those libraries as many times as
9589        // they are referenced in packages. When we do a batch of performDexOpt (for example
9590        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9591        // and the first package that uses the library will dexopt it. The
9592        // others will see that the compiled code for the library is up to date.
9593        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9594        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9595        if (!deps.isEmpty()) {
9596            for (PackageParser.Package depPackage : deps) {
9597                // TODO: Analyze and investigate if we (should) profile libraries.
9598                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9599                        getOrCreateCompilerPackageStats(depPackage),
9600                        true /* isUsedByOtherApps */,
9601                        options);
9602            }
9603        }
9604        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9605                getOrCreateCompilerPackageStats(p),
9606                mDexManager.isUsedByOtherApps(p.packageName), options);
9607    }
9608
9609    /**
9610     * Reconcile the information we have about the secondary dex files belonging to
9611     * {@code packagName} and the actual dex files. For all dex files that were
9612     * deleted, update the internal records and delete the generated oat files.
9613     */
9614    @Override
9615    public void reconcileSecondaryDexFiles(String packageName) {
9616        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9617            return;
9618        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9619            return;
9620        }
9621        mDexManager.reconcileSecondaryDexFiles(packageName);
9622    }
9623
9624    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9625    // a reference there.
9626    /*package*/ DexManager getDexManager() {
9627        return mDexManager;
9628    }
9629
9630    /**
9631     * Execute the background dexopt job immediately.
9632     */
9633    @Override
9634    public boolean runBackgroundDexoptJob() {
9635        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9636            return false;
9637        }
9638        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9639    }
9640
9641    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9642        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9643                || p.usesStaticLibraries != null) {
9644            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9645            Set<String> collectedNames = new HashSet<>();
9646            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9647
9648            retValue.remove(p);
9649
9650            return retValue;
9651        } else {
9652            return Collections.emptyList();
9653        }
9654    }
9655
9656    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9657            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9658        if (!collectedNames.contains(p.packageName)) {
9659            collectedNames.add(p.packageName);
9660            collected.add(p);
9661
9662            if (p.usesLibraries != null) {
9663                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9664                        null, collected, collectedNames);
9665            }
9666            if (p.usesOptionalLibraries != null) {
9667                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9668                        null, collected, collectedNames);
9669            }
9670            if (p.usesStaticLibraries != null) {
9671                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9672                        p.usesStaticLibrariesVersions, collected, collectedNames);
9673            }
9674        }
9675    }
9676
9677    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9678            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9679        final int libNameCount = libs.size();
9680        for (int i = 0; i < libNameCount; i++) {
9681            String libName = libs.get(i);
9682            int version = (versions != null && versions.length == libNameCount)
9683                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9684            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9685            if (libPkg != null) {
9686                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9687            }
9688        }
9689    }
9690
9691    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9692        synchronized (mPackages) {
9693            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9694            if (libEntry != null) {
9695                return mPackages.get(libEntry.apk);
9696            }
9697            return null;
9698        }
9699    }
9700
9701    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9702        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9703        if (versionedLib == null) {
9704            return null;
9705        }
9706        return versionedLib.get(version);
9707    }
9708
9709    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9710        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9711                pkg.staticSharedLibName);
9712        if (versionedLib == null) {
9713            return null;
9714        }
9715        int previousLibVersion = -1;
9716        final int versionCount = versionedLib.size();
9717        for (int i = 0; i < versionCount; i++) {
9718            final int libVersion = versionedLib.keyAt(i);
9719            if (libVersion < pkg.staticSharedLibVersion) {
9720                previousLibVersion = Math.max(previousLibVersion, libVersion);
9721            }
9722        }
9723        if (previousLibVersion >= 0) {
9724            return versionedLib.get(previousLibVersion);
9725        }
9726        return null;
9727    }
9728
9729    public void shutdown() {
9730        mPackageUsage.writeNow(mPackages);
9731        mCompilerStats.writeNow();
9732    }
9733
9734    @Override
9735    public void dumpProfiles(String packageName) {
9736        PackageParser.Package pkg;
9737        synchronized (mPackages) {
9738            pkg = mPackages.get(packageName);
9739            if (pkg == null) {
9740                throw new IllegalArgumentException("Unknown package: " + packageName);
9741            }
9742        }
9743        /* Only the shell, root, or the app user should be able to dump profiles. */
9744        int callingUid = Binder.getCallingUid();
9745        if (callingUid != Process.SHELL_UID &&
9746            callingUid != Process.ROOT_UID &&
9747            callingUid != pkg.applicationInfo.uid) {
9748            throw new SecurityException("dumpProfiles");
9749        }
9750
9751        synchronized (mInstallLock) {
9752            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9753            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9754            try {
9755                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9756                String codePaths = TextUtils.join(";", allCodePaths);
9757                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9758            } catch (InstallerException e) {
9759                Slog.w(TAG, "Failed to dump profiles", e);
9760            }
9761            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9762        }
9763    }
9764
9765    @Override
9766    public void forceDexOpt(String packageName) {
9767        enforceSystemOrRoot("forceDexOpt");
9768
9769        PackageParser.Package pkg;
9770        synchronized (mPackages) {
9771            pkg = mPackages.get(packageName);
9772            if (pkg == null) {
9773                throw new IllegalArgumentException("Unknown package: " + packageName);
9774            }
9775        }
9776
9777        synchronized (mInstallLock) {
9778            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9779
9780            // Whoever is calling forceDexOpt wants a compiled package.
9781            // Don't use profiles since that may cause compilation to be skipped.
9782            final int res = performDexOptInternalWithDependenciesLI(
9783                    pkg,
9784                    new DexoptOptions(packageName,
9785                            getDefaultCompilerFilter(),
9786                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9787
9788            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9789            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9790                throw new IllegalStateException("Failed to dexopt: " + res);
9791            }
9792        }
9793    }
9794
9795    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9796        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9797            Slog.w(TAG, "Unable to update from " + oldPkg.name
9798                    + " to " + newPkg.packageName
9799                    + ": old package not in system partition");
9800            return false;
9801        } else if (mPackages.get(oldPkg.name) != null) {
9802            Slog.w(TAG, "Unable to update from " + oldPkg.name
9803                    + " to " + newPkg.packageName
9804                    + ": old package still exists");
9805            return false;
9806        }
9807        return true;
9808    }
9809
9810    void removeCodePathLI(File codePath) {
9811        if (codePath.isDirectory()) {
9812            try {
9813                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9814            } catch (InstallerException e) {
9815                Slog.w(TAG, "Failed to remove code path", e);
9816            }
9817        } else {
9818            codePath.delete();
9819        }
9820    }
9821
9822    private int[] resolveUserIds(int userId) {
9823        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9824    }
9825
9826    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9827        if (pkg == null) {
9828            Slog.wtf(TAG, "Package was null!", new Throwable());
9829            return;
9830        }
9831        clearAppDataLeafLIF(pkg, userId, flags);
9832        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9833        for (int i = 0; i < childCount; i++) {
9834            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9835        }
9836    }
9837
9838    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9839        final PackageSetting ps;
9840        synchronized (mPackages) {
9841            ps = mSettings.mPackages.get(pkg.packageName);
9842        }
9843        for (int realUserId : resolveUserIds(userId)) {
9844            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9845            try {
9846                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9847                        ceDataInode);
9848            } catch (InstallerException e) {
9849                Slog.w(TAG, String.valueOf(e));
9850            }
9851        }
9852    }
9853
9854    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9855        if (pkg == null) {
9856            Slog.wtf(TAG, "Package was null!", new Throwable());
9857            return;
9858        }
9859        destroyAppDataLeafLIF(pkg, userId, flags);
9860        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9861        for (int i = 0; i < childCount; i++) {
9862            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9863        }
9864    }
9865
9866    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9867        final PackageSetting ps;
9868        synchronized (mPackages) {
9869            ps = mSettings.mPackages.get(pkg.packageName);
9870        }
9871        for (int realUserId : resolveUserIds(userId)) {
9872            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9873            try {
9874                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9875                        ceDataInode);
9876            } catch (InstallerException e) {
9877                Slog.w(TAG, String.valueOf(e));
9878            }
9879            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9880        }
9881    }
9882
9883    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9884        if (pkg == null) {
9885            Slog.wtf(TAG, "Package was null!", new Throwable());
9886            return;
9887        }
9888        destroyAppProfilesLeafLIF(pkg);
9889        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9890        for (int i = 0; i < childCount; i++) {
9891            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9892        }
9893    }
9894
9895    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9896        try {
9897            mInstaller.destroyAppProfiles(pkg.packageName);
9898        } catch (InstallerException e) {
9899            Slog.w(TAG, String.valueOf(e));
9900        }
9901    }
9902
9903    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9904        if (pkg == null) {
9905            Slog.wtf(TAG, "Package was null!", new Throwable());
9906            return;
9907        }
9908        clearAppProfilesLeafLIF(pkg);
9909        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9910        for (int i = 0; i < childCount; i++) {
9911            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9912        }
9913    }
9914
9915    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9916        try {
9917            mInstaller.clearAppProfiles(pkg.packageName);
9918        } catch (InstallerException e) {
9919            Slog.w(TAG, String.valueOf(e));
9920        }
9921    }
9922
9923    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9924            long lastUpdateTime) {
9925        // Set parent install/update time
9926        PackageSetting ps = (PackageSetting) pkg.mExtras;
9927        if (ps != null) {
9928            ps.firstInstallTime = firstInstallTime;
9929            ps.lastUpdateTime = lastUpdateTime;
9930        }
9931        // Set children install/update time
9932        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9933        for (int i = 0; i < childCount; i++) {
9934            PackageParser.Package childPkg = pkg.childPackages.get(i);
9935            ps = (PackageSetting) childPkg.mExtras;
9936            if (ps != null) {
9937                ps.firstInstallTime = firstInstallTime;
9938                ps.lastUpdateTime = lastUpdateTime;
9939            }
9940        }
9941    }
9942
9943    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9944            PackageParser.Package changingLib) {
9945        if (file.path != null) {
9946            usesLibraryFiles.add(file.path);
9947            return;
9948        }
9949        PackageParser.Package p = mPackages.get(file.apk);
9950        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9951            // If we are doing this while in the middle of updating a library apk,
9952            // then we need to make sure to use that new apk for determining the
9953            // dependencies here.  (We haven't yet finished committing the new apk
9954            // to the package manager state.)
9955            if (p == null || p.packageName.equals(changingLib.packageName)) {
9956                p = changingLib;
9957            }
9958        }
9959        if (p != null) {
9960            usesLibraryFiles.addAll(p.getAllCodePaths());
9961            if (p.usesLibraryFiles != null) {
9962                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9963            }
9964        }
9965    }
9966
9967    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9968            PackageParser.Package changingLib) throws PackageManagerException {
9969        if (pkg == null) {
9970            return;
9971        }
9972        ArraySet<String> usesLibraryFiles = null;
9973        if (pkg.usesLibraries != null) {
9974            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9975                    null, null, pkg.packageName, changingLib, true, null);
9976        }
9977        if (pkg.usesStaticLibraries != null) {
9978            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9979                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9980                    pkg.packageName, changingLib, true, usesLibraryFiles);
9981        }
9982        if (pkg.usesOptionalLibraries != null) {
9983            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9984                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9985        }
9986        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9987            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9988        } else {
9989            pkg.usesLibraryFiles = null;
9990        }
9991    }
9992
9993    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9994            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9995            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9996            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9997            throws PackageManagerException {
9998        final int libCount = requestedLibraries.size();
9999        for (int i = 0; i < libCount; i++) {
10000            final String libName = requestedLibraries.get(i);
10001            final int libVersion = requiredVersions != null ? requiredVersions[i]
10002                    : SharedLibraryInfo.VERSION_UNDEFINED;
10003            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10004            if (libEntry == null) {
10005                if (required) {
10006                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10007                            "Package " + packageName + " requires unavailable shared library "
10008                                    + libName + "; failing!");
10009                } else if (DEBUG_SHARED_LIBRARIES) {
10010                    Slog.i(TAG, "Package " + packageName
10011                            + " desires unavailable shared library "
10012                            + libName + "; ignoring!");
10013                }
10014            } else {
10015                if (requiredVersions != null && requiredCertDigests != null) {
10016                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10017                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10018                            "Package " + packageName + " requires unavailable static shared"
10019                                    + " library " + libName + " version "
10020                                    + libEntry.info.getVersion() + "; failing!");
10021                    }
10022
10023                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10024                    if (libPkg == null) {
10025                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10026                                "Package " + packageName + " requires unavailable static shared"
10027                                        + " library; failing!");
10028                    }
10029
10030                    String expectedCertDigest = requiredCertDigests[i];
10031                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10032                                libPkg.mSignatures[0]);
10033                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10034                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10035                                "Package " + packageName + " requires differently signed" +
10036                                        " static shared library; failing!");
10037                    }
10038                }
10039
10040                if (outUsedLibraries == null) {
10041                    outUsedLibraries = new ArraySet<>();
10042                }
10043                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10044            }
10045        }
10046        return outUsedLibraries;
10047    }
10048
10049    private static boolean hasString(List<String> list, List<String> which) {
10050        if (list == null) {
10051            return false;
10052        }
10053        for (int i=list.size()-1; i>=0; i--) {
10054            for (int j=which.size()-1; j>=0; j--) {
10055                if (which.get(j).equals(list.get(i))) {
10056                    return true;
10057                }
10058            }
10059        }
10060        return false;
10061    }
10062
10063    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10064            PackageParser.Package changingPkg) {
10065        ArrayList<PackageParser.Package> res = null;
10066        for (PackageParser.Package pkg : mPackages.values()) {
10067            if (changingPkg != null
10068                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10069                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10070                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10071                            changingPkg.staticSharedLibName)) {
10072                return null;
10073            }
10074            if (res == null) {
10075                res = new ArrayList<>();
10076            }
10077            res.add(pkg);
10078            try {
10079                updateSharedLibrariesLPr(pkg, changingPkg);
10080            } catch (PackageManagerException e) {
10081                // If a system app update or an app and a required lib missing we
10082                // delete the package and for updated system apps keep the data as
10083                // it is better for the user to reinstall than to be in an limbo
10084                // state. Also libs disappearing under an app should never happen
10085                // - just in case.
10086                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10087                    final int flags = pkg.isUpdatedSystemApp()
10088                            ? PackageManager.DELETE_KEEP_DATA : 0;
10089                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10090                            flags , null, true, null);
10091                }
10092                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10093            }
10094        }
10095        return res;
10096    }
10097
10098    /**
10099     * Derive the value of the {@code cpuAbiOverride} based on the provided
10100     * value and an optional stored value from the package settings.
10101     */
10102    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10103        String cpuAbiOverride = null;
10104
10105        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10106            cpuAbiOverride = null;
10107        } else if (abiOverride != null) {
10108            cpuAbiOverride = abiOverride;
10109        } else if (settings != null) {
10110            cpuAbiOverride = settings.cpuAbiOverrideString;
10111        }
10112
10113        return cpuAbiOverride;
10114    }
10115
10116    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10117            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10118                    throws PackageManagerException {
10119        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10120        // If the package has children and this is the first dive in the function
10121        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10122        // whether all packages (parent and children) would be successfully scanned
10123        // before the actual scan since scanning mutates internal state and we want
10124        // to atomically install the package and its children.
10125        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10126            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10127                scanFlags |= SCAN_CHECK_ONLY;
10128            }
10129        } else {
10130            scanFlags &= ~SCAN_CHECK_ONLY;
10131        }
10132
10133        final PackageParser.Package scannedPkg;
10134        try {
10135            // Scan the parent
10136            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10137            // Scan the children
10138            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10139            for (int i = 0; i < childCount; i++) {
10140                PackageParser.Package childPkg = pkg.childPackages.get(i);
10141                scanPackageLI(childPkg, policyFlags,
10142                        scanFlags, currentTime, user);
10143            }
10144        } finally {
10145            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10146        }
10147
10148        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10149            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10150        }
10151
10152        return scannedPkg;
10153    }
10154
10155    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10156            int scanFlags, long currentTime, @Nullable UserHandle user)
10157                    throws PackageManagerException {
10158        boolean success = false;
10159        try {
10160            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10161                    currentTime, user);
10162            success = true;
10163            return res;
10164        } finally {
10165            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10166                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10167                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10168                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10169                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10170            }
10171        }
10172    }
10173
10174    /**
10175     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10176     */
10177    private static boolean apkHasCode(String fileName) {
10178        StrictJarFile jarFile = null;
10179        try {
10180            jarFile = new StrictJarFile(fileName,
10181                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10182            return jarFile.findEntry("classes.dex") != null;
10183        } catch (IOException ignore) {
10184        } finally {
10185            try {
10186                if (jarFile != null) {
10187                    jarFile.close();
10188                }
10189            } catch (IOException ignore) {}
10190        }
10191        return false;
10192    }
10193
10194    /**
10195     * Enforces code policy for the package. This ensures that if an APK has
10196     * declared hasCode="true" in its manifest that the APK actually contains
10197     * code.
10198     *
10199     * @throws PackageManagerException If bytecode could not be found when it should exist
10200     */
10201    private static void assertCodePolicy(PackageParser.Package pkg)
10202            throws PackageManagerException {
10203        final boolean shouldHaveCode =
10204                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10205        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10206            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10207                    "Package " + pkg.baseCodePath + " code is missing");
10208        }
10209
10210        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10211            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10212                final boolean splitShouldHaveCode =
10213                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10214                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10215                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10216                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10217                }
10218            }
10219        }
10220    }
10221
10222    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10223            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10224                    throws PackageManagerException {
10225        if (DEBUG_PACKAGE_SCANNING) {
10226            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10227                Log.d(TAG, "Scanning package " + pkg.packageName);
10228        }
10229
10230        applyPolicy(pkg, policyFlags);
10231
10232        assertPackageIsValid(pkg, policyFlags, scanFlags);
10233
10234        // Initialize package source and resource directories
10235        final File scanFile = new File(pkg.codePath);
10236        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10237        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10238
10239        SharedUserSetting suid = null;
10240        PackageSetting pkgSetting = null;
10241
10242        // Getting the package setting may have a side-effect, so if we
10243        // are only checking if scan would succeed, stash a copy of the
10244        // old setting to restore at the end.
10245        PackageSetting nonMutatedPs = null;
10246
10247        // We keep references to the derived CPU Abis from settings in oder to reuse
10248        // them in the case where we're not upgrading or booting for the first time.
10249        String primaryCpuAbiFromSettings = null;
10250        String secondaryCpuAbiFromSettings = null;
10251
10252        // writer
10253        synchronized (mPackages) {
10254            if (pkg.mSharedUserId != null) {
10255                // SIDE EFFECTS; may potentially allocate a new shared user
10256                suid = mSettings.getSharedUserLPw(
10257                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10258                if (DEBUG_PACKAGE_SCANNING) {
10259                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10260                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10261                                + "): packages=" + suid.packages);
10262                }
10263            }
10264
10265            // Check if we are renaming from an original package name.
10266            PackageSetting origPackage = null;
10267            String realName = null;
10268            if (pkg.mOriginalPackages != null) {
10269                // This package may need to be renamed to a previously
10270                // installed name.  Let's check on that...
10271                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10272                if (pkg.mOriginalPackages.contains(renamed)) {
10273                    // This package had originally been installed as the
10274                    // original name, and we have already taken care of
10275                    // transitioning to the new one.  Just update the new
10276                    // one to continue using the old name.
10277                    realName = pkg.mRealPackage;
10278                    if (!pkg.packageName.equals(renamed)) {
10279                        // Callers into this function may have already taken
10280                        // care of renaming the package; only do it here if
10281                        // it is not already done.
10282                        pkg.setPackageName(renamed);
10283                    }
10284                } else {
10285                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10286                        if ((origPackage = mSettings.getPackageLPr(
10287                                pkg.mOriginalPackages.get(i))) != null) {
10288                            // We do have the package already installed under its
10289                            // original name...  should we use it?
10290                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10291                                // New package is not compatible with original.
10292                                origPackage = null;
10293                                continue;
10294                            } else if (origPackage.sharedUser != null) {
10295                                // Make sure uid is compatible between packages.
10296                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10297                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10298                                            + " to " + pkg.packageName + ": old uid "
10299                                            + origPackage.sharedUser.name
10300                                            + " differs from " + pkg.mSharedUserId);
10301                                    origPackage = null;
10302                                    continue;
10303                                }
10304                                // TODO: Add case when shared user id is added [b/28144775]
10305                            } else {
10306                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10307                                        + pkg.packageName + " to old name " + origPackage.name);
10308                            }
10309                            break;
10310                        }
10311                    }
10312                }
10313            }
10314
10315            if (mTransferedPackages.contains(pkg.packageName)) {
10316                Slog.w(TAG, "Package " + pkg.packageName
10317                        + " was transferred to another, but its .apk remains");
10318            }
10319
10320            // See comments in nonMutatedPs declaration
10321            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10322                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10323                if (foundPs != null) {
10324                    nonMutatedPs = new PackageSetting(foundPs);
10325                }
10326            }
10327
10328            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10329                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10330                if (foundPs != null) {
10331                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10332                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10333                }
10334            }
10335
10336            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10337            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10338                PackageManagerService.reportSettingsProblem(Log.WARN,
10339                        "Package " + pkg.packageName + " shared user changed from "
10340                                + (pkgSetting.sharedUser != null
10341                                        ? pkgSetting.sharedUser.name : "<nothing>")
10342                                + " to "
10343                                + (suid != null ? suid.name : "<nothing>")
10344                                + "; replacing with new");
10345                pkgSetting = null;
10346            }
10347            final PackageSetting oldPkgSetting =
10348                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10349            final PackageSetting disabledPkgSetting =
10350                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10351
10352            String[] usesStaticLibraries = null;
10353            if (pkg.usesStaticLibraries != null) {
10354                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10355                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10356            }
10357
10358            if (pkgSetting == null) {
10359                final String parentPackageName = (pkg.parentPackage != null)
10360                        ? pkg.parentPackage.packageName : null;
10361                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10362                // REMOVE SharedUserSetting from method; update in a separate call
10363                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10364                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10365                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10366                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10367                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10368                        true /*allowInstall*/, instantApp, parentPackageName,
10369                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10370                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10371                // SIDE EFFECTS; updates system state; move elsewhere
10372                if (origPackage != null) {
10373                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10374                }
10375                mSettings.addUserToSettingLPw(pkgSetting);
10376            } else {
10377                // REMOVE SharedUserSetting from method; update in a separate call.
10378                //
10379                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10380                // secondaryCpuAbi are not known at this point so we always update them
10381                // to null here, only to reset them at a later point.
10382                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10383                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10384                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10385                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10386                        UserManagerService.getInstance(), usesStaticLibraries,
10387                        pkg.usesStaticLibrariesVersions);
10388            }
10389            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10390            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10391
10392            // SIDE EFFECTS; modifies system state; move elsewhere
10393            if (pkgSetting.origPackage != null) {
10394                // If we are first transitioning from an original package,
10395                // fix up the new package's name now.  We need to do this after
10396                // looking up the package under its new name, so getPackageLP
10397                // can take care of fiddling things correctly.
10398                pkg.setPackageName(origPackage.name);
10399
10400                // File a report about this.
10401                String msg = "New package " + pkgSetting.realName
10402                        + " renamed to replace old package " + pkgSetting.name;
10403                reportSettingsProblem(Log.WARN, msg);
10404
10405                // Make a note of it.
10406                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10407                    mTransferedPackages.add(origPackage.name);
10408                }
10409
10410                // No longer need to retain this.
10411                pkgSetting.origPackage = null;
10412            }
10413
10414            // SIDE EFFECTS; modifies system state; move elsewhere
10415            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10416                // Make a note of it.
10417                mTransferedPackages.add(pkg.packageName);
10418            }
10419
10420            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10421                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10422            }
10423
10424            if ((scanFlags & SCAN_BOOTING) == 0
10425                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10426                // Check all shared libraries and map to their actual file path.
10427                // We only do this here for apps not on a system dir, because those
10428                // are the only ones that can fail an install due to this.  We
10429                // will take care of the system apps by updating all of their
10430                // library paths after the scan is done. Also during the initial
10431                // scan don't update any libs as we do this wholesale after all
10432                // apps are scanned to avoid dependency based scanning.
10433                updateSharedLibrariesLPr(pkg, null);
10434            }
10435
10436            if (mFoundPolicyFile) {
10437                SELinuxMMAC.assignSeInfoValue(pkg);
10438            }
10439            pkg.applicationInfo.uid = pkgSetting.appId;
10440            pkg.mExtras = pkgSetting;
10441
10442
10443            // Static shared libs have same package with different versions where
10444            // we internally use a synthetic package name to allow multiple versions
10445            // of the same package, therefore we need to compare signatures against
10446            // the package setting for the latest library version.
10447            PackageSetting signatureCheckPs = pkgSetting;
10448            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10449                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10450                if (libraryEntry != null) {
10451                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10452                }
10453            }
10454
10455            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10456                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10457                    // We just determined the app is signed correctly, so bring
10458                    // over the latest parsed certs.
10459                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10460                } else {
10461                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10462                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10463                                "Package " + pkg.packageName + " upgrade keys do not match the "
10464                                + "previously installed version");
10465                    } else {
10466                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10467                        String msg = "System package " + pkg.packageName
10468                                + " signature changed; retaining data.";
10469                        reportSettingsProblem(Log.WARN, msg);
10470                    }
10471                }
10472            } else {
10473                try {
10474                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10475                    verifySignaturesLP(signatureCheckPs, pkg);
10476                    // We just determined the app is signed correctly, so bring
10477                    // over the latest parsed certs.
10478                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10479                } catch (PackageManagerException e) {
10480                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10481                        throw e;
10482                    }
10483                    // The signature has changed, but this package is in the system
10484                    // image...  let's recover!
10485                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10486                    // However...  if this package is part of a shared user, but it
10487                    // doesn't match the signature of the shared user, let's fail.
10488                    // What this means is that you can't change the signatures
10489                    // associated with an overall shared user, which doesn't seem all
10490                    // that unreasonable.
10491                    if (signatureCheckPs.sharedUser != null) {
10492                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10493                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10494                            throw new PackageManagerException(
10495                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10496                                    "Signature mismatch for shared user: "
10497                                            + pkgSetting.sharedUser);
10498                        }
10499                    }
10500                    // File a report about this.
10501                    String msg = "System package " + pkg.packageName
10502                            + " signature changed; retaining data.";
10503                    reportSettingsProblem(Log.WARN, msg);
10504                }
10505            }
10506
10507            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10508                // This package wants to adopt ownership of permissions from
10509                // another package.
10510                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10511                    final String origName = pkg.mAdoptPermissions.get(i);
10512                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10513                    if (orig != null) {
10514                        if (verifyPackageUpdateLPr(orig, pkg)) {
10515                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10516                                    + pkg.packageName);
10517                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10518                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10519                        }
10520                    }
10521                }
10522            }
10523        }
10524
10525        pkg.applicationInfo.processName = fixProcessName(
10526                pkg.applicationInfo.packageName,
10527                pkg.applicationInfo.processName);
10528
10529        if (pkg != mPlatformPackage) {
10530            // Get all of our default paths setup
10531            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10532        }
10533
10534        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10535
10536        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10537            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10538                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10539                final boolean extractNativeLibs = !pkg.isLibrary();
10540                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10541                        mAppLib32InstallDir);
10542                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10543
10544                // Some system apps still use directory structure for native libraries
10545                // in which case we might end up not detecting abi solely based on apk
10546                // structure. Try to detect abi based on directory structure.
10547                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10548                        pkg.applicationInfo.primaryCpuAbi == null) {
10549                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10550                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10551                }
10552            } else {
10553                // This is not a first boot or an upgrade, don't bother deriving the
10554                // ABI during the scan. Instead, trust the value that was stored in the
10555                // package setting.
10556                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10557                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10558
10559                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10560
10561                if (DEBUG_ABI_SELECTION) {
10562                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10563                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10564                        pkg.applicationInfo.secondaryCpuAbi);
10565                }
10566            }
10567        } else {
10568            if ((scanFlags & SCAN_MOVE) != 0) {
10569                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10570                // but we already have this packages package info in the PackageSetting. We just
10571                // use that and derive the native library path based on the new codepath.
10572                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10573                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10574            }
10575
10576            // Set native library paths again. For moves, the path will be updated based on the
10577            // ABIs we've determined above. For non-moves, the path will be updated based on the
10578            // ABIs we determined during compilation, but the path will depend on the final
10579            // package path (after the rename away from the stage path).
10580            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10581        }
10582
10583        // This is a special case for the "system" package, where the ABI is
10584        // dictated by the zygote configuration (and init.rc). We should keep track
10585        // of this ABI so that we can deal with "normal" applications that run under
10586        // the same UID correctly.
10587        if (mPlatformPackage == pkg) {
10588            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10589                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10590        }
10591
10592        // If there's a mismatch between the abi-override in the package setting
10593        // and the abiOverride specified for the install. Warn about this because we
10594        // would've already compiled the app without taking the package setting into
10595        // account.
10596        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10597            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10598                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10599                        " for package " + pkg.packageName);
10600            }
10601        }
10602
10603        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10604        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10605        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10606
10607        // Copy the derived override back to the parsed package, so that we can
10608        // update the package settings accordingly.
10609        pkg.cpuAbiOverride = cpuAbiOverride;
10610
10611        if (DEBUG_ABI_SELECTION) {
10612            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10613                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10614                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10615        }
10616
10617        // Push the derived path down into PackageSettings so we know what to
10618        // clean up at uninstall time.
10619        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10620
10621        if (DEBUG_ABI_SELECTION) {
10622            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10623                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10624                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10625        }
10626
10627        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10628        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10629            // We don't do this here during boot because we can do it all
10630            // at once after scanning all existing packages.
10631            //
10632            // We also do this *before* we perform dexopt on this package, so that
10633            // we can avoid redundant dexopts, and also to make sure we've got the
10634            // code and package path correct.
10635            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10636        }
10637
10638        if (mFactoryTest && pkg.requestedPermissions.contains(
10639                android.Manifest.permission.FACTORY_TEST)) {
10640            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10641        }
10642
10643        if (isSystemApp(pkg)) {
10644            pkgSetting.isOrphaned = true;
10645        }
10646
10647        // Take care of first install / last update times.
10648        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10649        if (currentTime != 0) {
10650            if (pkgSetting.firstInstallTime == 0) {
10651                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10652            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10653                pkgSetting.lastUpdateTime = currentTime;
10654            }
10655        } else if (pkgSetting.firstInstallTime == 0) {
10656            // We need *something*.  Take time time stamp of the file.
10657            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10658        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10659            if (scanFileTime != pkgSetting.timeStamp) {
10660                // A package on the system image has changed; consider this
10661                // to be an update.
10662                pkgSetting.lastUpdateTime = scanFileTime;
10663            }
10664        }
10665        pkgSetting.setTimeStamp(scanFileTime);
10666
10667        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10668            if (nonMutatedPs != null) {
10669                synchronized (mPackages) {
10670                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10671                }
10672            }
10673        } else {
10674            final int userId = user == null ? 0 : user.getIdentifier();
10675            // Modify state for the given package setting
10676            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10677                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10678            if (pkgSetting.getInstantApp(userId)) {
10679                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10680            }
10681        }
10682        return pkg;
10683    }
10684
10685    /**
10686     * Applies policy to the parsed package based upon the given policy flags.
10687     * Ensures the package is in a good state.
10688     * <p>
10689     * Implementation detail: This method must NOT have any side effect. It would
10690     * ideally be static, but, it requires locks to read system state.
10691     */
10692    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10693        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10694            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10695            if (pkg.applicationInfo.isDirectBootAware()) {
10696                // we're direct boot aware; set for all components
10697                for (PackageParser.Service s : pkg.services) {
10698                    s.info.encryptionAware = s.info.directBootAware = true;
10699                }
10700                for (PackageParser.Provider p : pkg.providers) {
10701                    p.info.encryptionAware = p.info.directBootAware = true;
10702                }
10703                for (PackageParser.Activity a : pkg.activities) {
10704                    a.info.encryptionAware = a.info.directBootAware = true;
10705                }
10706                for (PackageParser.Activity r : pkg.receivers) {
10707                    r.info.encryptionAware = r.info.directBootAware = true;
10708                }
10709            }
10710        } else {
10711            // Only allow system apps to be flagged as core apps.
10712            pkg.coreApp = false;
10713            // clear flags not applicable to regular apps
10714            pkg.applicationInfo.privateFlags &=
10715                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10716            pkg.applicationInfo.privateFlags &=
10717                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10718        }
10719        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10720
10721        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10722            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10723        }
10724
10725        if (!isSystemApp(pkg)) {
10726            // Only system apps can use these features.
10727            pkg.mOriginalPackages = null;
10728            pkg.mRealPackage = null;
10729            pkg.mAdoptPermissions = null;
10730        }
10731    }
10732
10733    /**
10734     * Asserts the parsed package is valid according to the given policy. If the
10735     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10736     * <p>
10737     * Implementation detail: This method must NOT have any side effects. It would
10738     * ideally be static, but, it requires locks to read system state.
10739     *
10740     * @throws PackageManagerException If the package fails any of the validation checks
10741     */
10742    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10743            throws PackageManagerException {
10744        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10745            assertCodePolicy(pkg);
10746        }
10747
10748        if (pkg.applicationInfo.getCodePath() == null ||
10749                pkg.applicationInfo.getResourcePath() == null) {
10750            // Bail out. The resource and code paths haven't been set.
10751            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10752                    "Code and resource paths haven't been set correctly");
10753        }
10754
10755        // Make sure we're not adding any bogus keyset info
10756        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10757        ksms.assertScannedPackageValid(pkg);
10758
10759        synchronized (mPackages) {
10760            // The special "android" package can only be defined once
10761            if (pkg.packageName.equals("android")) {
10762                if (mAndroidApplication != null) {
10763                    Slog.w(TAG, "*************************************************");
10764                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10765                    Slog.w(TAG, " codePath=" + pkg.codePath);
10766                    Slog.w(TAG, "*************************************************");
10767                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10768                            "Core android package being redefined.  Skipping.");
10769                }
10770            }
10771
10772            // A package name must be unique; don't allow duplicates
10773            if (mPackages.containsKey(pkg.packageName)) {
10774                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10775                        "Application package " + pkg.packageName
10776                        + " already installed.  Skipping duplicate.");
10777            }
10778
10779            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10780                // Static libs have a synthetic package name containing the version
10781                // but we still want the base name to be unique.
10782                if (mPackages.containsKey(pkg.manifestPackageName)) {
10783                    throw new PackageManagerException(
10784                            "Duplicate static shared lib provider package");
10785                }
10786
10787                // Static shared libraries should have at least O target SDK
10788                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10789                    throw new PackageManagerException(
10790                            "Packages declaring static-shared libs must target O SDK or higher");
10791                }
10792
10793                // Package declaring static a shared lib cannot be instant apps
10794                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10795                    throw new PackageManagerException(
10796                            "Packages declaring static-shared libs cannot be instant apps");
10797                }
10798
10799                // Package declaring static a shared lib cannot be renamed since the package
10800                // name is synthetic and apps can't code around package manager internals.
10801                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10802                    throw new PackageManagerException(
10803                            "Packages declaring static-shared libs cannot be renamed");
10804                }
10805
10806                // Package declaring static a shared lib cannot declare child packages
10807                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10808                    throw new PackageManagerException(
10809                            "Packages declaring static-shared libs cannot have child packages");
10810                }
10811
10812                // Package declaring static a shared lib cannot declare dynamic libs
10813                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10814                    throw new PackageManagerException(
10815                            "Packages declaring static-shared libs cannot declare dynamic libs");
10816                }
10817
10818                // Package declaring static a shared lib cannot declare shared users
10819                if (pkg.mSharedUserId != null) {
10820                    throw new PackageManagerException(
10821                            "Packages declaring static-shared libs cannot declare shared users");
10822                }
10823
10824                // Static shared libs cannot declare activities
10825                if (!pkg.activities.isEmpty()) {
10826                    throw new PackageManagerException(
10827                            "Static shared libs cannot declare activities");
10828                }
10829
10830                // Static shared libs cannot declare services
10831                if (!pkg.services.isEmpty()) {
10832                    throw new PackageManagerException(
10833                            "Static shared libs cannot declare services");
10834                }
10835
10836                // Static shared libs cannot declare providers
10837                if (!pkg.providers.isEmpty()) {
10838                    throw new PackageManagerException(
10839                            "Static shared libs cannot declare content providers");
10840                }
10841
10842                // Static shared libs cannot declare receivers
10843                if (!pkg.receivers.isEmpty()) {
10844                    throw new PackageManagerException(
10845                            "Static shared libs cannot declare broadcast receivers");
10846                }
10847
10848                // Static shared libs cannot declare permission groups
10849                if (!pkg.permissionGroups.isEmpty()) {
10850                    throw new PackageManagerException(
10851                            "Static shared libs cannot declare permission groups");
10852                }
10853
10854                // Static shared libs cannot declare permissions
10855                if (!pkg.permissions.isEmpty()) {
10856                    throw new PackageManagerException(
10857                            "Static shared libs cannot declare permissions");
10858                }
10859
10860                // Static shared libs cannot declare protected broadcasts
10861                if (pkg.protectedBroadcasts != null) {
10862                    throw new PackageManagerException(
10863                            "Static shared libs cannot declare protected broadcasts");
10864                }
10865
10866                // Static shared libs cannot be overlay targets
10867                if (pkg.mOverlayTarget != null) {
10868                    throw new PackageManagerException(
10869                            "Static shared libs cannot be overlay targets");
10870                }
10871
10872                // The version codes must be ordered as lib versions
10873                int minVersionCode = Integer.MIN_VALUE;
10874                int maxVersionCode = Integer.MAX_VALUE;
10875
10876                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10877                        pkg.staticSharedLibName);
10878                if (versionedLib != null) {
10879                    final int versionCount = versionedLib.size();
10880                    for (int i = 0; i < versionCount; i++) {
10881                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10882                        final int libVersionCode = libInfo.getDeclaringPackage()
10883                                .getVersionCode();
10884                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10885                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10886                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10887                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10888                        } else {
10889                            minVersionCode = maxVersionCode = libVersionCode;
10890                            break;
10891                        }
10892                    }
10893                }
10894                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10895                    throw new PackageManagerException("Static shared"
10896                            + " lib version codes must be ordered as lib versions");
10897                }
10898            }
10899
10900            // Only privileged apps and updated privileged apps can add child packages.
10901            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10902                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10903                    throw new PackageManagerException("Only privileged apps can add child "
10904                            + "packages. Ignoring package " + pkg.packageName);
10905                }
10906                final int childCount = pkg.childPackages.size();
10907                for (int i = 0; i < childCount; i++) {
10908                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10909                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10910                            childPkg.packageName)) {
10911                        throw new PackageManagerException("Can't override child of "
10912                                + "another disabled app. Ignoring package " + pkg.packageName);
10913                    }
10914                }
10915            }
10916
10917            // If we're only installing presumed-existing packages, require that the
10918            // scanned APK is both already known and at the path previously established
10919            // for it.  Previously unknown packages we pick up normally, but if we have an
10920            // a priori expectation about this package's install presence, enforce it.
10921            // With a singular exception for new system packages. When an OTA contains
10922            // a new system package, we allow the codepath to change from a system location
10923            // to the user-installed location. If we don't allow this change, any newer,
10924            // user-installed version of the application will be ignored.
10925            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10926                if (mExpectingBetter.containsKey(pkg.packageName)) {
10927                    logCriticalInfo(Log.WARN,
10928                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10929                } else {
10930                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10931                    if (known != null) {
10932                        if (DEBUG_PACKAGE_SCANNING) {
10933                            Log.d(TAG, "Examining " + pkg.codePath
10934                                    + " and requiring known paths " + known.codePathString
10935                                    + " & " + known.resourcePathString);
10936                        }
10937                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10938                                || !pkg.applicationInfo.getResourcePath().equals(
10939                                        known.resourcePathString)) {
10940                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10941                                    "Application package " + pkg.packageName
10942                                    + " found at " + pkg.applicationInfo.getCodePath()
10943                                    + " but expected at " + known.codePathString
10944                                    + "; ignoring.");
10945                        }
10946                    }
10947                }
10948            }
10949
10950            // Verify that this new package doesn't have any content providers
10951            // that conflict with existing packages.  Only do this if the
10952            // package isn't already installed, since we don't want to break
10953            // things that are installed.
10954            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10955                final int N = pkg.providers.size();
10956                int i;
10957                for (i=0; i<N; i++) {
10958                    PackageParser.Provider p = pkg.providers.get(i);
10959                    if (p.info.authority != null) {
10960                        String names[] = p.info.authority.split(";");
10961                        for (int j = 0; j < names.length; j++) {
10962                            if (mProvidersByAuthority.containsKey(names[j])) {
10963                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10964                                final String otherPackageName =
10965                                        ((other != null && other.getComponentName() != null) ?
10966                                                other.getComponentName().getPackageName() : "?");
10967                                throw new PackageManagerException(
10968                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10969                                        "Can't install because provider name " + names[j]
10970                                                + " (in package " + pkg.applicationInfo.packageName
10971                                                + ") is already used by " + otherPackageName);
10972                            }
10973                        }
10974                    }
10975                }
10976            }
10977        }
10978    }
10979
10980    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10981            int type, String declaringPackageName, int declaringVersionCode) {
10982        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10983        if (versionedLib == null) {
10984            versionedLib = new SparseArray<>();
10985            mSharedLibraries.put(name, versionedLib);
10986            if (type == SharedLibraryInfo.TYPE_STATIC) {
10987                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10988            }
10989        } else if (versionedLib.indexOfKey(version) >= 0) {
10990            return false;
10991        }
10992        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10993                version, type, declaringPackageName, declaringVersionCode);
10994        versionedLib.put(version, libEntry);
10995        return true;
10996    }
10997
10998    private boolean removeSharedLibraryLPw(String name, int version) {
10999        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11000        if (versionedLib == null) {
11001            return false;
11002        }
11003        final int libIdx = versionedLib.indexOfKey(version);
11004        if (libIdx < 0) {
11005            return false;
11006        }
11007        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11008        versionedLib.remove(version);
11009        if (versionedLib.size() <= 0) {
11010            mSharedLibraries.remove(name);
11011            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11012                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11013                        .getPackageName());
11014            }
11015        }
11016        return true;
11017    }
11018
11019    /**
11020     * Adds a scanned package to the system. When this method is finished, the package will
11021     * be available for query, resolution, etc...
11022     */
11023    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11024            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11025        final String pkgName = pkg.packageName;
11026        if (mCustomResolverComponentName != null &&
11027                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11028            setUpCustomResolverActivity(pkg);
11029        }
11030
11031        if (pkg.packageName.equals("android")) {
11032            synchronized (mPackages) {
11033                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11034                    // Set up information for our fall-back user intent resolution activity.
11035                    mPlatformPackage = pkg;
11036                    pkg.mVersionCode = mSdkVersion;
11037                    mAndroidApplication = pkg.applicationInfo;
11038                    if (!mResolverReplaced) {
11039                        mResolveActivity.applicationInfo = mAndroidApplication;
11040                        mResolveActivity.name = ResolverActivity.class.getName();
11041                        mResolveActivity.packageName = mAndroidApplication.packageName;
11042                        mResolveActivity.processName = "system:ui";
11043                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11044                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11045                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11046                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11047                        mResolveActivity.exported = true;
11048                        mResolveActivity.enabled = true;
11049                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11050                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11051                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11052                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11053                                | ActivityInfo.CONFIG_ORIENTATION
11054                                | ActivityInfo.CONFIG_KEYBOARD
11055                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11056                        mResolveInfo.activityInfo = mResolveActivity;
11057                        mResolveInfo.priority = 0;
11058                        mResolveInfo.preferredOrder = 0;
11059                        mResolveInfo.match = 0;
11060                        mResolveComponentName = new ComponentName(
11061                                mAndroidApplication.packageName, mResolveActivity.name);
11062                    }
11063                }
11064            }
11065        }
11066
11067        ArrayList<PackageParser.Package> clientLibPkgs = null;
11068        // writer
11069        synchronized (mPackages) {
11070            boolean hasStaticSharedLibs = false;
11071
11072            // Any app can add new static shared libraries
11073            if (pkg.staticSharedLibName != null) {
11074                // Static shared libs don't allow renaming as they have synthetic package
11075                // names to allow install of multiple versions, so use name from manifest.
11076                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11077                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11078                        pkg.manifestPackageName, pkg.mVersionCode)) {
11079                    hasStaticSharedLibs = true;
11080                } else {
11081                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11082                                + pkg.staticSharedLibName + " already exists; skipping");
11083                }
11084                // Static shared libs cannot be updated once installed since they
11085                // use synthetic package name which includes the version code, so
11086                // not need to update other packages's shared lib dependencies.
11087            }
11088
11089            if (!hasStaticSharedLibs
11090                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11091                // Only system apps can add new dynamic shared libraries.
11092                if (pkg.libraryNames != null) {
11093                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11094                        String name = pkg.libraryNames.get(i);
11095                        boolean allowed = false;
11096                        if (pkg.isUpdatedSystemApp()) {
11097                            // New library entries can only be added through the
11098                            // system image.  This is important to get rid of a lot
11099                            // of nasty edge cases: for example if we allowed a non-
11100                            // system update of the app to add a library, then uninstalling
11101                            // the update would make the library go away, and assumptions
11102                            // we made such as through app install filtering would now
11103                            // have allowed apps on the device which aren't compatible
11104                            // with it.  Better to just have the restriction here, be
11105                            // conservative, and create many fewer cases that can negatively
11106                            // impact the user experience.
11107                            final PackageSetting sysPs = mSettings
11108                                    .getDisabledSystemPkgLPr(pkg.packageName);
11109                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11110                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11111                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11112                                        allowed = true;
11113                                        break;
11114                                    }
11115                                }
11116                            }
11117                        } else {
11118                            allowed = true;
11119                        }
11120                        if (allowed) {
11121                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11122                                    SharedLibraryInfo.VERSION_UNDEFINED,
11123                                    SharedLibraryInfo.TYPE_DYNAMIC,
11124                                    pkg.packageName, pkg.mVersionCode)) {
11125                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11126                                        + name + " already exists; skipping");
11127                            }
11128                        } else {
11129                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11130                                    + name + " that is not declared on system image; skipping");
11131                        }
11132                    }
11133
11134                    if ((scanFlags & SCAN_BOOTING) == 0) {
11135                        // If we are not booting, we need to update any applications
11136                        // that are clients of our shared library.  If we are booting,
11137                        // this will all be done once the scan is complete.
11138                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11139                    }
11140                }
11141            }
11142        }
11143
11144        if ((scanFlags & SCAN_BOOTING) != 0) {
11145            // No apps can run during boot scan, so they don't need to be frozen
11146        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11147            // Caller asked to not kill app, so it's probably not frozen
11148        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11149            // Caller asked us to ignore frozen check for some reason; they
11150            // probably didn't know the package name
11151        } else {
11152            // We're doing major surgery on this package, so it better be frozen
11153            // right now to keep it from launching
11154            checkPackageFrozen(pkgName);
11155        }
11156
11157        // Also need to kill any apps that are dependent on the library.
11158        if (clientLibPkgs != null) {
11159            for (int i=0; i<clientLibPkgs.size(); i++) {
11160                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11161                killApplication(clientPkg.applicationInfo.packageName,
11162                        clientPkg.applicationInfo.uid, "update lib");
11163            }
11164        }
11165
11166        // writer
11167        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11168
11169        synchronized (mPackages) {
11170            // We don't expect installation to fail beyond this point
11171
11172            // Add the new setting to mSettings
11173            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11174            // Add the new setting to mPackages
11175            mPackages.put(pkg.applicationInfo.packageName, pkg);
11176            // Make sure we don't accidentally delete its data.
11177            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11178            while (iter.hasNext()) {
11179                PackageCleanItem item = iter.next();
11180                if (pkgName.equals(item.packageName)) {
11181                    iter.remove();
11182                }
11183            }
11184
11185            // Add the package's KeySets to the global KeySetManagerService
11186            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11187            ksms.addScannedPackageLPw(pkg);
11188
11189            int N = pkg.providers.size();
11190            StringBuilder r = null;
11191            int i;
11192            for (i=0; i<N; i++) {
11193                PackageParser.Provider p = pkg.providers.get(i);
11194                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11195                        p.info.processName);
11196                mProviders.addProvider(p);
11197                p.syncable = p.info.isSyncable;
11198                if (p.info.authority != null) {
11199                    String names[] = p.info.authority.split(";");
11200                    p.info.authority = null;
11201                    for (int j = 0; j < names.length; j++) {
11202                        if (j == 1 && p.syncable) {
11203                            // We only want the first authority for a provider to possibly be
11204                            // syncable, so if we already added this provider using a different
11205                            // authority clear the syncable flag. We copy the provider before
11206                            // changing it because the mProviders object contains a reference
11207                            // to a provider that we don't want to change.
11208                            // Only do this for the second authority since the resulting provider
11209                            // object can be the same for all future authorities for this provider.
11210                            p = new PackageParser.Provider(p);
11211                            p.syncable = false;
11212                        }
11213                        if (!mProvidersByAuthority.containsKey(names[j])) {
11214                            mProvidersByAuthority.put(names[j], p);
11215                            if (p.info.authority == null) {
11216                                p.info.authority = names[j];
11217                            } else {
11218                                p.info.authority = p.info.authority + ";" + names[j];
11219                            }
11220                            if (DEBUG_PACKAGE_SCANNING) {
11221                                if (chatty)
11222                                    Log.d(TAG, "Registered content provider: " + names[j]
11223                                            + ", className = " + p.info.name + ", isSyncable = "
11224                                            + p.info.isSyncable);
11225                            }
11226                        } else {
11227                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11228                            Slog.w(TAG, "Skipping provider name " + names[j] +
11229                                    " (in package " + pkg.applicationInfo.packageName +
11230                                    "): name already used by "
11231                                    + ((other != null && other.getComponentName() != null)
11232                                            ? other.getComponentName().getPackageName() : "?"));
11233                        }
11234                    }
11235                }
11236                if (chatty) {
11237                    if (r == null) {
11238                        r = new StringBuilder(256);
11239                    } else {
11240                        r.append(' ');
11241                    }
11242                    r.append(p.info.name);
11243                }
11244            }
11245            if (r != null) {
11246                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11247            }
11248
11249            N = pkg.services.size();
11250            r = null;
11251            for (i=0; i<N; i++) {
11252                PackageParser.Service s = pkg.services.get(i);
11253                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11254                        s.info.processName);
11255                mServices.addService(s);
11256                if (chatty) {
11257                    if (r == null) {
11258                        r = new StringBuilder(256);
11259                    } else {
11260                        r.append(' ');
11261                    }
11262                    r.append(s.info.name);
11263                }
11264            }
11265            if (r != null) {
11266                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11267            }
11268
11269            N = pkg.receivers.size();
11270            r = null;
11271            for (i=0; i<N; i++) {
11272                PackageParser.Activity a = pkg.receivers.get(i);
11273                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11274                        a.info.processName);
11275                mReceivers.addActivity(a, "receiver");
11276                if (chatty) {
11277                    if (r == null) {
11278                        r = new StringBuilder(256);
11279                    } else {
11280                        r.append(' ');
11281                    }
11282                    r.append(a.info.name);
11283                }
11284            }
11285            if (r != null) {
11286                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11287            }
11288
11289            N = pkg.activities.size();
11290            r = null;
11291            for (i=0; i<N; i++) {
11292                PackageParser.Activity a = pkg.activities.get(i);
11293                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11294                        a.info.processName);
11295                mActivities.addActivity(a, "activity");
11296                if (chatty) {
11297                    if (r == null) {
11298                        r = new StringBuilder(256);
11299                    } else {
11300                        r.append(' ');
11301                    }
11302                    r.append(a.info.name);
11303                }
11304            }
11305            if (r != null) {
11306                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11307            }
11308
11309            N = pkg.permissionGroups.size();
11310            r = null;
11311            for (i=0; i<N; i++) {
11312                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11313                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11314                final String curPackageName = cur == null ? null : cur.info.packageName;
11315                // Dont allow ephemeral apps to define new permission groups.
11316                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11317                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11318                            + pg.info.packageName
11319                            + " ignored: instant apps cannot define new permission groups.");
11320                    continue;
11321                }
11322                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11323                if (cur == null || isPackageUpdate) {
11324                    mPermissionGroups.put(pg.info.name, pg);
11325                    if (chatty) {
11326                        if (r == null) {
11327                            r = new StringBuilder(256);
11328                        } else {
11329                            r.append(' ');
11330                        }
11331                        if (isPackageUpdate) {
11332                            r.append("UPD:");
11333                        }
11334                        r.append(pg.info.name);
11335                    }
11336                } else {
11337                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11338                            + pg.info.packageName + " ignored: original from "
11339                            + cur.info.packageName);
11340                    if (chatty) {
11341                        if (r == null) {
11342                            r = new StringBuilder(256);
11343                        } else {
11344                            r.append(' ');
11345                        }
11346                        r.append("DUP:");
11347                        r.append(pg.info.name);
11348                    }
11349                }
11350            }
11351            if (r != null) {
11352                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11353            }
11354
11355            N = pkg.permissions.size();
11356            r = null;
11357            for (i=0; i<N; i++) {
11358                PackageParser.Permission p = pkg.permissions.get(i);
11359
11360                // Dont allow ephemeral apps to define new permissions.
11361                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11362                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11363                            + p.info.packageName
11364                            + " ignored: instant apps cannot define new permissions.");
11365                    continue;
11366                }
11367
11368                // Assume by default that we did not install this permission into the system.
11369                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11370
11371                // Now that permission groups have a special meaning, we ignore permission
11372                // groups for legacy apps to prevent unexpected behavior. In particular,
11373                // permissions for one app being granted to someone just because they happen
11374                // to be in a group defined by another app (before this had no implications).
11375                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11376                    p.group = mPermissionGroups.get(p.info.group);
11377                    // Warn for a permission in an unknown group.
11378                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11379                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11380                                + p.info.packageName + " in an unknown group " + p.info.group);
11381                    }
11382                }
11383
11384                ArrayMap<String, BasePermission> permissionMap =
11385                        p.tree ? mSettings.mPermissionTrees
11386                                : mSettings.mPermissions;
11387                BasePermission bp = permissionMap.get(p.info.name);
11388
11389                // Allow system apps to redefine non-system permissions
11390                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11391                    final boolean currentOwnerIsSystem = (bp.perm != null
11392                            && isSystemApp(bp.perm.owner));
11393                    if (isSystemApp(p.owner)) {
11394                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11395                            // It's a built-in permission and no owner, take ownership now
11396                            bp.packageSetting = pkgSetting;
11397                            bp.perm = p;
11398                            bp.uid = pkg.applicationInfo.uid;
11399                            bp.sourcePackage = p.info.packageName;
11400                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11401                        } else if (!currentOwnerIsSystem) {
11402                            String msg = "New decl " + p.owner + " of permission  "
11403                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11404                            reportSettingsProblem(Log.WARN, msg);
11405                            bp = null;
11406                        }
11407                    }
11408                }
11409
11410                if (bp == null) {
11411                    bp = new BasePermission(p.info.name, p.info.packageName,
11412                            BasePermission.TYPE_NORMAL);
11413                    permissionMap.put(p.info.name, bp);
11414                }
11415
11416                if (bp.perm == null) {
11417                    if (bp.sourcePackage == null
11418                            || bp.sourcePackage.equals(p.info.packageName)) {
11419                        BasePermission tree = findPermissionTreeLP(p.info.name);
11420                        if (tree == null
11421                                || tree.sourcePackage.equals(p.info.packageName)) {
11422                            bp.packageSetting = pkgSetting;
11423                            bp.perm = p;
11424                            bp.uid = pkg.applicationInfo.uid;
11425                            bp.sourcePackage = p.info.packageName;
11426                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11427                            if (chatty) {
11428                                if (r == null) {
11429                                    r = new StringBuilder(256);
11430                                } else {
11431                                    r.append(' ');
11432                                }
11433                                r.append(p.info.name);
11434                            }
11435                        } else {
11436                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11437                                    + p.info.packageName + " ignored: base tree "
11438                                    + tree.name + " is from package "
11439                                    + tree.sourcePackage);
11440                        }
11441                    } else {
11442                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11443                                + p.info.packageName + " ignored: original from "
11444                                + bp.sourcePackage);
11445                    }
11446                } else if (chatty) {
11447                    if (r == null) {
11448                        r = new StringBuilder(256);
11449                    } else {
11450                        r.append(' ');
11451                    }
11452                    r.append("DUP:");
11453                    r.append(p.info.name);
11454                }
11455                if (bp.perm == p) {
11456                    bp.protectionLevel = p.info.protectionLevel;
11457                }
11458            }
11459
11460            if (r != null) {
11461                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11462            }
11463
11464            N = pkg.instrumentation.size();
11465            r = null;
11466            for (i=0; i<N; i++) {
11467                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11468                a.info.packageName = pkg.applicationInfo.packageName;
11469                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11470                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11471                a.info.splitNames = pkg.splitNames;
11472                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11473                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11474                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11475                a.info.dataDir = pkg.applicationInfo.dataDir;
11476                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11477                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11478                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11479                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11480                mInstrumentation.put(a.getComponentName(), a);
11481                if (chatty) {
11482                    if (r == null) {
11483                        r = new StringBuilder(256);
11484                    } else {
11485                        r.append(' ');
11486                    }
11487                    r.append(a.info.name);
11488                }
11489            }
11490            if (r != null) {
11491                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11492            }
11493
11494            if (pkg.protectedBroadcasts != null) {
11495                N = pkg.protectedBroadcasts.size();
11496                synchronized (mProtectedBroadcasts) {
11497                    for (i = 0; i < N; i++) {
11498                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11499                    }
11500                }
11501            }
11502        }
11503
11504        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11505    }
11506
11507    /**
11508     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11509     * is derived purely on the basis of the contents of {@code scanFile} and
11510     * {@code cpuAbiOverride}.
11511     *
11512     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11513     */
11514    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11515                                 String cpuAbiOverride, boolean extractLibs,
11516                                 File appLib32InstallDir)
11517            throws PackageManagerException {
11518        // Give ourselves some initial paths; we'll come back for another
11519        // pass once we've determined ABI below.
11520        setNativeLibraryPaths(pkg, appLib32InstallDir);
11521
11522        // We would never need to extract libs for forward-locked and external packages,
11523        // since the container service will do it for us. We shouldn't attempt to
11524        // extract libs from system app when it was not updated.
11525        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11526                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11527            extractLibs = false;
11528        }
11529
11530        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11531        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11532
11533        NativeLibraryHelper.Handle handle = null;
11534        try {
11535            handle = NativeLibraryHelper.Handle.create(pkg);
11536            // TODO(multiArch): This can be null for apps that didn't go through the
11537            // usual installation process. We can calculate it again, like we
11538            // do during install time.
11539            //
11540            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11541            // unnecessary.
11542            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11543
11544            // Null out the abis so that they can be recalculated.
11545            pkg.applicationInfo.primaryCpuAbi = null;
11546            pkg.applicationInfo.secondaryCpuAbi = null;
11547            if (isMultiArch(pkg.applicationInfo)) {
11548                // Warn if we've set an abiOverride for multi-lib packages..
11549                // By definition, we need to copy both 32 and 64 bit libraries for
11550                // such packages.
11551                if (pkg.cpuAbiOverride != null
11552                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11553                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11554                }
11555
11556                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11557                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11558                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11559                    if (extractLibs) {
11560                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11561                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11562                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11563                                useIsaSpecificSubdirs);
11564                    } else {
11565                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11566                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11567                    }
11568                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11569                }
11570
11571                // Shared library native code should be in the APK zip aligned
11572                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11573                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11574                            "Shared library native lib extraction not supported");
11575                }
11576
11577                maybeThrowExceptionForMultiArchCopy(
11578                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11579
11580                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11581                    if (extractLibs) {
11582                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11583                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11584                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11585                                useIsaSpecificSubdirs);
11586                    } else {
11587                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11588                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11589                    }
11590                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11591                }
11592
11593                maybeThrowExceptionForMultiArchCopy(
11594                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11595
11596                if (abi64 >= 0) {
11597                    // Shared library native libs should be in the APK zip aligned
11598                    if (extractLibs && pkg.isLibrary()) {
11599                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11600                                "Shared library native lib extraction not supported");
11601                    }
11602                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11603                }
11604
11605                if (abi32 >= 0) {
11606                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11607                    if (abi64 >= 0) {
11608                        if (pkg.use32bitAbi) {
11609                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11610                            pkg.applicationInfo.primaryCpuAbi = abi;
11611                        } else {
11612                            pkg.applicationInfo.secondaryCpuAbi = abi;
11613                        }
11614                    } else {
11615                        pkg.applicationInfo.primaryCpuAbi = abi;
11616                    }
11617                }
11618            } else {
11619                String[] abiList = (cpuAbiOverride != null) ?
11620                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11621
11622                // Enable gross and lame hacks for apps that are built with old
11623                // SDK tools. We must scan their APKs for renderscript bitcode and
11624                // not launch them if it's present. Don't bother checking on devices
11625                // that don't have 64 bit support.
11626                boolean needsRenderScriptOverride = false;
11627                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11628                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11629                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11630                    needsRenderScriptOverride = true;
11631                }
11632
11633                final int copyRet;
11634                if (extractLibs) {
11635                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11636                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11637                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11638                } else {
11639                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11640                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11641                }
11642                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11643
11644                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11645                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11646                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11647                }
11648
11649                if (copyRet >= 0) {
11650                    // Shared libraries that have native libs must be multi-architecture
11651                    if (pkg.isLibrary()) {
11652                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11653                                "Shared library with native libs must be multiarch");
11654                    }
11655                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11656                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11657                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11658                } else if (needsRenderScriptOverride) {
11659                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11660                }
11661            }
11662        } catch (IOException ioe) {
11663            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11664        } finally {
11665            IoUtils.closeQuietly(handle);
11666        }
11667
11668        // Now that we've calculated the ABIs and determined if it's an internal app,
11669        // we will go ahead and populate the nativeLibraryPath.
11670        setNativeLibraryPaths(pkg, appLib32InstallDir);
11671    }
11672
11673    /**
11674     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11675     * i.e, so that all packages can be run inside a single process if required.
11676     *
11677     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11678     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11679     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11680     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11681     * updating a package that belongs to a shared user.
11682     *
11683     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11684     * adds unnecessary complexity.
11685     */
11686    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11687            PackageParser.Package scannedPackage) {
11688        String requiredInstructionSet = null;
11689        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11690            requiredInstructionSet = VMRuntime.getInstructionSet(
11691                     scannedPackage.applicationInfo.primaryCpuAbi);
11692        }
11693
11694        PackageSetting requirer = null;
11695        for (PackageSetting ps : packagesForUser) {
11696            // If packagesForUser contains scannedPackage, we skip it. This will happen
11697            // when scannedPackage is an update of an existing package. Without this check,
11698            // we will never be able to change the ABI of any package belonging to a shared
11699            // user, even if it's compatible with other packages.
11700            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11701                if (ps.primaryCpuAbiString == null) {
11702                    continue;
11703                }
11704
11705                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11706                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11707                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11708                    // this but there's not much we can do.
11709                    String errorMessage = "Instruction set mismatch, "
11710                            + ((requirer == null) ? "[caller]" : requirer)
11711                            + " requires " + requiredInstructionSet + " whereas " + ps
11712                            + " requires " + instructionSet;
11713                    Slog.w(TAG, errorMessage);
11714                }
11715
11716                if (requiredInstructionSet == null) {
11717                    requiredInstructionSet = instructionSet;
11718                    requirer = ps;
11719                }
11720            }
11721        }
11722
11723        if (requiredInstructionSet != null) {
11724            String adjustedAbi;
11725            if (requirer != null) {
11726                // requirer != null implies that either scannedPackage was null or that scannedPackage
11727                // did not require an ABI, in which case we have to adjust scannedPackage to match
11728                // the ABI of the set (which is the same as requirer's ABI)
11729                adjustedAbi = requirer.primaryCpuAbiString;
11730                if (scannedPackage != null) {
11731                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11732                }
11733            } else {
11734                // requirer == null implies that we're updating all ABIs in the set to
11735                // match scannedPackage.
11736                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11737            }
11738
11739            for (PackageSetting ps : packagesForUser) {
11740                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11741                    if (ps.primaryCpuAbiString != null) {
11742                        continue;
11743                    }
11744
11745                    ps.primaryCpuAbiString = adjustedAbi;
11746                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11747                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11748                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11749                        if (DEBUG_ABI_SELECTION) {
11750                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11751                                    + " (requirer="
11752                                    + (requirer != null ? requirer.pkg : "null")
11753                                    + ", scannedPackage="
11754                                    + (scannedPackage != null ? scannedPackage : "null")
11755                                    + ")");
11756                        }
11757                        try {
11758                            mInstaller.rmdex(ps.codePathString,
11759                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11760                        } catch (InstallerException ignored) {
11761                        }
11762                    }
11763                }
11764            }
11765        }
11766    }
11767
11768    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11769        synchronized (mPackages) {
11770            mResolverReplaced = true;
11771            // Set up information for custom user intent resolution activity.
11772            mResolveActivity.applicationInfo = pkg.applicationInfo;
11773            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11774            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11775            mResolveActivity.processName = pkg.applicationInfo.packageName;
11776            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11777            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11778                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11779            mResolveActivity.theme = 0;
11780            mResolveActivity.exported = true;
11781            mResolveActivity.enabled = true;
11782            mResolveInfo.activityInfo = mResolveActivity;
11783            mResolveInfo.priority = 0;
11784            mResolveInfo.preferredOrder = 0;
11785            mResolveInfo.match = 0;
11786            mResolveComponentName = mCustomResolverComponentName;
11787            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11788                    mResolveComponentName);
11789        }
11790    }
11791
11792    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11793        if (installerActivity == null) {
11794            if (DEBUG_EPHEMERAL) {
11795                Slog.d(TAG, "Clear ephemeral installer activity");
11796            }
11797            mInstantAppInstallerActivity = null;
11798            return;
11799        }
11800
11801        if (DEBUG_EPHEMERAL) {
11802            Slog.d(TAG, "Set ephemeral installer activity: "
11803                    + installerActivity.getComponentName());
11804        }
11805        // Set up information for ephemeral installer activity
11806        mInstantAppInstallerActivity = installerActivity;
11807        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11808                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11809        mInstantAppInstallerActivity.exported = true;
11810        mInstantAppInstallerActivity.enabled = true;
11811        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11812        mInstantAppInstallerInfo.priority = 0;
11813        mInstantAppInstallerInfo.preferredOrder = 1;
11814        mInstantAppInstallerInfo.isDefault = true;
11815        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11816                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11817    }
11818
11819    private static String calculateBundledApkRoot(final String codePathString) {
11820        final File codePath = new File(codePathString);
11821        final File codeRoot;
11822        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11823            codeRoot = Environment.getRootDirectory();
11824        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11825            codeRoot = Environment.getOemDirectory();
11826        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11827            codeRoot = Environment.getVendorDirectory();
11828        } else {
11829            // Unrecognized code path; take its top real segment as the apk root:
11830            // e.g. /something/app/blah.apk => /something
11831            try {
11832                File f = codePath.getCanonicalFile();
11833                File parent = f.getParentFile();    // non-null because codePath is a file
11834                File tmp;
11835                while ((tmp = parent.getParentFile()) != null) {
11836                    f = parent;
11837                    parent = tmp;
11838                }
11839                codeRoot = f;
11840                Slog.w(TAG, "Unrecognized code path "
11841                        + codePath + " - using " + codeRoot);
11842            } catch (IOException e) {
11843                // Can't canonicalize the code path -- shenanigans?
11844                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11845                return Environment.getRootDirectory().getPath();
11846            }
11847        }
11848        return codeRoot.getPath();
11849    }
11850
11851    /**
11852     * Derive and set the location of native libraries for the given package,
11853     * which varies depending on where and how the package was installed.
11854     */
11855    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11856        final ApplicationInfo info = pkg.applicationInfo;
11857        final String codePath = pkg.codePath;
11858        final File codeFile = new File(codePath);
11859        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11860        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11861
11862        info.nativeLibraryRootDir = null;
11863        info.nativeLibraryRootRequiresIsa = false;
11864        info.nativeLibraryDir = null;
11865        info.secondaryNativeLibraryDir = null;
11866
11867        if (isApkFile(codeFile)) {
11868            // Monolithic install
11869            if (bundledApp) {
11870                // If "/system/lib64/apkname" exists, assume that is the per-package
11871                // native library directory to use; otherwise use "/system/lib/apkname".
11872                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11873                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11874                        getPrimaryInstructionSet(info));
11875
11876                // This is a bundled system app so choose the path based on the ABI.
11877                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11878                // is just the default path.
11879                final String apkName = deriveCodePathName(codePath);
11880                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11881                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11882                        apkName).getAbsolutePath();
11883
11884                if (info.secondaryCpuAbi != null) {
11885                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11886                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11887                            secondaryLibDir, apkName).getAbsolutePath();
11888                }
11889            } else if (asecApp) {
11890                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11891                        .getAbsolutePath();
11892            } else {
11893                final String apkName = deriveCodePathName(codePath);
11894                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11895                        .getAbsolutePath();
11896            }
11897
11898            info.nativeLibraryRootRequiresIsa = false;
11899            info.nativeLibraryDir = info.nativeLibraryRootDir;
11900        } else {
11901            // Cluster install
11902            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11903            info.nativeLibraryRootRequiresIsa = true;
11904
11905            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11906                    getPrimaryInstructionSet(info)).getAbsolutePath();
11907
11908            if (info.secondaryCpuAbi != null) {
11909                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11910                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11911            }
11912        }
11913    }
11914
11915    /**
11916     * Calculate the abis and roots for a bundled app. These can uniquely
11917     * be determined from the contents of the system partition, i.e whether
11918     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11919     * of this information, and instead assume that the system was built
11920     * sensibly.
11921     */
11922    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11923                                           PackageSetting pkgSetting) {
11924        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11925
11926        // If "/system/lib64/apkname" exists, assume that is the per-package
11927        // native library directory to use; otherwise use "/system/lib/apkname".
11928        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11929        setBundledAppAbi(pkg, apkRoot, apkName);
11930        // pkgSetting might be null during rescan following uninstall of updates
11931        // to a bundled app, so accommodate that possibility.  The settings in
11932        // that case will be established later from the parsed package.
11933        //
11934        // If the settings aren't null, sync them up with what we've just derived.
11935        // note that apkRoot isn't stored in the package settings.
11936        if (pkgSetting != null) {
11937            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11938            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11939        }
11940    }
11941
11942    /**
11943     * Deduces the ABI of a bundled app and sets the relevant fields on the
11944     * parsed pkg object.
11945     *
11946     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11947     *        under which system libraries are installed.
11948     * @param apkName the name of the installed package.
11949     */
11950    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11951        final File codeFile = new File(pkg.codePath);
11952
11953        final boolean has64BitLibs;
11954        final boolean has32BitLibs;
11955        if (isApkFile(codeFile)) {
11956            // Monolithic install
11957            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11958            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11959        } else {
11960            // Cluster install
11961            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11962            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11963                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11964                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11965                has64BitLibs = (new File(rootDir, isa)).exists();
11966            } else {
11967                has64BitLibs = false;
11968            }
11969            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11970                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11971                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11972                has32BitLibs = (new File(rootDir, isa)).exists();
11973            } else {
11974                has32BitLibs = false;
11975            }
11976        }
11977
11978        if (has64BitLibs && !has32BitLibs) {
11979            // The package has 64 bit libs, but not 32 bit libs. Its primary
11980            // ABI should be 64 bit. We can safely assume here that the bundled
11981            // native libraries correspond to the most preferred ABI in the list.
11982
11983            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11984            pkg.applicationInfo.secondaryCpuAbi = null;
11985        } else if (has32BitLibs && !has64BitLibs) {
11986            // The package has 32 bit libs but not 64 bit libs. Its primary
11987            // ABI should be 32 bit.
11988
11989            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11990            pkg.applicationInfo.secondaryCpuAbi = null;
11991        } else if (has32BitLibs && has64BitLibs) {
11992            // The application has both 64 and 32 bit bundled libraries. We check
11993            // here that the app declares multiArch support, and warn if it doesn't.
11994            //
11995            // We will be lenient here and record both ABIs. The primary will be the
11996            // ABI that's higher on the list, i.e, a device that's configured to prefer
11997            // 64 bit apps will see a 64 bit primary ABI,
11998
11999            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12000                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12001            }
12002
12003            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12004                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12005                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12006            } else {
12007                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12008                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12009            }
12010        } else {
12011            pkg.applicationInfo.primaryCpuAbi = null;
12012            pkg.applicationInfo.secondaryCpuAbi = null;
12013        }
12014    }
12015
12016    private void killApplication(String pkgName, int appId, String reason) {
12017        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12018    }
12019
12020    private void killApplication(String pkgName, int appId, int userId, String reason) {
12021        // Request the ActivityManager to kill the process(only for existing packages)
12022        // so that we do not end up in a confused state while the user is still using the older
12023        // version of the application while the new one gets installed.
12024        final long token = Binder.clearCallingIdentity();
12025        try {
12026            IActivityManager am = ActivityManager.getService();
12027            if (am != null) {
12028                try {
12029                    am.killApplication(pkgName, appId, userId, reason);
12030                } catch (RemoteException e) {
12031                }
12032            }
12033        } finally {
12034            Binder.restoreCallingIdentity(token);
12035        }
12036    }
12037
12038    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12039        // Remove the parent package setting
12040        PackageSetting ps = (PackageSetting) pkg.mExtras;
12041        if (ps != null) {
12042            removePackageLI(ps, chatty);
12043        }
12044        // Remove the child package setting
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            ps = (PackageSetting) childPkg.mExtras;
12049            if (ps != null) {
12050                removePackageLI(ps, chatty);
12051            }
12052        }
12053    }
12054
12055    void removePackageLI(PackageSetting ps, boolean chatty) {
12056        if (DEBUG_INSTALL) {
12057            if (chatty)
12058                Log.d(TAG, "Removing package " + ps.name);
12059        }
12060
12061        // writer
12062        synchronized (mPackages) {
12063            mPackages.remove(ps.name);
12064            final PackageParser.Package pkg = ps.pkg;
12065            if (pkg != null) {
12066                cleanPackageDataStructuresLILPw(pkg, chatty);
12067            }
12068        }
12069    }
12070
12071    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12072        if (DEBUG_INSTALL) {
12073            if (chatty)
12074                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12075        }
12076
12077        // writer
12078        synchronized (mPackages) {
12079            // Remove the parent package
12080            mPackages.remove(pkg.applicationInfo.packageName);
12081            cleanPackageDataStructuresLILPw(pkg, chatty);
12082
12083            // Remove the child packages
12084            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12085            for (int i = 0; i < childCount; i++) {
12086                PackageParser.Package childPkg = pkg.childPackages.get(i);
12087                mPackages.remove(childPkg.applicationInfo.packageName);
12088                cleanPackageDataStructuresLILPw(childPkg, chatty);
12089            }
12090        }
12091    }
12092
12093    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12094        int N = pkg.providers.size();
12095        StringBuilder r = null;
12096        int i;
12097        for (i=0; i<N; i++) {
12098            PackageParser.Provider p = pkg.providers.get(i);
12099            mProviders.removeProvider(p);
12100            if (p.info.authority == null) {
12101
12102                /* There was another ContentProvider with this authority when
12103                 * this app was installed so this authority is null,
12104                 * Ignore it as we don't have to unregister the provider.
12105                 */
12106                continue;
12107            }
12108            String names[] = p.info.authority.split(";");
12109            for (int j = 0; j < names.length; j++) {
12110                if (mProvidersByAuthority.get(names[j]) == p) {
12111                    mProvidersByAuthority.remove(names[j]);
12112                    if (DEBUG_REMOVE) {
12113                        if (chatty)
12114                            Log.d(TAG, "Unregistered content provider: " + names[j]
12115                                    + ", className = " + p.info.name + ", isSyncable = "
12116                                    + p.info.isSyncable);
12117                    }
12118                }
12119            }
12120            if (DEBUG_REMOVE && chatty) {
12121                if (r == null) {
12122                    r = new StringBuilder(256);
12123                } else {
12124                    r.append(' ');
12125                }
12126                r.append(p.info.name);
12127            }
12128        }
12129        if (r != null) {
12130            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12131        }
12132
12133        N = pkg.services.size();
12134        r = null;
12135        for (i=0; i<N; i++) {
12136            PackageParser.Service s = pkg.services.get(i);
12137            mServices.removeService(s);
12138            if (chatty) {
12139                if (r == null) {
12140                    r = new StringBuilder(256);
12141                } else {
12142                    r.append(' ');
12143                }
12144                r.append(s.info.name);
12145            }
12146        }
12147        if (r != null) {
12148            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12149        }
12150
12151        N = pkg.receivers.size();
12152        r = null;
12153        for (i=0; i<N; i++) {
12154            PackageParser.Activity a = pkg.receivers.get(i);
12155            mReceivers.removeActivity(a, "receiver");
12156            if (DEBUG_REMOVE && chatty) {
12157                if (r == null) {
12158                    r = new StringBuilder(256);
12159                } else {
12160                    r.append(' ');
12161                }
12162                r.append(a.info.name);
12163            }
12164        }
12165        if (r != null) {
12166            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12167        }
12168
12169        N = pkg.activities.size();
12170        r = null;
12171        for (i=0; i<N; i++) {
12172            PackageParser.Activity a = pkg.activities.get(i);
12173            mActivities.removeActivity(a, "activity");
12174            if (DEBUG_REMOVE && chatty) {
12175                if (r == null) {
12176                    r = new StringBuilder(256);
12177                } else {
12178                    r.append(' ');
12179                }
12180                r.append(a.info.name);
12181            }
12182        }
12183        if (r != null) {
12184            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12185        }
12186
12187        N = pkg.permissions.size();
12188        r = null;
12189        for (i=0; i<N; i++) {
12190            PackageParser.Permission p = pkg.permissions.get(i);
12191            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12192            if (bp == null) {
12193                bp = mSettings.mPermissionTrees.get(p.info.name);
12194            }
12195            if (bp != null && bp.perm == p) {
12196                bp.perm = null;
12197                if (DEBUG_REMOVE && chatty) {
12198                    if (r == null) {
12199                        r = new StringBuilder(256);
12200                    } else {
12201                        r.append(' ');
12202                    }
12203                    r.append(p.info.name);
12204                }
12205            }
12206            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12207                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12208                if (appOpPkgs != null) {
12209                    appOpPkgs.remove(pkg.packageName);
12210                }
12211            }
12212        }
12213        if (r != null) {
12214            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12215        }
12216
12217        N = pkg.requestedPermissions.size();
12218        r = null;
12219        for (i=0; i<N; i++) {
12220            String perm = pkg.requestedPermissions.get(i);
12221            BasePermission bp = mSettings.mPermissions.get(perm);
12222            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12223                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12224                if (appOpPkgs != null) {
12225                    appOpPkgs.remove(pkg.packageName);
12226                    if (appOpPkgs.isEmpty()) {
12227                        mAppOpPermissionPackages.remove(perm);
12228                    }
12229                }
12230            }
12231        }
12232        if (r != null) {
12233            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12234        }
12235
12236        N = pkg.instrumentation.size();
12237        r = null;
12238        for (i=0; i<N; i++) {
12239            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12240            mInstrumentation.remove(a.getComponentName());
12241            if (DEBUG_REMOVE && chatty) {
12242                if (r == null) {
12243                    r = new StringBuilder(256);
12244                } else {
12245                    r.append(' ');
12246                }
12247                r.append(a.info.name);
12248            }
12249        }
12250        if (r != null) {
12251            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12252        }
12253
12254        r = null;
12255        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12256            // Only system apps can hold shared libraries.
12257            if (pkg.libraryNames != null) {
12258                for (i = 0; i < pkg.libraryNames.size(); i++) {
12259                    String name = pkg.libraryNames.get(i);
12260                    if (removeSharedLibraryLPw(name, 0)) {
12261                        if (DEBUG_REMOVE && chatty) {
12262                            if (r == null) {
12263                                r = new StringBuilder(256);
12264                            } else {
12265                                r.append(' ');
12266                            }
12267                            r.append(name);
12268                        }
12269                    }
12270                }
12271            }
12272        }
12273
12274        r = null;
12275
12276        // Any package can hold static shared libraries.
12277        if (pkg.staticSharedLibName != null) {
12278            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12279                if (DEBUG_REMOVE && chatty) {
12280                    if (r == null) {
12281                        r = new StringBuilder(256);
12282                    } else {
12283                        r.append(' ');
12284                    }
12285                    r.append(pkg.staticSharedLibName);
12286                }
12287            }
12288        }
12289
12290        if (r != null) {
12291            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12292        }
12293    }
12294
12295    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12296        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12297            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12298                return true;
12299            }
12300        }
12301        return false;
12302    }
12303
12304    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12305    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12306    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12307
12308    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12309        // Update the parent permissions
12310        updatePermissionsLPw(pkg.packageName, pkg, flags);
12311        // Update the child permissions
12312        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12313        for (int i = 0; i < childCount; i++) {
12314            PackageParser.Package childPkg = pkg.childPackages.get(i);
12315            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12316        }
12317    }
12318
12319    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12320            int flags) {
12321        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12322        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12323    }
12324
12325    private void updatePermissionsLPw(String changingPkg,
12326            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12327        // Make sure there are no dangling permission trees.
12328        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12329        while (it.hasNext()) {
12330            final BasePermission bp = it.next();
12331            if (bp.packageSetting == null) {
12332                // We may not yet have parsed the package, so just see if
12333                // we still know about its settings.
12334                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12335            }
12336            if (bp.packageSetting == null) {
12337                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12338                        + " from package " + bp.sourcePackage);
12339                it.remove();
12340            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12341                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12342                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12343                            + " from package " + bp.sourcePackage);
12344                    flags |= UPDATE_PERMISSIONS_ALL;
12345                    it.remove();
12346                }
12347            }
12348        }
12349
12350        // Make sure all dynamic permissions have been assigned to a package,
12351        // and make sure there are no dangling permissions.
12352        it = mSettings.mPermissions.values().iterator();
12353        while (it.hasNext()) {
12354            final BasePermission bp = it.next();
12355            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12356                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12357                        + bp.name + " pkg=" + bp.sourcePackage
12358                        + " info=" + bp.pendingInfo);
12359                if (bp.packageSetting == null && bp.pendingInfo != null) {
12360                    final BasePermission tree = findPermissionTreeLP(bp.name);
12361                    if (tree != null && tree.perm != null) {
12362                        bp.packageSetting = tree.packageSetting;
12363                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12364                                new PermissionInfo(bp.pendingInfo));
12365                        bp.perm.info.packageName = tree.perm.info.packageName;
12366                        bp.perm.info.name = bp.name;
12367                        bp.uid = tree.uid;
12368                    }
12369                }
12370            }
12371            if (bp.packageSetting == null) {
12372                // We may not yet have parsed the package, so just see if
12373                // we still know about its settings.
12374                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12375            }
12376            if (bp.packageSetting == null) {
12377                Slog.w(TAG, "Removing dangling permission: " + bp.name
12378                        + " from package " + bp.sourcePackage);
12379                it.remove();
12380            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12381                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12382                    Slog.i(TAG, "Removing old permission: " + bp.name
12383                            + " from package " + bp.sourcePackage);
12384                    flags |= UPDATE_PERMISSIONS_ALL;
12385                    it.remove();
12386                }
12387            }
12388        }
12389
12390        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12391        // Now update the permissions for all packages, in particular
12392        // replace the granted permissions of the system packages.
12393        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12394            for (PackageParser.Package pkg : mPackages.values()) {
12395                if (pkg != pkgInfo) {
12396                    // Only replace for packages on requested volume
12397                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12398                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12399                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12400                    grantPermissionsLPw(pkg, replace, changingPkg);
12401                }
12402            }
12403        }
12404
12405        if (pkgInfo != null) {
12406            // Only replace for packages on requested volume
12407            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12408            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12409                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12410            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12411        }
12412        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12413    }
12414
12415    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12416            String packageOfInterest) {
12417        // IMPORTANT: There are two types of permissions: install and runtime.
12418        // Install time permissions are granted when the app is installed to
12419        // all device users and users added in the future. Runtime permissions
12420        // are granted at runtime explicitly to specific users. Normal and signature
12421        // protected permissions are install time permissions. Dangerous permissions
12422        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12423        // otherwise they are runtime permissions. This function does not manage
12424        // runtime permissions except for the case an app targeting Lollipop MR1
12425        // being upgraded to target a newer SDK, in which case dangerous permissions
12426        // are transformed from install time to runtime ones.
12427
12428        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12429        if (ps == null) {
12430            return;
12431        }
12432
12433        PermissionsState permissionsState = ps.getPermissionsState();
12434        PermissionsState origPermissions = permissionsState;
12435
12436        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12437
12438        boolean runtimePermissionsRevoked = false;
12439        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12440
12441        boolean changedInstallPermission = false;
12442
12443        if (replace) {
12444            ps.installPermissionsFixed = false;
12445            if (!ps.isSharedUser()) {
12446                origPermissions = new PermissionsState(permissionsState);
12447                permissionsState.reset();
12448            } else {
12449                // We need to know only about runtime permission changes since the
12450                // calling code always writes the install permissions state but
12451                // the runtime ones are written only if changed. The only cases of
12452                // changed runtime permissions here are promotion of an install to
12453                // runtime and revocation of a runtime from a shared user.
12454                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12455                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12456                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12457                    runtimePermissionsRevoked = true;
12458                }
12459            }
12460        }
12461
12462        permissionsState.setGlobalGids(mGlobalGids);
12463
12464        final int N = pkg.requestedPermissions.size();
12465        for (int i=0; i<N; i++) {
12466            final String name = pkg.requestedPermissions.get(i);
12467            final BasePermission bp = mSettings.mPermissions.get(name);
12468            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12469                    >= Build.VERSION_CODES.M;
12470
12471            if (DEBUG_INSTALL) {
12472                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12473            }
12474
12475            if (bp == null || bp.packageSetting == null) {
12476                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12477                    if (DEBUG_PERMISSIONS) {
12478                        Slog.i(TAG, "Unknown permission " + name
12479                                + " in package " + pkg.packageName);
12480                    }
12481                }
12482                continue;
12483            }
12484
12485
12486            // Limit ephemeral apps to ephemeral allowed permissions.
12487            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12488                if (DEBUG_PERMISSIONS) {
12489                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12490                            + pkg.packageName);
12491                }
12492                continue;
12493            }
12494
12495            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12496                if (DEBUG_PERMISSIONS) {
12497                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12498                            + pkg.packageName);
12499                }
12500                continue;
12501            }
12502
12503            final String perm = bp.name;
12504            boolean allowedSig = false;
12505            int grant = GRANT_DENIED;
12506
12507            // Keep track of app op permissions.
12508            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12509                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12510                if (pkgs == null) {
12511                    pkgs = new ArraySet<>();
12512                    mAppOpPermissionPackages.put(bp.name, pkgs);
12513                }
12514                pkgs.add(pkg.packageName);
12515            }
12516
12517            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12518            switch (level) {
12519                case PermissionInfo.PROTECTION_NORMAL: {
12520                    // For all apps normal permissions are install time ones.
12521                    grant = GRANT_INSTALL;
12522                } break;
12523
12524                case PermissionInfo.PROTECTION_DANGEROUS: {
12525                    // If a permission review is required for legacy apps we represent
12526                    // their permissions as always granted runtime ones since we need
12527                    // to keep the review required permission flag per user while an
12528                    // install permission's state is shared across all users.
12529                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12530                        // For legacy apps dangerous permissions are install time ones.
12531                        grant = GRANT_INSTALL;
12532                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12533                        // For legacy apps that became modern, install becomes runtime.
12534                        grant = GRANT_UPGRADE;
12535                    } else if (mPromoteSystemApps
12536                            && isSystemApp(ps)
12537                            && mExistingSystemPackages.contains(ps.name)) {
12538                        // For legacy system apps, install becomes runtime.
12539                        // We cannot check hasInstallPermission() for system apps since those
12540                        // permissions were granted implicitly and not persisted pre-M.
12541                        grant = GRANT_UPGRADE;
12542                    } else {
12543                        // For modern apps keep runtime permissions unchanged.
12544                        grant = GRANT_RUNTIME;
12545                    }
12546                } break;
12547
12548                case PermissionInfo.PROTECTION_SIGNATURE: {
12549                    // For all apps signature permissions are install time ones.
12550                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12551                    if (allowedSig) {
12552                        grant = GRANT_INSTALL;
12553                    }
12554                } break;
12555            }
12556
12557            if (DEBUG_PERMISSIONS) {
12558                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12559            }
12560
12561            if (grant != GRANT_DENIED) {
12562                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12563                    // If this is an existing, non-system package, then
12564                    // we can't add any new permissions to it.
12565                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12566                        // Except...  if this is a permission that was added
12567                        // to the platform (note: need to only do this when
12568                        // updating the platform).
12569                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12570                            grant = GRANT_DENIED;
12571                        }
12572                    }
12573                }
12574
12575                switch (grant) {
12576                    case GRANT_INSTALL: {
12577                        // Revoke this as runtime permission to handle the case of
12578                        // a runtime permission being downgraded to an install one.
12579                        // Also in permission review mode we keep dangerous permissions
12580                        // for legacy apps
12581                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12582                            if (origPermissions.getRuntimePermissionState(
12583                                    bp.name, userId) != null) {
12584                                // Revoke the runtime permission and clear the flags.
12585                                origPermissions.revokeRuntimePermission(bp, userId);
12586                                origPermissions.updatePermissionFlags(bp, userId,
12587                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12588                                // If we revoked a permission permission, we have to write.
12589                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12590                                        changedRuntimePermissionUserIds, userId);
12591                            }
12592                        }
12593                        // Grant an install permission.
12594                        if (permissionsState.grantInstallPermission(bp) !=
12595                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12596                            changedInstallPermission = true;
12597                        }
12598                    } break;
12599
12600                    case GRANT_RUNTIME: {
12601                        // Grant previously granted runtime permissions.
12602                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12603                            PermissionState permissionState = origPermissions
12604                                    .getRuntimePermissionState(bp.name, userId);
12605                            int flags = permissionState != null
12606                                    ? permissionState.getFlags() : 0;
12607                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12608                                // Don't propagate the permission in a permission review mode if
12609                                // the former was revoked, i.e. marked to not propagate on upgrade.
12610                                // Note that in a permission review mode install permissions are
12611                                // represented as constantly granted runtime ones since we need to
12612                                // keep a per user state associated with the permission. Also the
12613                                // revoke on upgrade flag is no longer applicable and is reset.
12614                                final boolean revokeOnUpgrade = (flags & PackageManager
12615                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12616                                if (revokeOnUpgrade) {
12617                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12618                                    // Since we changed the flags, we have to write.
12619                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12620                                            changedRuntimePermissionUserIds, userId);
12621                                }
12622                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12623                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12624                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12625                                        // If we cannot put the permission as it was,
12626                                        // we have to write.
12627                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12628                                                changedRuntimePermissionUserIds, userId);
12629                                    }
12630                                }
12631
12632                                // If the app supports runtime permissions no need for a review.
12633                                if (mPermissionReviewRequired
12634                                        && appSupportsRuntimePermissions
12635                                        && (flags & PackageManager
12636                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12637                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12638                                    // Since we changed the flags, we have to write.
12639                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12640                                            changedRuntimePermissionUserIds, userId);
12641                                }
12642                            } else if (mPermissionReviewRequired
12643                                    && !appSupportsRuntimePermissions) {
12644                                // For legacy apps that need a permission review, every new
12645                                // runtime permission is granted but it is pending a review.
12646                                // We also need to review only platform defined runtime
12647                                // permissions as these are the only ones the platform knows
12648                                // how to disable the API to simulate revocation as legacy
12649                                // apps don't expect to run with revoked permissions.
12650                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12651                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12652                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12653                                        // We changed the flags, hence have to write.
12654                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12655                                                changedRuntimePermissionUserIds, userId);
12656                                    }
12657                                }
12658                                if (permissionsState.grantRuntimePermission(bp, userId)
12659                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12660                                    // We changed the permission, hence have to write.
12661                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12662                                            changedRuntimePermissionUserIds, userId);
12663                                }
12664                            }
12665                            // Propagate the permission flags.
12666                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12667                        }
12668                    } break;
12669
12670                    case GRANT_UPGRADE: {
12671                        // Grant runtime permissions for a previously held install permission.
12672                        PermissionState permissionState = origPermissions
12673                                .getInstallPermissionState(bp.name);
12674                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12675
12676                        if (origPermissions.revokeInstallPermission(bp)
12677                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12678                            // We will be transferring the permission flags, so clear them.
12679                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12680                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12681                            changedInstallPermission = true;
12682                        }
12683
12684                        // If the permission is not to be promoted to runtime we ignore it and
12685                        // also its other flags as they are not applicable to install permissions.
12686                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12687                            for (int userId : currentUserIds) {
12688                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12689                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12690                                    // Transfer the permission flags.
12691                                    permissionsState.updatePermissionFlags(bp, userId,
12692                                            flags, flags);
12693                                    // If we granted the permission, we have to write.
12694                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12695                                            changedRuntimePermissionUserIds, userId);
12696                                }
12697                            }
12698                        }
12699                    } break;
12700
12701                    default: {
12702                        if (packageOfInterest == null
12703                                || packageOfInterest.equals(pkg.packageName)) {
12704                            if (DEBUG_PERMISSIONS) {
12705                                Slog.i(TAG, "Not granting permission " + perm
12706                                        + " to package " + pkg.packageName
12707                                        + " because it was previously installed without");
12708                            }
12709                        }
12710                    } break;
12711                }
12712            } else {
12713                if (permissionsState.revokeInstallPermission(bp) !=
12714                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12715                    // Also drop the permission flags.
12716                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12717                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12718                    changedInstallPermission = true;
12719                    Slog.i(TAG, "Un-granting permission " + perm
12720                            + " from package " + pkg.packageName
12721                            + " (protectionLevel=" + bp.protectionLevel
12722                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12723                            + ")");
12724                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12725                    // Don't print warning for app op permissions, since it is fine for them
12726                    // not to be granted, there is a UI for the user to decide.
12727                    if (DEBUG_PERMISSIONS
12728                            && (packageOfInterest == null
12729                                    || packageOfInterest.equals(pkg.packageName))) {
12730                        Slog.i(TAG, "Not granting permission " + perm
12731                                + " to package " + pkg.packageName
12732                                + " (protectionLevel=" + bp.protectionLevel
12733                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12734                                + ")");
12735                    }
12736                }
12737            }
12738        }
12739
12740        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12741                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12742            // This is the first that we have heard about this package, so the
12743            // permissions we have now selected are fixed until explicitly
12744            // changed.
12745            ps.installPermissionsFixed = true;
12746        }
12747
12748        // Persist the runtime permissions state for users with changes. If permissions
12749        // were revoked because no app in the shared user declares them we have to
12750        // write synchronously to avoid losing runtime permissions state.
12751        for (int userId : changedRuntimePermissionUserIds) {
12752            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12753        }
12754    }
12755
12756    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12757        boolean allowed = false;
12758        final int NP = PackageParser.NEW_PERMISSIONS.length;
12759        for (int ip=0; ip<NP; ip++) {
12760            final PackageParser.NewPermissionInfo npi
12761                    = PackageParser.NEW_PERMISSIONS[ip];
12762            if (npi.name.equals(perm)
12763                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12764                allowed = true;
12765                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12766                        + pkg.packageName);
12767                break;
12768            }
12769        }
12770        return allowed;
12771    }
12772
12773    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12774            BasePermission bp, PermissionsState origPermissions) {
12775        boolean privilegedPermission = (bp.protectionLevel
12776                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12777        boolean privappPermissionsDisable =
12778                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12779        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12780        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12781        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12782                && !platformPackage && platformPermission) {
12783            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12784                    .getPrivAppPermissions(pkg.packageName);
12785            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12786            if (!whitelisted) {
12787                Slog.w(TAG, "Privileged permission " + perm + " for package "
12788                        + pkg.packageName + " - not in privapp-permissions whitelist");
12789                // Only report violations for apps on system image
12790                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12791                    if (mPrivappPermissionsViolations == null) {
12792                        mPrivappPermissionsViolations = new ArraySet<>();
12793                    }
12794                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12795                }
12796                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12797                    return false;
12798                }
12799            }
12800        }
12801        boolean allowed = (compareSignatures(
12802                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12803                        == PackageManager.SIGNATURE_MATCH)
12804                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12805                        == PackageManager.SIGNATURE_MATCH);
12806        if (!allowed && privilegedPermission) {
12807            if (isSystemApp(pkg)) {
12808                // For updated system applications, a system permission
12809                // is granted only if it had been defined by the original application.
12810                if (pkg.isUpdatedSystemApp()) {
12811                    final PackageSetting sysPs = mSettings
12812                            .getDisabledSystemPkgLPr(pkg.packageName);
12813                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12814                        // If the original was granted this permission, we take
12815                        // that grant decision as read and propagate it to the
12816                        // update.
12817                        if (sysPs.isPrivileged()) {
12818                            allowed = true;
12819                        }
12820                    } else {
12821                        // The system apk may have been updated with an older
12822                        // version of the one on the data partition, but which
12823                        // granted a new system permission that it didn't have
12824                        // before.  In this case we do want to allow the app to
12825                        // now get the new permission if the ancestral apk is
12826                        // privileged to get it.
12827                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12828                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12829                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12830                                    allowed = true;
12831                                    break;
12832                                }
12833                            }
12834                        }
12835                        // Also if a privileged parent package on the system image or any of
12836                        // its children requested a privileged permission, the updated child
12837                        // packages can also get the permission.
12838                        if (pkg.parentPackage != null) {
12839                            final PackageSetting disabledSysParentPs = mSettings
12840                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12841                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12842                                    && disabledSysParentPs.isPrivileged()) {
12843                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12844                                    allowed = true;
12845                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12846                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12847                                    for (int i = 0; i < count; i++) {
12848                                        PackageParser.Package disabledSysChildPkg =
12849                                                disabledSysParentPs.pkg.childPackages.get(i);
12850                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12851                                                perm)) {
12852                                            allowed = true;
12853                                            break;
12854                                        }
12855                                    }
12856                                }
12857                            }
12858                        }
12859                    }
12860                } else {
12861                    allowed = isPrivilegedApp(pkg);
12862                }
12863            }
12864        }
12865        if (!allowed) {
12866            if (!allowed && (bp.protectionLevel
12867                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12868                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12869                // If this was a previously normal/dangerous permission that got moved
12870                // to a system permission as part of the runtime permission redesign, then
12871                // we still want to blindly grant it to old apps.
12872                allowed = true;
12873            }
12874            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12875                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12876                // If this permission is to be granted to the system installer and
12877                // this app is an installer, then it gets the permission.
12878                allowed = true;
12879            }
12880            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12881                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12882                // If this permission is to be granted to the system verifier and
12883                // this app is a verifier, then it gets the permission.
12884                allowed = true;
12885            }
12886            if (!allowed && (bp.protectionLevel
12887                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12888                    && isSystemApp(pkg)) {
12889                // Any pre-installed system app is allowed to get this permission.
12890                allowed = true;
12891            }
12892            if (!allowed && (bp.protectionLevel
12893                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12894                // For development permissions, a development permission
12895                // is granted only if it was already granted.
12896                allowed = origPermissions.hasInstallPermission(perm);
12897            }
12898            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12899                    && pkg.packageName.equals(mSetupWizardPackage)) {
12900                // If this permission is to be granted to the system setup wizard and
12901                // this app is a setup wizard, then it gets the permission.
12902                allowed = true;
12903            }
12904        }
12905        return allowed;
12906    }
12907
12908    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12909        final int permCount = pkg.requestedPermissions.size();
12910        for (int j = 0; j < permCount; j++) {
12911            String requestedPermission = pkg.requestedPermissions.get(j);
12912            if (permission.equals(requestedPermission)) {
12913                return true;
12914            }
12915        }
12916        return false;
12917    }
12918
12919    final class ActivityIntentResolver
12920            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12921        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12922                boolean defaultOnly, int userId) {
12923            if (!sUserManager.exists(userId)) return null;
12924            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12925            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12926        }
12927
12928        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12929                int userId) {
12930            if (!sUserManager.exists(userId)) return null;
12931            mFlags = flags;
12932            return super.queryIntent(intent, resolvedType,
12933                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12934                    userId);
12935        }
12936
12937        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12938                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12939            if (!sUserManager.exists(userId)) return null;
12940            if (packageActivities == null) {
12941                return null;
12942            }
12943            mFlags = flags;
12944            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12945            final int N = packageActivities.size();
12946            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12947                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12948
12949            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12950            for (int i = 0; i < N; ++i) {
12951                intentFilters = packageActivities.get(i).intents;
12952                if (intentFilters != null && intentFilters.size() > 0) {
12953                    PackageParser.ActivityIntentInfo[] array =
12954                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12955                    intentFilters.toArray(array);
12956                    listCut.add(array);
12957                }
12958            }
12959            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12960        }
12961
12962        /**
12963         * Finds a privileged activity that matches the specified activity names.
12964         */
12965        private PackageParser.Activity findMatchingActivity(
12966                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12967            for (PackageParser.Activity sysActivity : activityList) {
12968                if (sysActivity.info.name.equals(activityInfo.name)) {
12969                    return sysActivity;
12970                }
12971                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12972                    return sysActivity;
12973                }
12974                if (sysActivity.info.targetActivity != null) {
12975                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12976                        return sysActivity;
12977                    }
12978                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12979                        return sysActivity;
12980                    }
12981                }
12982            }
12983            return null;
12984        }
12985
12986        public class IterGenerator<E> {
12987            public Iterator<E> generate(ActivityIntentInfo info) {
12988                return null;
12989            }
12990        }
12991
12992        public class ActionIterGenerator extends IterGenerator<String> {
12993            @Override
12994            public Iterator<String> generate(ActivityIntentInfo info) {
12995                return info.actionsIterator();
12996            }
12997        }
12998
12999        public class CategoriesIterGenerator extends IterGenerator<String> {
13000            @Override
13001            public Iterator<String> generate(ActivityIntentInfo info) {
13002                return info.categoriesIterator();
13003            }
13004        }
13005
13006        public class SchemesIterGenerator extends IterGenerator<String> {
13007            @Override
13008            public Iterator<String> generate(ActivityIntentInfo info) {
13009                return info.schemesIterator();
13010            }
13011        }
13012
13013        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13014            @Override
13015            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13016                return info.authoritiesIterator();
13017            }
13018        }
13019
13020        /**
13021         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13022         * MODIFIED. Do not pass in a list that should not be changed.
13023         */
13024        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13025                IterGenerator<T> generator, Iterator<T> searchIterator) {
13026            // loop through the set of actions; every one must be found in the intent filter
13027            while (searchIterator.hasNext()) {
13028                // we must have at least one filter in the list to consider a match
13029                if (intentList.size() == 0) {
13030                    break;
13031                }
13032
13033                final T searchAction = searchIterator.next();
13034
13035                // loop through the set of intent filters
13036                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13037                while (intentIter.hasNext()) {
13038                    final ActivityIntentInfo intentInfo = intentIter.next();
13039                    boolean selectionFound = false;
13040
13041                    // loop through the intent filter's selection criteria; at least one
13042                    // of them must match the searched criteria
13043                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13044                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13045                        final T intentSelection = intentSelectionIter.next();
13046                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13047                            selectionFound = true;
13048                            break;
13049                        }
13050                    }
13051
13052                    // the selection criteria wasn't found in this filter's set; this filter
13053                    // is not a potential match
13054                    if (!selectionFound) {
13055                        intentIter.remove();
13056                    }
13057                }
13058            }
13059        }
13060
13061        private boolean isProtectedAction(ActivityIntentInfo filter) {
13062            final Iterator<String> actionsIter = filter.actionsIterator();
13063            while (actionsIter != null && actionsIter.hasNext()) {
13064                final String filterAction = actionsIter.next();
13065                if (PROTECTED_ACTIONS.contains(filterAction)) {
13066                    return true;
13067                }
13068            }
13069            return false;
13070        }
13071
13072        /**
13073         * Adjusts the priority of the given intent filter according to policy.
13074         * <p>
13075         * <ul>
13076         * <li>The priority for non privileged applications is capped to '0'</li>
13077         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13078         * <li>The priority for unbundled updates to privileged applications is capped to the
13079         *      priority defined on the system partition</li>
13080         * </ul>
13081         * <p>
13082         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13083         * allowed to obtain any priority on any action.
13084         */
13085        private void adjustPriority(
13086                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13087            // nothing to do; priority is fine as-is
13088            if (intent.getPriority() <= 0) {
13089                return;
13090            }
13091
13092            final ActivityInfo activityInfo = intent.activity.info;
13093            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13094
13095            final boolean privilegedApp =
13096                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13097            if (!privilegedApp) {
13098                // non-privileged applications can never define a priority >0
13099                if (DEBUG_FILTERS) {
13100                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13101                            + " package: " + applicationInfo.packageName
13102                            + " activity: " + intent.activity.className
13103                            + " origPrio: " + intent.getPriority());
13104                }
13105                intent.setPriority(0);
13106                return;
13107            }
13108
13109            if (systemActivities == null) {
13110                // the system package is not disabled; we're parsing the system partition
13111                if (isProtectedAction(intent)) {
13112                    if (mDeferProtectedFilters) {
13113                        // We can't deal with these just yet. No component should ever obtain a
13114                        // >0 priority for a protected actions, with ONE exception -- the setup
13115                        // wizard. The setup wizard, however, cannot be known until we're able to
13116                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13117                        // until all intent filters have been processed. Chicken, meet egg.
13118                        // Let the filter temporarily have a high priority and rectify the
13119                        // priorities after all system packages have been scanned.
13120                        mProtectedFilters.add(intent);
13121                        if (DEBUG_FILTERS) {
13122                            Slog.i(TAG, "Protected action; save for later;"
13123                                    + " package: " + applicationInfo.packageName
13124                                    + " activity: " + intent.activity.className
13125                                    + " origPrio: " + intent.getPriority());
13126                        }
13127                        return;
13128                    } else {
13129                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13130                            Slog.i(TAG, "No setup wizard;"
13131                                + " All protected intents capped to priority 0");
13132                        }
13133                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13134                            if (DEBUG_FILTERS) {
13135                                Slog.i(TAG, "Found setup wizard;"
13136                                    + " allow priority " + intent.getPriority() + ";"
13137                                    + " package: " + intent.activity.info.packageName
13138                                    + " activity: " + intent.activity.className
13139                                    + " priority: " + intent.getPriority());
13140                            }
13141                            // setup wizard gets whatever it wants
13142                            return;
13143                        }
13144                        if (DEBUG_FILTERS) {
13145                            Slog.i(TAG, "Protected action; cap priority to 0;"
13146                                    + " package: " + intent.activity.info.packageName
13147                                    + " activity: " + intent.activity.className
13148                                    + " origPrio: " + intent.getPriority());
13149                        }
13150                        intent.setPriority(0);
13151                        return;
13152                    }
13153                }
13154                // privileged apps on the system image get whatever priority they request
13155                return;
13156            }
13157
13158            // privileged app unbundled update ... try to find the same activity
13159            final PackageParser.Activity foundActivity =
13160                    findMatchingActivity(systemActivities, activityInfo);
13161            if (foundActivity == null) {
13162                // this is a new activity; it cannot obtain >0 priority
13163                if (DEBUG_FILTERS) {
13164                    Slog.i(TAG, "New activity; cap priority to 0;"
13165                            + " package: " + applicationInfo.packageName
13166                            + " activity: " + intent.activity.className
13167                            + " origPrio: " + intent.getPriority());
13168                }
13169                intent.setPriority(0);
13170                return;
13171            }
13172
13173            // found activity, now check for filter equivalence
13174
13175            // a shallow copy is enough; we modify the list, not its contents
13176            final List<ActivityIntentInfo> intentListCopy =
13177                    new ArrayList<>(foundActivity.intents);
13178            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13179
13180            // find matching action subsets
13181            final Iterator<String> actionsIterator = intent.actionsIterator();
13182            if (actionsIterator != null) {
13183                getIntentListSubset(
13184                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13185                if (intentListCopy.size() == 0) {
13186                    // no more intents to match; we're not equivalent
13187                    if (DEBUG_FILTERS) {
13188                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13189                                + " package: " + applicationInfo.packageName
13190                                + " activity: " + intent.activity.className
13191                                + " origPrio: " + intent.getPriority());
13192                    }
13193                    intent.setPriority(0);
13194                    return;
13195                }
13196            }
13197
13198            // find matching category subsets
13199            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13200            if (categoriesIterator != null) {
13201                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13202                        categoriesIterator);
13203                if (intentListCopy.size() == 0) {
13204                    // no more intents to match; we're not equivalent
13205                    if (DEBUG_FILTERS) {
13206                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13207                                + " package: " + applicationInfo.packageName
13208                                + " activity: " + intent.activity.className
13209                                + " origPrio: " + intent.getPriority());
13210                    }
13211                    intent.setPriority(0);
13212                    return;
13213                }
13214            }
13215
13216            // find matching schemes subsets
13217            final Iterator<String> schemesIterator = intent.schemesIterator();
13218            if (schemesIterator != null) {
13219                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13220                        schemesIterator);
13221                if (intentListCopy.size() == 0) {
13222                    // no more intents to match; we're not equivalent
13223                    if (DEBUG_FILTERS) {
13224                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13225                                + " package: " + applicationInfo.packageName
13226                                + " activity: " + intent.activity.className
13227                                + " origPrio: " + intent.getPriority());
13228                    }
13229                    intent.setPriority(0);
13230                    return;
13231                }
13232            }
13233
13234            // find matching authorities subsets
13235            final Iterator<IntentFilter.AuthorityEntry>
13236                    authoritiesIterator = intent.authoritiesIterator();
13237            if (authoritiesIterator != null) {
13238                getIntentListSubset(intentListCopy,
13239                        new AuthoritiesIterGenerator(),
13240                        authoritiesIterator);
13241                if (intentListCopy.size() == 0) {
13242                    // no more intents to match; we're not equivalent
13243                    if (DEBUG_FILTERS) {
13244                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13245                                + " package: " + applicationInfo.packageName
13246                                + " activity: " + intent.activity.className
13247                                + " origPrio: " + intent.getPriority());
13248                    }
13249                    intent.setPriority(0);
13250                    return;
13251                }
13252            }
13253
13254            // we found matching filter(s); app gets the max priority of all intents
13255            int cappedPriority = 0;
13256            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13257                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13258            }
13259            if (intent.getPriority() > cappedPriority) {
13260                if (DEBUG_FILTERS) {
13261                    Slog.i(TAG, "Found matching filter(s);"
13262                            + " cap priority to " + cappedPriority + ";"
13263                            + " package: " + applicationInfo.packageName
13264                            + " activity: " + intent.activity.className
13265                            + " origPrio: " + intent.getPriority());
13266                }
13267                intent.setPriority(cappedPriority);
13268                return;
13269            }
13270            // all this for nothing; the requested priority was <= what was on the system
13271        }
13272
13273        public final void addActivity(PackageParser.Activity a, String type) {
13274            mActivities.put(a.getComponentName(), a);
13275            if (DEBUG_SHOW_INFO)
13276                Log.v(
13277                TAG, "  " + type + " " +
13278                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13279            if (DEBUG_SHOW_INFO)
13280                Log.v(TAG, "    Class=" + a.info.name);
13281            final int NI = a.intents.size();
13282            for (int j=0; j<NI; j++) {
13283                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13284                if ("activity".equals(type)) {
13285                    final PackageSetting ps =
13286                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13287                    final List<PackageParser.Activity> systemActivities =
13288                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13289                    adjustPriority(systemActivities, intent);
13290                }
13291                if (DEBUG_SHOW_INFO) {
13292                    Log.v(TAG, "    IntentFilter:");
13293                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13294                }
13295                if (!intent.debugCheck()) {
13296                    Log.w(TAG, "==> For Activity " + a.info.name);
13297                }
13298                addFilter(intent);
13299            }
13300        }
13301
13302        public final void removeActivity(PackageParser.Activity a, String type) {
13303            mActivities.remove(a.getComponentName());
13304            if (DEBUG_SHOW_INFO) {
13305                Log.v(TAG, "  " + type + " "
13306                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13307                                : a.info.name) + ":");
13308                Log.v(TAG, "    Class=" + a.info.name);
13309            }
13310            final int NI = a.intents.size();
13311            for (int j=0; j<NI; j++) {
13312                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13313                if (DEBUG_SHOW_INFO) {
13314                    Log.v(TAG, "    IntentFilter:");
13315                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13316                }
13317                removeFilter(intent);
13318            }
13319        }
13320
13321        @Override
13322        protected boolean allowFilterResult(
13323                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13324            ActivityInfo filterAi = filter.activity.info;
13325            for (int i=dest.size()-1; i>=0; i--) {
13326                ActivityInfo destAi = dest.get(i).activityInfo;
13327                if (destAi.name == filterAi.name
13328                        && destAi.packageName == filterAi.packageName) {
13329                    return false;
13330                }
13331            }
13332            return true;
13333        }
13334
13335        @Override
13336        protected ActivityIntentInfo[] newArray(int size) {
13337            return new ActivityIntentInfo[size];
13338        }
13339
13340        @Override
13341        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13342            if (!sUserManager.exists(userId)) return true;
13343            PackageParser.Package p = filter.activity.owner;
13344            if (p != null) {
13345                PackageSetting ps = (PackageSetting)p.mExtras;
13346                if (ps != null) {
13347                    // System apps are never considered stopped for purposes of
13348                    // filtering, because there may be no way for the user to
13349                    // actually re-launch them.
13350                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13351                            && ps.getStopped(userId);
13352                }
13353            }
13354            return false;
13355        }
13356
13357        @Override
13358        protected boolean isPackageForFilter(String packageName,
13359                PackageParser.ActivityIntentInfo info) {
13360            return packageName.equals(info.activity.owner.packageName);
13361        }
13362
13363        @Override
13364        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13365                int match, int userId) {
13366            if (!sUserManager.exists(userId)) return null;
13367            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13368                return null;
13369            }
13370            final PackageParser.Activity activity = info.activity;
13371            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13372            if (ps == null) {
13373                return null;
13374            }
13375            final PackageUserState userState = ps.readUserState(userId);
13376            ActivityInfo ai =
13377                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13378            if (ai == null) {
13379                return null;
13380            }
13381            final boolean matchExplicitlyVisibleOnly =
13382                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13383            final boolean matchVisibleToInstantApp =
13384                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13385            final boolean componentVisible =
13386                    matchVisibleToInstantApp
13387                    && info.isVisibleToInstantApp()
13388                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13389            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13390            // throw out filters that aren't visible to ephemeral apps
13391            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13392                return null;
13393            }
13394            // throw out instant app filters if we're not explicitly requesting them
13395            if (!matchInstantApp && userState.instantApp) {
13396                return null;
13397            }
13398            // throw out instant app filters if updates are available; will trigger
13399            // instant app resolution
13400            if (userState.instantApp && ps.isUpdateAvailable()) {
13401                return null;
13402            }
13403            final ResolveInfo res = new ResolveInfo();
13404            res.activityInfo = ai;
13405            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13406                res.filter = info;
13407            }
13408            if (info != null) {
13409                res.handleAllWebDataURI = info.handleAllWebDataURI();
13410            }
13411            res.priority = info.getPriority();
13412            res.preferredOrder = activity.owner.mPreferredOrder;
13413            //System.out.println("Result: " + res.activityInfo.className +
13414            //                   " = " + res.priority);
13415            res.match = match;
13416            res.isDefault = info.hasDefault;
13417            res.labelRes = info.labelRes;
13418            res.nonLocalizedLabel = info.nonLocalizedLabel;
13419            if (userNeedsBadging(userId)) {
13420                res.noResourceId = true;
13421            } else {
13422                res.icon = info.icon;
13423            }
13424            res.iconResourceId = info.icon;
13425            res.system = res.activityInfo.applicationInfo.isSystemApp();
13426            res.isInstantAppAvailable = userState.instantApp;
13427            return res;
13428        }
13429
13430        @Override
13431        protected void sortResults(List<ResolveInfo> results) {
13432            Collections.sort(results, mResolvePrioritySorter);
13433        }
13434
13435        @Override
13436        protected void dumpFilter(PrintWriter out, String prefix,
13437                PackageParser.ActivityIntentInfo filter) {
13438            out.print(prefix); out.print(
13439                    Integer.toHexString(System.identityHashCode(filter.activity)));
13440                    out.print(' ');
13441                    filter.activity.printComponentShortName(out);
13442                    out.print(" filter ");
13443                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13444        }
13445
13446        @Override
13447        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13448            return filter.activity;
13449        }
13450
13451        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13452            PackageParser.Activity activity = (PackageParser.Activity)label;
13453            out.print(prefix); out.print(
13454                    Integer.toHexString(System.identityHashCode(activity)));
13455                    out.print(' ');
13456                    activity.printComponentShortName(out);
13457            if (count > 1) {
13458                out.print(" ("); out.print(count); out.print(" filters)");
13459            }
13460            out.println();
13461        }
13462
13463        // Keys are String (activity class name), values are Activity.
13464        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13465                = new ArrayMap<ComponentName, PackageParser.Activity>();
13466        private int mFlags;
13467    }
13468
13469    private final class ServiceIntentResolver
13470            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13471        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13472                boolean defaultOnly, int userId) {
13473            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13474            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13475        }
13476
13477        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13478                int userId) {
13479            if (!sUserManager.exists(userId)) return null;
13480            mFlags = flags;
13481            return super.queryIntent(intent, resolvedType,
13482                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13483                    userId);
13484        }
13485
13486        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13487                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13488            if (!sUserManager.exists(userId)) return null;
13489            if (packageServices == null) {
13490                return null;
13491            }
13492            mFlags = flags;
13493            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13494            final int N = packageServices.size();
13495            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13496                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13497
13498            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13499            for (int i = 0; i < N; ++i) {
13500                intentFilters = packageServices.get(i).intents;
13501                if (intentFilters != null && intentFilters.size() > 0) {
13502                    PackageParser.ServiceIntentInfo[] array =
13503                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13504                    intentFilters.toArray(array);
13505                    listCut.add(array);
13506                }
13507            }
13508            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13509        }
13510
13511        public final void addService(PackageParser.Service s) {
13512            mServices.put(s.getComponentName(), s);
13513            if (DEBUG_SHOW_INFO) {
13514                Log.v(TAG, "  "
13515                        + (s.info.nonLocalizedLabel != null
13516                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13517                Log.v(TAG, "    Class=" + s.info.name);
13518            }
13519            final int NI = s.intents.size();
13520            int j;
13521            for (j=0; j<NI; j++) {
13522                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13523                if (DEBUG_SHOW_INFO) {
13524                    Log.v(TAG, "    IntentFilter:");
13525                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13526                }
13527                if (!intent.debugCheck()) {
13528                    Log.w(TAG, "==> For Service " + s.info.name);
13529                }
13530                addFilter(intent);
13531            }
13532        }
13533
13534        public final void removeService(PackageParser.Service s) {
13535            mServices.remove(s.getComponentName());
13536            if (DEBUG_SHOW_INFO) {
13537                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13538                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13539                Log.v(TAG, "    Class=" + s.info.name);
13540            }
13541            final int NI = s.intents.size();
13542            int j;
13543            for (j=0; j<NI; j++) {
13544                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13545                if (DEBUG_SHOW_INFO) {
13546                    Log.v(TAG, "    IntentFilter:");
13547                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13548                }
13549                removeFilter(intent);
13550            }
13551        }
13552
13553        @Override
13554        protected boolean allowFilterResult(
13555                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13556            ServiceInfo filterSi = filter.service.info;
13557            for (int i=dest.size()-1; i>=0; i--) {
13558                ServiceInfo destAi = dest.get(i).serviceInfo;
13559                if (destAi.name == filterSi.name
13560                        && destAi.packageName == filterSi.packageName) {
13561                    return false;
13562                }
13563            }
13564            return true;
13565        }
13566
13567        @Override
13568        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13569            return new PackageParser.ServiceIntentInfo[size];
13570        }
13571
13572        @Override
13573        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13574            if (!sUserManager.exists(userId)) return true;
13575            PackageParser.Package p = filter.service.owner;
13576            if (p != null) {
13577                PackageSetting ps = (PackageSetting)p.mExtras;
13578                if (ps != null) {
13579                    // System apps are never considered stopped for purposes of
13580                    // filtering, because there may be no way for the user to
13581                    // actually re-launch them.
13582                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13583                            && ps.getStopped(userId);
13584                }
13585            }
13586            return false;
13587        }
13588
13589        @Override
13590        protected boolean isPackageForFilter(String packageName,
13591                PackageParser.ServiceIntentInfo info) {
13592            return packageName.equals(info.service.owner.packageName);
13593        }
13594
13595        @Override
13596        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13597                int match, int userId) {
13598            if (!sUserManager.exists(userId)) return null;
13599            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13600            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13601                return null;
13602            }
13603            final PackageParser.Service service = info.service;
13604            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13605            if (ps == null) {
13606                return null;
13607            }
13608            final PackageUserState userState = ps.readUserState(userId);
13609            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13610                    userState, userId);
13611            if (si == null) {
13612                return null;
13613            }
13614            final boolean matchVisibleToInstantApp =
13615                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13616            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13617            // throw out filters that aren't visible to ephemeral apps
13618            if (matchVisibleToInstantApp
13619                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13620                return null;
13621            }
13622            // throw out ephemeral filters if we're not explicitly requesting them
13623            if (!isInstantApp && userState.instantApp) {
13624                return null;
13625            }
13626            // throw out instant app filters if updates are available; will trigger
13627            // instant app resolution
13628            if (userState.instantApp && ps.isUpdateAvailable()) {
13629                return null;
13630            }
13631            final ResolveInfo res = new ResolveInfo();
13632            res.serviceInfo = si;
13633            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13634                res.filter = filter;
13635            }
13636            res.priority = info.getPriority();
13637            res.preferredOrder = service.owner.mPreferredOrder;
13638            res.match = match;
13639            res.isDefault = info.hasDefault;
13640            res.labelRes = info.labelRes;
13641            res.nonLocalizedLabel = info.nonLocalizedLabel;
13642            res.icon = info.icon;
13643            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13644            return res;
13645        }
13646
13647        @Override
13648        protected void sortResults(List<ResolveInfo> results) {
13649            Collections.sort(results, mResolvePrioritySorter);
13650        }
13651
13652        @Override
13653        protected void dumpFilter(PrintWriter out, String prefix,
13654                PackageParser.ServiceIntentInfo filter) {
13655            out.print(prefix); out.print(
13656                    Integer.toHexString(System.identityHashCode(filter.service)));
13657                    out.print(' ');
13658                    filter.service.printComponentShortName(out);
13659                    out.print(" filter ");
13660                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13661        }
13662
13663        @Override
13664        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13665            return filter.service;
13666        }
13667
13668        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13669            PackageParser.Service service = (PackageParser.Service)label;
13670            out.print(prefix); out.print(
13671                    Integer.toHexString(System.identityHashCode(service)));
13672                    out.print(' ');
13673                    service.printComponentShortName(out);
13674            if (count > 1) {
13675                out.print(" ("); out.print(count); out.print(" filters)");
13676            }
13677            out.println();
13678        }
13679
13680//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13681//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13682//            final List<ResolveInfo> retList = Lists.newArrayList();
13683//            while (i.hasNext()) {
13684//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13685//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13686//                    retList.add(resolveInfo);
13687//                }
13688//            }
13689//            return retList;
13690//        }
13691
13692        // Keys are String (activity class name), values are Activity.
13693        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13694                = new ArrayMap<ComponentName, PackageParser.Service>();
13695        private int mFlags;
13696    }
13697
13698    private final class ProviderIntentResolver
13699            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13700        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13701                boolean defaultOnly, int userId) {
13702            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13703            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13704        }
13705
13706        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13707                int userId) {
13708            if (!sUserManager.exists(userId))
13709                return null;
13710            mFlags = flags;
13711            return super.queryIntent(intent, resolvedType,
13712                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13713                    userId);
13714        }
13715
13716        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13717                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13718            if (!sUserManager.exists(userId))
13719                return null;
13720            if (packageProviders == null) {
13721                return null;
13722            }
13723            mFlags = flags;
13724            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13725            final int N = packageProviders.size();
13726            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13727                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13728
13729            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13730            for (int i = 0; i < N; ++i) {
13731                intentFilters = packageProviders.get(i).intents;
13732                if (intentFilters != null && intentFilters.size() > 0) {
13733                    PackageParser.ProviderIntentInfo[] array =
13734                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13735                    intentFilters.toArray(array);
13736                    listCut.add(array);
13737                }
13738            }
13739            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13740        }
13741
13742        public final void addProvider(PackageParser.Provider p) {
13743            if (mProviders.containsKey(p.getComponentName())) {
13744                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13745                return;
13746            }
13747
13748            mProviders.put(p.getComponentName(), p);
13749            if (DEBUG_SHOW_INFO) {
13750                Log.v(TAG, "  "
13751                        + (p.info.nonLocalizedLabel != null
13752                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13753                Log.v(TAG, "    Class=" + p.info.name);
13754            }
13755            final int NI = p.intents.size();
13756            int j;
13757            for (j = 0; j < NI; j++) {
13758                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13759                if (DEBUG_SHOW_INFO) {
13760                    Log.v(TAG, "    IntentFilter:");
13761                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13762                }
13763                if (!intent.debugCheck()) {
13764                    Log.w(TAG, "==> For Provider " + p.info.name);
13765                }
13766                addFilter(intent);
13767            }
13768        }
13769
13770        public final void removeProvider(PackageParser.Provider p) {
13771            mProviders.remove(p.getComponentName());
13772            if (DEBUG_SHOW_INFO) {
13773                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13774                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13775                Log.v(TAG, "    Class=" + p.info.name);
13776            }
13777            final int NI = p.intents.size();
13778            int j;
13779            for (j = 0; j < NI; j++) {
13780                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13781                if (DEBUG_SHOW_INFO) {
13782                    Log.v(TAG, "    IntentFilter:");
13783                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13784                }
13785                removeFilter(intent);
13786            }
13787        }
13788
13789        @Override
13790        protected boolean allowFilterResult(
13791                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13792            ProviderInfo filterPi = filter.provider.info;
13793            for (int i = dest.size() - 1; i >= 0; i--) {
13794                ProviderInfo destPi = dest.get(i).providerInfo;
13795                if (destPi.name == filterPi.name
13796                        && destPi.packageName == filterPi.packageName) {
13797                    return false;
13798                }
13799            }
13800            return true;
13801        }
13802
13803        @Override
13804        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13805            return new PackageParser.ProviderIntentInfo[size];
13806        }
13807
13808        @Override
13809        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13810            if (!sUserManager.exists(userId))
13811                return true;
13812            PackageParser.Package p = filter.provider.owner;
13813            if (p != null) {
13814                PackageSetting ps = (PackageSetting) p.mExtras;
13815                if (ps != null) {
13816                    // System apps are never considered stopped for purposes of
13817                    // filtering, because there may be no way for the user to
13818                    // actually re-launch them.
13819                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13820                            && ps.getStopped(userId);
13821                }
13822            }
13823            return false;
13824        }
13825
13826        @Override
13827        protected boolean isPackageForFilter(String packageName,
13828                PackageParser.ProviderIntentInfo info) {
13829            return packageName.equals(info.provider.owner.packageName);
13830        }
13831
13832        @Override
13833        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13834                int match, int userId) {
13835            if (!sUserManager.exists(userId))
13836                return null;
13837            final PackageParser.ProviderIntentInfo info = filter;
13838            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13839                return null;
13840            }
13841            final PackageParser.Provider provider = info.provider;
13842            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13843            if (ps == null) {
13844                return null;
13845            }
13846            final PackageUserState userState = ps.readUserState(userId);
13847            final boolean matchVisibleToInstantApp =
13848                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13849            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13850            // throw out filters that aren't visible to instant applications
13851            if (matchVisibleToInstantApp
13852                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13853                return null;
13854            }
13855            // throw out instant application filters if we're not explicitly requesting them
13856            if (!isInstantApp && userState.instantApp) {
13857                return null;
13858            }
13859            // throw out instant application filters if updates are available; will trigger
13860            // instant application resolution
13861            if (userState.instantApp && ps.isUpdateAvailable()) {
13862                return null;
13863            }
13864            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13865                    userState, userId);
13866            if (pi == null) {
13867                return null;
13868            }
13869            final ResolveInfo res = new ResolveInfo();
13870            res.providerInfo = pi;
13871            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13872                res.filter = filter;
13873            }
13874            res.priority = info.getPriority();
13875            res.preferredOrder = provider.owner.mPreferredOrder;
13876            res.match = match;
13877            res.isDefault = info.hasDefault;
13878            res.labelRes = info.labelRes;
13879            res.nonLocalizedLabel = info.nonLocalizedLabel;
13880            res.icon = info.icon;
13881            res.system = res.providerInfo.applicationInfo.isSystemApp();
13882            return res;
13883        }
13884
13885        @Override
13886        protected void sortResults(List<ResolveInfo> results) {
13887            Collections.sort(results, mResolvePrioritySorter);
13888        }
13889
13890        @Override
13891        protected void dumpFilter(PrintWriter out, String prefix,
13892                PackageParser.ProviderIntentInfo filter) {
13893            out.print(prefix);
13894            out.print(
13895                    Integer.toHexString(System.identityHashCode(filter.provider)));
13896            out.print(' ');
13897            filter.provider.printComponentShortName(out);
13898            out.print(" filter ");
13899            out.println(Integer.toHexString(System.identityHashCode(filter)));
13900        }
13901
13902        @Override
13903        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13904            return filter.provider;
13905        }
13906
13907        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13908            PackageParser.Provider provider = (PackageParser.Provider)label;
13909            out.print(prefix); out.print(
13910                    Integer.toHexString(System.identityHashCode(provider)));
13911                    out.print(' ');
13912                    provider.printComponentShortName(out);
13913            if (count > 1) {
13914                out.print(" ("); out.print(count); out.print(" filters)");
13915            }
13916            out.println();
13917        }
13918
13919        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13920                = new ArrayMap<ComponentName, PackageParser.Provider>();
13921        private int mFlags;
13922    }
13923
13924    static final class EphemeralIntentResolver
13925            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13926        /**
13927         * The result that has the highest defined order. Ordering applies on a
13928         * per-package basis. Mapping is from package name to Pair of order and
13929         * EphemeralResolveInfo.
13930         * <p>
13931         * NOTE: This is implemented as a field variable for convenience and efficiency.
13932         * By having a field variable, we're able to track filter ordering as soon as
13933         * a non-zero order is defined. Otherwise, multiple loops across the result set
13934         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13935         * this needs to be contained entirely within {@link #filterResults}.
13936         */
13937        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13938
13939        @Override
13940        protected AuxiliaryResolveInfo[] newArray(int size) {
13941            return new AuxiliaryResolveInfo[size];
13942        }
13943
13944        @Override
13945        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13946            return true;
13947        }
13948
13949        @Override
13950        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13951                int userId) {
13952            if (!sUserManager.exists(userId)) {
13953                return null;
13954            }
13955            final String packageName = responseObj.resolveInfo.getPackageName();
13956            final Integer order = responseObj.getOrder();
13957            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13958                    mOrderResult.get(packageName);
13959            // ordering is enabled and this item's order isn't high enough
13960            if (lastOrderResult != null && lastOrderResult.first >= order) {
13961                return null;
13962            }
13963            final InstantAppResolveInfo res = responseObj.resolveInfo;
13964            if (order > 0) {
13965                // non-zero order, enable ordering
13966                mOrderResult.put(packageName, new Pair<>(order, res));
13967            }
13968            return responseObj;
13969        }
13970
13971        @Override
13972        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13973            // only do work if ordering is enabled [most of the time it won't be]
13974            if (mOrderResult.size() == 0) {
13975                return;
13976            }
13977            int resultSize = results.size();
13978            for (int i = 0; i < resultSize; i++) {
13979                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13980                final String packageName = info.getPackageName();
13981                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13982                if (savedInfo == null) {
13983                    // package doesn't having ordering
13984                    continue;
13985                }
13986                if (savedInfo.second == info) {
13987                    // circled back to the highest ordered item; remove from order list
13988                    mOrderResult.remove(savedInfo);
13989                    if (mOrderResult.size() == 0) {
13990                        // no more ordered items
13991                        break;
13992                    }
13993                    continue;
13994                }
13995                // item has a worse order, remove it from the result list
13996                results.remove(i);
13997                resultSize--;
13998                i--;
13999            }
14000        }
14001    }
14002
14003    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14004            new Comparator<ResolveInfo>() {
14005        public int compare(ResolveInfo r1, ResolveInfo r2) {
14006            int v1 = r1.priority;
14007            int v2 = r2.priority;
14008            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14009            if (v1 != v2) {
14010                return (v1 > v2) ? -1 : 1;
14011            }
14012            v1 = r1.preferredOrder;
14013            v2 = r2.preferredOrder;
14014            if (v1 != v2) {
14015                return (v1 > v2) ? -1 : 1;
14016            }
14017            if (r1.isDefault != r2.isDefault) {
14018                return r1.isDefault ? -1 : 1;
14019            }
14020            v1 = r1.match;
14021            v2 = r2.match;
14022            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14023            if (v1 != v2) {
14024                return (v1 > v2) ? -1 : 1;
14025            }
14026            if (r1.system != r2.system) {
14027                return r1.system ? -1 : 1;
14028            }
14029            if (r1.activityInfo != null) {
14030                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14031            }
14032            if (r1.serviceInfo != null) {
14033                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14034            }
14035            if (r1.providerInfo != null) {
14036                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14037            }
14038            return 0;
14039        }
14040    };
14041
14042    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14043            new Comparator<ProviderInfo>() {
14044        public int compare(ProviderInfo p1, ProviderInfo p2) {
14045            final int v1 = p1.initOrder;
14046            final int v2 = p2.initOrder;
14047            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14048        }
14049    };
14050
14051    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14052            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14053            final int[] userIds) {
14054        mHandler.post(new Runnable() {
14055            @Override
14056            public void run() {
14057                try {
14058                    final IActivityManager am = ActivityManager.getService();
14059                    if (am == null) return;
14060                    final int[] resolvedUserIds;
14061                    if (userIds == null) {
14062                        resolvedUserIds = am.getRunningUserIds();
14063                    } else {
14064                        resolvedUserIds = userIds;
14065                    }
14066                    for (int id : resolvedUserIds) {
14067                        final Intent intent = new Intent(action,
14068                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14069                        if (extras != null) {
14070                            intent.putExtras(extras);
14071                        }
14072                        if (targetPkg != null) {
14073                            intent.setPackage(targetPkg);
14074                        }
14075                        // Modify the UID when posting to other users
14076                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14077                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14078                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14079                            intent.putExtra(Intent.EXTRA_UID, uid);
14080                        }
14081                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14082                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14083                        if (DEBUG_BROADCASTS) {
14084                            RuntimeException here = new RuntimeException("here");
14085                            here.fillInStackTrace();
14086                            Slog.d(TAG, "Sending to user " + id + ": "
14087                                    + intent.toShortString(false, true, false, false)
14088                                    + " " + intent.getExtras(), here);
14089                        }
14090                        am.broadcastIntent(null, intent, null, finishedReceiver,
14091                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14092                                null, finishedReceiver != null, false, id);
14093                    }
14094                } catch (RemoteException ex) {
14095                }
14096            }
14097        });
14098    }
14099
14100    /**
14101     * Check if the external storage media is available. This is true if there
14102     * is a mounted external storage medium or if the external storage is
14103     * emulated.
14104     */
14105    private boolean isExternalMediaAvailable() {
14106        return mMediaMounted || Environment.isExternalStorageEmulated();
14107    }
14108
14109    @Override
14110    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14111        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14112            return null;
14113        }
14114        // writer
14115        synchronized (mPackages) {
14116            if (!isExternalMediaAvailable()) {
14117                // If the external storage is no longer mounted at this point,
14118                // the caller may not have been able to delete all of this
14119                // packages files and can not delete any more.  Bail.
14120                return null;
14121            }
14122            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14123            if (lastPackage != null) {
14124                pkgs.remove(lastPackage);
14125            }
14126            if (pkgs.size() > 0) {
14127                return pkgs.get(0);
14128            }
14129        }
14130        return null;
14131    }
14132
14133    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14134        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14135                userId, andCode ? 1 : 0, packageName);
14136        if (mSystemReady) {
14137            msg.sendToTarget();
14138        } else {
14139            if (mPostSystemReadyMessages == null) {
14140                mPostSystemReadyMessages = new ArrayList<>();
14141            }
14142            mPostSystemReadyMessages.add(msg);
14143        }
14144    }
14145
14146    void startCleaningPackages() {
14147        // reader
14148        if (!isExternalMediaAvailable()) {
14149            return;
14150        }
14151        synchronized (mPackages) {
14152            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14153                return;
14154            }
14155        }
14156        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14157        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14158        IActivityManager am = ActivityManager.getService();
14159        if (am != null) {
14160            int dcsUid = -1;
14161            synchronized (mPackages) {
14162                if (!mDefaultContainerWhitelisted) {
14163                    mDefaultContainerWhitelisted = true;
14164                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14165                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14166                }
14167            }
14168            try {
14169                if (dcsUid > 0) {
14170                    am.backgroundWhitelistUid(dcsUid);
14171                }
14172                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14173                        UserHandle.USER_SYSTEM);
14174            } catch (RemoteException e) {
14175            }
14176        }
14177    }
14178
14179    @Override
14180    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14181            int installFlags, String installerPackageName, int userId) {
14182        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14183
14184        final int callingUid = Binder.getCallingUid();
14185        enforceCrossUserPermission(callingUid, userId,
14186                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14187
14188        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14189            try {
14190                if (observer != null) {
14191                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14192                }
14193            } catch (RemoteException re) {
14194            }
14195            return;
14196        }
14197
14198        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14199            installFlags |= PackageManager.INSTALL_FROM_ADB;
14200
14201        } else {
14202            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14203            // about installerPackageName.
14204
14205            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14206            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14207        }
14208
14209        UserHandle user;
14210        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14211            user = UserHandle.ALL;
14212        } else {
14213            user = new UserHandle(userId);
14214        }
14215
14216        // Only system components can circumvent runtime permissions when installing.
14217        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14218                && mContext.checkCallingOrSelfPermission(Manifest.permission
14219                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14220            throw new SecurityException("You need the "
14221                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14222                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14223        }
14224
14225        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14226                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14227            throw new IllegalArgumentException(
14228                    "New installs into ASEC containers no longer supported");
14229        }
14230
14231        final File originFile = new File(originPath);
14232        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14233
14234        final Message msg = mHandler.obtainMessage(INIT_COPY);
14235        final VerificationInfo verificationInfo = new VerificationInfo(
14236                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14237        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14238                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14239                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14240                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14241        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14242        msg.obj = params;
14243
14244        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14245                System.identityHashCode(msg.obj));
14246        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14247                System.identityHashCode(msg.obj));
14248
14249        mHandler.sendMessage(msg);
14250    }
14251
14252
14253    /**
14254     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14255     * it is acting on behalf on an enterprise or the user).
14256     *
14257     * Note that the ordering of the conditionals in this method is important. The checks we perform
14258     * are as follows, in this order:
14259     *
14260     * 1) If the install is being performed by a system app, we can trust the app to have set the
14261     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14262     *    what it is.
14263     * 2) If the install is being performed by a device or profile owner app, the install reason
14264     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14265     *    set the install reason correctly. If the app targets an older SDK version where install
14266     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14267     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14268     * 3) In all other cases, the install is being performed by a regular app that is neither part
14269     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14270     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14271     *    set to enterprise policy and if so, change it to unknown instead.
14272     */
14273    private int fixUpInstallReason(String installerPackageName, int installerUid,
14274            int installReason) {
14275        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14276                == PERMISSION_GRANTED) {
14277            // If the install is being performed by a system app, we trust that app to have set the
14278            // install reason correctly.
14279            return installReason;
14280        }
14281
14282        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14283            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14284        if (dpm != null) {
14285            ComponentName owner = null;
14286            try {
14287                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14288                if (owner == null) {
14289                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14290                }
14291            } catch (RemoteException e) {
14292            }
14293            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14294                // If the install is being performed by a device or profile owner, the install
14295                // reason should be enterprise policy.
14296                return PackageManager.INSTALL_REASON_POLICY;
14297            }
14298        }
14299
14300        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14301            // If the install is being performed by a regular app (i.e. neither system app nor
14302            // device or profile owner), we have no reason to believe that the app is acting on
14303            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14304            // change it to unknown instead.
14305            return PackageManager.INSTALL_REASON_UNKNOWN;
14306        }
14307
14308        // If the install is being performed by a regular app and the install reason was set to any
14309        // value but enterprise policy, leave the install reason unchanged.
14310        return installReason;
14311    }
14312
14313    void installStage(String packageName, File stagedDir, String stagedCid,
14314            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14315            String installerPackageName, int installerUid, UserHandle user,
14316            Certificate[][] certificates) {
14317        if (DEBUG_EPHEMERAL) {
14318            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14319                Slog.d(TAG, "Ephemeral install of " + packageName);
14320            }
14321        }
14322        final VerificationInfo verificationInfo = new VerificationInfo(
14323                sessionParams.originatingUri, sessionParams.referrerUri,
14324                sessionParams.originatingUid, installerUid);
14325
14326        final OriginInfo origin;
14327        if (stagedDir != null) {
14328            origin = OriginInfo.fromStagedFile(stagedDir);
14329        } else {
14330            origin = OriginInfo.fromStagedContainer(stagedCid);
14331        }
14332
14333        final Message msg = mHandler.obtainMessage(INIT_COPY);
14334        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14335                sessionParams.installReason);
14336        final InstallParams params = new InstallParams(origin, null, observer,
14337                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14338                verificationInfo, user, sessionParams.abiOverride,
14339                sessionParams.grantedRuntimePermissions, certificates, installReason);
14340        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14341        msg.obj = params;
14342
14343        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14344                System.identityHashCode(msg.obj));
14345        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14346                System.identityHashCode(msg.obj));
14347
14348        mHandler.sendMessage(msg);
14349    }
14350
14351    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14352            int userId) {
14353        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14354        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14355
14356        // Send a session commit broadcast
14357        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14358        info.installReason = pkgSetting.getInstallReason(userId);
14359        info.appPackageName = packageName;
14360        sendSessionCommitBroadcast(info, userId);
14361    }
14362
14363    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14364        if (ArrayUtils.isEmpty(userIds)) {
14365            return;
14366        }
14367        Bundle extras = new Bundle(1);
14368        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14369        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14370
14371        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14372                packageName, extras, 0, null, null, userIds);
14373        if (isSystem) {
14374            mHandler.post(() -> {
14375                        for (int userId : userIds) {
14376                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14377                        }
14378                    }
14379            );
14380        }
14381    }
14382
14383    /**
14384     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14385     * automatically without needing an explicit launch.
14386     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14387     */
14388    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14389        // If user is not running, the app didn't miss any broadcast
14390        if (!mUserManagerInternal.isUserRunning(userId)) {
14391            return;
14392        }
14393        final IActivityManager am = ActivityManager.getService();
14394        try {
14395            // Deliver LOCKED_BOOT_COMPLETED first
14396            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14397                    .setPackage(packageName);
14398            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14399            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14400                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14401
14402            // Deliver BOOT_COMPLETED only if user is unlocked
14403            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14404                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14405                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14406                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14407            }
14408        } catch (RemoteException e) {
14409            throw e.rethrowFromSystemServer();
14410        }
14411    }
14412
14413    @Override
14414    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14415            int userId) {
14416        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14417        PackageSetting pkgSetting;
14418        final int callingUid = Binder.getCallingUid();
14419        enforceCrossUserPermission(callingUid, userId,
14420                true /* requireFullPermission */, true /* checkShell */,
14421                "setApplicationHiddenSetting for user " + userId);
14422
14423        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14424            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14425            return false;
14426        }
14427
14428        long callingId = Binder.clearCallingIdentity();
14429        try {
14430            boolean sendAdded = false;
14431            boolean sendRemoved = false;
14432            // writer
14433            synchronized (mPackages) {
14434                pkgSetting = mSettings.mPackages.get(packageName);
14435                if (pkgSetting == null) {
14436                    return false;
14437                }
14438                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14439                    return false;
14440                }
14441                // Do not allow "android" is being disabled
14442                if ("android".equals(packageName)) {
14443                    Slog.w(TAG, "Cannot hide package: android");
14444                    return false;
14445                }
14446                // Cannot hide static shared libs as they are considered
14447                // a part of the using app (emulating static linking). Also
14448                // static libs are installed always on internal storage.
14449                PackageParser.Package pkg = mPackages.get(packageName);
14450                if (pkg != null && pkg.staticSharedLibName != null) {
14451                    Slog.w(TAG, "Cannot hide package: " + packageName
14452                            + " providing static shared library: "
14453                            + pkg.staticSharedLibName);
14454                    return false;
14455                }
14456                // Only allow protected packages to hide themselves.
14457                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14458                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14459                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14460                    return false;
14461                }
14462
14463                if (pkgSetting.getHidden(userId) != hidden) {
14464                    pkgSetting.setHidden(hidden, userId);
14465                    mSettings.writePackageRestrictionsLPr(userId);
14466                    if (hidden) {
14467                        sendRemoved = true;
14468                    } else {
14469                        sendAdded = true;
14470                    }
14471                }
14472            }
14473            if (sendAdded) {
14474                sendPackageAddedForUser(packageName, pkgSetting, userId);
14475                return true;
14476            }
14477            if (sendRemoved) {
14478                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14479                        "hiding pkg");
14480                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14481                return true;
14482            }
14483        } finally {
14484            Binder.restoreCallingIdentity(callingId);
14485        }
14486        return false;
14487    }
14488
14489    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14490            int userId) {
14491        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14492        info.removedPackage = packageName;
14493        info.installerPackageName = pkgSetting.installerPackageName;
14494        info.removedUsers = new int[] {userId};
14495        info.broadcastUsers = new int[] {userId};
14496        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14497        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14498    }
14499
14500    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14501        if (pkgList.length > 0) {
14502            Bundle extras = new Bundle(1);
14503            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14504
14505            sendPackageBroadcast(
14506                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14507                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14508                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14509                    new int[] {userId});
14510        }
14511    }
14512
14513    /**
14514     * Returns true if application is not found or there was an error. Otherwise it returns
14515     * the hidden state of the package for the given user.
14516     */
14517    @Override
14518    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14519        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14520        final int callingUid = Binder.getCallingUid();
14521        enforceCrossUserPermission(callingUid, userId,
14522                true /* requireFullPermission */, false /* checkShell */,
14523                "getApplicationHidden for user " + userId);
14524        PackageSetting ps;
14525        long callingId = Binder.clearCallingIdentity();
14526        try {
14527            // writer
14528            synchronized (mPackages) {
14529                ps = mSettings.mPackages.get(packageName);
14530                if (ps == null) {
14531                    return true;
14532                }
14533                if (filterAppAccessLPr(ps, callingUid, userId)) {
14534                    return true;
14535                }
14536                return ps.getHidden(userId);
14537            }
14538        } finally {
14539            Binder.restoreCallingIdentity(callingId);
14540        }
14541    }
14542
14543    /**
14544     * @hide
14545     */
14546    @Override
14547    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14548            int installReason) {
14549        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14550                null);
14551        PackageSetting pkgSetting;
14552        final int callingUid = Binder.getCallingUid();
14553        enforceCrossUserPermission(callingUid, userId,
14554                true /* requireFullPermission */, true /* checkShell */,
14555                "installExistingPackage for user " + userId);
14556        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14557            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14558        }
14559
14560        long callingId = Binder.clearCallingIdentity();
14561        try {
14562            boolean installed = false;
14563            final boolean instantApp =
14564                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14565            final boolean fullApp =
14566                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14567
14568            // writer
14569            synchronized (mPackages) {
14570                pkgSetting = mSettings.mPackages.get(packageName);
14571                if (pkgSetting == null) {
14572                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14573                }
14574                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14575                    // only allow the existing package to be used if it's installed as a full
14576                    // application for at least one user
14577                    boolean installAllowed = false;
14578                    for (int checkUserId : sUserManager.getUserIds()) {
14579                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14580                        if (installAllowed) {
14581                            break;
14582                        }
14583                    }
14584                    if (!installAllowed) {
14585                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14586                    }
14587                }
14588                if (!pkgSetting.getInstalled(userId)) {
14589                    pkgSetting.setInstalled(true, userId);
14590                    pkgSetting.setHidden(false, userId);
14591                    pkgSetting.setInstallReason(installReason, userId);
14592                    mSettings.writePackageRestrictionsLPr(userId);
14593                    mSettings.writeKernelMappingLPr(pkgSetting);
14594                    installed = true;
14595                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14596                    // upgrade app from instant to full; we don't allow app downgrade
14597                    installed = true;
14598                }
14599                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14600            }
14601
14602            if (installed) {
14603                if (pkgSetting.pkg != null) {
14604                    synchronized (mInstallLock) {
14605                        // We don't need to freeze for a brand new install
14606                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14607                    }
14608                }
14609                sendPackageAddedForUser(packageName, pkgSetting, userId);
14610                synchronized (mPackages) {
14611                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14612                }
14613            }
14614        } finally {
14615            Binder.restoreCallingIdentity(callingId);
14616        }
14617
14618        return PackageManager.INSTALL_SUCCEEDED;
14619    }
14620
14621    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14622            boolean instantApp, boolean fullApp) {
14623        // no state specified; do nothing
14624        if (!instantApp && !fullApp) {
14625            return;
14626        }
14627        if (userId != UserHandle.USER_ALL) {
14628            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14629                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14630            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14631                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14632            }
14633        } else {
14634            for (int currentUserId : sUserManager.getUserIds()) {
14635                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14636                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14637                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14638                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14639                }
14640            }
14641        }
14642    }
14643
14644    boolean isUserRestricted(int userId, String restrictionKey) {
14645        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14646        if (restrictions.getBoolean(restrictionKey, false)) {
14647            Log.w(TAG, "User is restricted: " + restrictionKey);
14648            return true;
14649        }
14650        return false;
14651    }
14652
14653    @Override
14654    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14655            int userId) {
14656        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14657        final int callingUid = Binder.getCallingUid();
14658        enforceCrossUserPermission(callingUid, userId,
14659                true /* requireFullPermission */, true /* checkShell */,
14660                "setPackagesSuspended for user " + userId);
14661
14662        if (ArrayUtils.isEmpty(packageNames)) {
14663            return packageNames;
14664        }
14665
14666        // List of package names for whom the suspended state has changed.
14667        List<String> changedPackages = new ArrayList<>(packageNames.length);
14668        // List of package names for whom the suspended state is not set as requested in this
14669        // method.
14670        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14671        long callingId = Binder.clearCallingIdentity();
14672        try {
14673            for (int i = 0; i < packageNames.length; i++) {
14674                String packageName = packageNames[i];
14675                boolean changed = false;
14676                final int appId;
14677                synchronized (mPackages) {
14678                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14679                    if (pkgSetting == null
14680                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14681                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14682                                + "\". Skipping suspending/un-suspending.");
14683                        unactionedPackages.add(packageName);
14684                        continue;
14685                    }
14686                    appId = pkgSetting.appId;
14687                    if (pkgSetting.getSuspended(userId) != suspended) {
14688                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14689                            unactionedPackages.add(packageName);
14690                            continue;
14691                        }
14692                        pkgSetting.setSuspended(suspended, userId);
14693                        mSettings.writePackageRestrictionsLPr(userId);
14694                        changed = true;
14695                        changedPackages.add(packageName);
14696                    }
14697                }
14698
14699                if (changed && suspended) {
14700                    killApplication(packageName, UserHandle.getUid(userId, appId),
14701                            "suspending package");
14702                }
14703            }
14704        } finally {
14705            Binder.restoreCallingIdentity(callingId);
14706        }
14707
14708        if (!changedPackages.isEmpty()) {
14709            sendPackagesSuspendedForUser(changedPackages.toArray(
14710                    new String[changedPackages.size()]), userId, suspended);
14711        }
14712
14713        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14714    }
14715
14716    @Override
14717    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14718        final int callingUid = Binder.getCallingUid();
14719        enforceCrossUserPermission(callingUid, userId,
14720                true /* requireFullPermission */, false /* checkShell */,
14721                "isPackageSuspendedForUser for user " + userId);
14722        synchronized (mPackages) {
14723            final PackageSetting ps = mSettings.mPackages.get(packageName);
14724            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14725                throw new IllegalArgumentException("Unknown target package: " + packageName);
14726            }
14727            return ps.getSuspended(userId);
14728        }
14729    }
14730
14731    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14732        if (isPackageDeviceAdmin(packageName, userId)) {
14733            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14734                    + "\": has an active device admin");
14735            return false;
14736        }
14737
14738        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14739        if (packageName.equals(activeLauncherPackageName)) {
14740            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14741                    + "\": contains the active launcher");
14742            return false;
14743        }
14744
14745        if (packageName.equals(mRequiredInstallerPackage)) {
14746            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14747                    + "\": required for package installation");
14748            return false;
14749        }
14750
14751        if (packageName.equals(mRequiredUninstallerPackage)) {
14752            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14753                    + "\": required for package uninstallation");
14754            return false;
14755        }
14756
14757        if (packageName.equals(mRequiredVerifierPackage)) {
14758            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14759                    + "\": required for package verification");
14760            return false;
14761        }
14762
14763        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14764            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14765                    + "\": is the default dialer");
14766            return false;
14767        }
14768
14769        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14770            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14771                    + "\": protected package");
14772            return false;
14773        }
14774
14775        // Cannot suspend static shared libs as they are considered
14776        // a part of the using app (emulating static linking). Also
14777        // static libs are installed always on internal storage.
14778        PackageParser.Package pkg = mPackages.get(packageName);
14779        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14780            Slog.w(TAG, "Cannot suspend package: " + packageName
14781                    + " providing static shared library: "
14782                    + pkg.staticSharedLibName);
14783            return false;
14784        }
14785
14786        return true;
14787    }
14788
14789    private String getActiveLauncherPackageName(int userId) {
14790        Intent intent = new Intent(Intent.ACTION_MAIN);
14791        intent.addCategory(Intent.CATEGORY_HOME);
14792        ResolveInfo resolveInfo = resolveIntent(
14793                intent,
14794                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14795                PackageManager.MATCH_DEFAULT_ONLY,
14796                userId);
14797
14798        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14799    }
14800
14801    private String getDefaultDialerPackageName(int userId) {
14802        synchronized (mPackages) {
14803            return mSettings.getDefaultDialerPackageNameLPw(userId);
14804        }
14805    }
14806
14807    @Override
14808    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14809        mContext.enforceCallingOrSelfPermission(
14810                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14811                "Only package verification agents can verify applications");
14812
14813        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14814        final PackageVerificationResponse response = new PackageVerificationResponse(
14815                verificationCode, Binder.getCallingUid());
14816        msg.arg1 = id;
14817        msg.obj = response;
14818        mHandler.sendMessage(msg);
14819    }
14820
14821    @Override
14822    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14823            long millisecondsToDelay) {
14824        mContext.enforceCallingOrSelfPermission(
14825                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14826                "Only package verification agents can extend verification timeouts");
14827
14828        final PackageVerificationState state = mPendingVerification.get(id);
14829        final PackageVerificationResponse response = new PackageVerificationResponse(
14830                verificationCodeAtTimeout, Binder.getCallingUid());
14831
14832        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14833            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14834        }
14835        if (millisecondsToDelay < 0) {
14836            millisecondsToDelay = 0;
14837        }
14838        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14839                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14840            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14841        }
14842
14843        if ((state != null) && !state.timeoutExtended()) {
14844            state.extendTimeout();
14845
14846            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14847            msg.arg1 = id;
14848            msg.obj = response;
14849            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14850        }
14851    }
14852
14853    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14854            int verificationCode, UserHandle user) {
14855        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14856        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14857        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14858        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14859        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14860
14861        mContext.sendBroadcastAsUser(intent, user,
14862                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14863    }
14864
14865    private ComponentName matchComponentForVerifier(String packageName,
14866            List<ResolveInfo> receivers) {
14867        ActivityInfo targetReceiver = null;
14868
14869        final int NR = receivers.size();
14870        for (int i = 0; i < NR; i++) {
14871            final ResolveInfo info = receivers.get(i);
14872            if (info.activityInfo == null) {
14873                continue;
14874            }
14875
14876            if (packageName.equals(info.activityInfo.packageName)) {
14877                targetReceiver = info.activityInfo;
14878                break;
14879            }
14880        }
14881
14882        if (targetReceiver == null) {
14883            return null;
14884        }
14885
14886        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14887    }
14888
14889    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14890            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14891        if (pkgInfo.verifiers.length == 0) {
14892            return null;
14893        }
14894
14895        final int N = pkgInfo.verifiers.length;
14896        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14897        for (int i = 0; i < N; i++) {
14898            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14899
14900            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14901                    receivers);
14902            if (comp == null) {
14903                continue;
14904            }
14905
14906            final int verifierUid = getUidForVerifier(verifierInfo);
14907            if (verifierUid == -1) {
14908                continue;
14909            }
14910
14911            if (DEBUG_VERIFY) {
14912                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14913                        + " with the correct signature");
14914            }
14915            sufficientVerifiers.add(comp);
14916            verificationState.addSufficientVerifier(verifierUid);
14917        }
14918
14919        return sufficientVerifiers;
14920    }
14921
14922    private int getUidForVerifier(VerifierInfo verifierInfo) {
14923        synchronized (mPackages) {
14924            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14925            if (pkg == null) {
14926                return -1;
14927            } else if (pkg.mSignatures.length != 1) {
14928                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14929                        + " has more than one signature; ignoring");
14930                return -1;
14931            }
14932
14933            /*
14934             * If the public key of the package's signature does not match
14935             * our expected public key, then this is a different package and
14936             * we should skip.
14937             */
14938
14939            final byte[] expectedPublicKey;
14940            try {
14941                final Signature verifierSig = pkg.mSignatures[0];
14942                final PublicKey publicKey = verifierSig.getPublicKey();
14943                expectedPublicKey = publicKey.getEncoded();
14944            } catch (CertificateException e) {
14945                return -1;
14946            }
14947
14948            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14949
14950            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14951                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14952                        + " does not have the expected public key; ignoring");
14953                return -1;
14954            }
14955
14956            return pkg.applicationInfo.uid;
14957        }
14958    }
14959
14960    @Override
14961    public void finishPackageInstall(int token, boolean didLaunch) {
14962        enforceSystemOrRoot("Only the system is allowed to finish installs");
14963
14964        if (DEBUG_INSTALL) {
14965            Slog.v(TAG, "BM finishing package install for " + token);
14966        }
14967        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14968
14969        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14970        mHandler.sendMessage(msg);
14971    }
14972
14973    /**
14974     * Get the verification agent timeout.  Used for both the APK verifier and the
14975     * intent filter verifier.
14976     *
14977     * @return verification timeout in milliseconds
14978     */
14979    private long getVerificationTimeout() {
14980        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14981                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14982                DEFAULT_VERIFICATION_TIMEOUT);
14983    }
14984
14985    /**
14986     * Get the default verification agent response code.
14987     *
14988     * @return default verification response code
14989     */
14990    private int getDefaultVerificationResponse(UserHandle user) {
14991        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14992            return PackageManager.VERIFICATION_REJECT;
14993        }
14994        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14995                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14996                DEFAULT_VERIFICATION_RESPONSE);
14997    }
14998
14999    /**
15000     * Check whether or not package verification has been enabled.
15001     *
15002     * @return true if verification should be performed
15003     */
15004    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15005        if (!DEFAULT_VERIFY_ENABLE) {
15006            return false;
15007        }
15008
15009        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15010
15011        // Check if installing from ADB
15012        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15013            // Do not run verification in a test harness environment
15014            if (ActivityManager.isRunningInTestHarness()) {
15015                return false;
15016            }
15017            if (ensureVerifyAppsEnabled) {
15018                return true;
15019            }
15020            // Check if the developer does not want package verification for ADB installs
15021            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15022                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15023                return false;
15024            }
15025        } else {
15026            // only when not installed from ADB, skip verification for instant apps when
15027            // the installer and verifier are the same.
15028            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15029                if (mInstantAppInstallerActivity != null
15030                        && mInstantAppInstallerActivity.packageName.equals(
15031                                mRequiredVerifierPackage)) {
15032                    try {
15033                        mContext.getSystemService(AppOpsManager.class)
15034                                .checkPackage(installerUid, mRequiredVerifierPackage);
15035                        if (DEBUG_VERIFY) {
15036                            Slog.i(TAG, "disable verification for instant app");
15037                        }
15038                        return false;
15039                    } catch (SecurityException ignore) { }
15040                }
15041            }
15042        }
15043
15044        if (ensureVerifyAppsEnabled) {
15045            return true;
15046        }
15047
15048        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15049                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15050    }
15051
15052    @Override
15053    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15054            throws RemoteException {
15055        mContext.enforceCallingOrSelfPermission(
15056                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15057                "Only intentfilter verification agents can verify applications");
15058
15059        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15060        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15061                Binder.getCallingUid(), verificationCode, failedDomains);
15062        msg.arg1 = id;
15063        msg.obj = response;
15064        mHandler.sendMessage(msg);
15065    }
15066
15067    @Override
15068    public int getIntentVerificationStatus(String packageName, int userId) {
15069        final int callingUid = Binder.getCallingUid();
15070        if (getInstantAppPackageName(callingUid) != null) {
15071            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15072        }
15073        synchronized (mPackages) {
15074            final PackageSetting ps = mSettings.mPackages.get(packageName);
15075            if (ps == null
15076                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15077                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15078            }
15079            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15080        }
15081    }
15082
15083    @Override
15084    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15085        mContext.enforceCallingOrSelfPermission(
15086                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15087
15088        boolean result = false;
15089        synchronized (mPackages) {
15090            final PackageSetting ps = mSettings.mPackages.get(packageName);
15091            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15092                return false;
15093            }
15094            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15095        }
15096        if (result) {
15097            scheduleWritePackageRestrictionsLocked(userId);
15098        }
15099        return result;
15100    }
15101
15102    @Override
15103    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15104            String packageName) {
15105        final int callingUid = Binder.getCallingUid();
15106        if (getInstantAppPackageName(callingUid) != null) {
15107            return ParceledListSlice.emptyList();
15108        }
15109        synchronized (mPackages) {
15110            final PackageSetting ps = mSettings.mPackages.get(packageName);
15111            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15112                return ParceledListSlice.emptyList();
15113            }
15114            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15115        }
15116    }
15117
15118    @Override
15119    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15120        if (TextUtils.isEmpty(packageName)) {
15121            return ParceledListSlice.emptyList();
15122        }
15123        final int callingUid = Binder.getCallingUid();
15124        final int callingUserId = UserHandle.getUserId(callingUid);
15125        synchronized (mPackages) {
15126            PackageParser.Package pkg = mPackages.get(packageName);
15127            if (pkg == null || pkg.activities == null) {
15128                return ParceledListSlice.emptyList();
15129            }
15130            if (pkg.mExtras == null) {
15131                return ParceledListSlice.emptyList();
15132            }
15133            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15134            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15135                return ParceledListSlice.emptyList();
15136            }
15137            final int count = pkg.activities.size();
15138            ArrayList<IntentFilter> result = new ArrayList<>();
15139            for (int n=0; n<count; n++) {
15140                PackageParser.Activity activity = pkg.activities.get(n);
15141                if (activity.intents != null && activity.intents.size() > 0) {
15142                    result.addAll(activity.intents);
15143                }
15144            }
15145            return new ParceledListSlice<>(result);
15146        }
15147    }
15148
15149    @Override
15150    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15151        mContext.enforceCallingOrSelfPermission(
15152                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15153
15154        synchronized (mPackages) {
15155            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15156            if (packageName != null) {
15157                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15158                        packageName, userId);
15159            }
15160            return result;
15161        }
15162    }
15163
15164    @Override
15165    public String getDefaultBrowserPackageName(int userId) {
15166        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15167            return null;
15168        }
15169        synchronized (mPackages) {
15170            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15171        }
15172    }
15173
15174    /**
15175     * Get the "allow unknown sources" setting.
15176     *
15177     * @return the current "allow unknown sources" setting
15178     */
15179    private int getUnknownSourcesSettings() {
15180        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15181                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15182                -1);
15183    }
15184
15185    @Override
15186    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15187        final int callingUid = Binder.getCallingUid();
15188        if (getInstantAppPackageName(callingUid) != null) {
15189            return;
15190        }
15191        // writer
15192        synchronized (mPackages) {
15193            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15194            if (targetPackageSetting == null
15195                    || filterAppAccessLPr(
15196                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15197                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15198            }
15199
15200            PackageSetting installerPackageSetting;
15201            if (installerPackageName != null) {
15202                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15203                if (installerPackageSetting == null) {
15204                    throw new IllegalArgumentException("Unknown installer package: "
15205                            + installerPackageName);
15206                }
15207            } else {
15208                installerPackageSetting = null;
15209            }
15210
15211            Signature[] callerSignature;
15212            Object obj = mSettings.getUserIdLPr(callingUid);
15213            if (obj != null) {
15214                if (obj instanceof SharedUserSetting) {
15215                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15216                } else if (obj instanceof PackageSetting) {
15217                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15218                } else {
15219                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15220                }
15221            } else {
15222                throw new SecurityException("Unknown calling UID: " + callingUid);
15223            }
15224
15225            // Verify: can't set installerPackageName to a package that is
15226            // not signed with the same cert as the caller.
15227            if (installerPackageSetting != null) {
15228                if (compareSignatures(callerSignature,
15229                        installerPackageSetting.signatures.mSignatures)
15230                        != PackageManager.SIGNATURE_MATCH) {
15231                    throw new SecurityException(
15232                            "Caller does not have same cert as new installer package "
15233                            + installerPackageName);
15234                }
15235            }
15236
15237            // Verify: if target already has an installer package, it must
15238            // be signed with the same cert as the caller.
15239            if (targetPackageSetting.installerPackageName != null) {
15240                PackageSetting setting = mSettings.mPackages.get(
15241                        targetPackageSetting.installerPackageName);
15242                // If the currently set package isn't valid, then it's always
15243                // okay to change it.
15244                if (setting != null) {
15245                    if (compareSignatures(callerSignature,
15246                            setting.signatures.mSignatures)
15247                            != PackageManager.SIGNATURE_MATCH) {
15248                        throw new SecurityException(
15249                                "Caller does not have same cert as old installer package "
15250                                + targetPackageSetting.installerPackageName);
15251                    }
15252                }
15253            }
15254
15255            // Okay!
15256            targetPackageSetting.installerPackageName = installerPackageName;
15257            if (installerPackageName != null) {
15258                mSettings.mInstallerPackages.add(installerPackageName);
15259            }
15260            scheduleWriteSettingsLocked();
15261        }
15262    }
15263
15264    @Override
15265    public void setApplicationCategoryHint(String packageName, int categoryHint,
15266            String callerPackageName) {
15267        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15268            throw new SecurityException("Instant applications don't have access to this method");
15269        }
15270        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15271                callerPackageName);
15272        synchronized (mPackages) {
15273            PackageSetting ps = mSettings.mPackages.get(packageName);
15274            if (ps == null) {
15275                throw new IllegalArgumentException("Unknown target package " + packageName);
15276            }
15277            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15278                throw new IllegalArgumentException("Unknown target package " + packageName);
15279            }
15280            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15281                throw new IllegalArgumentException("Calling package " + callerPackageName
15282                        + " is not installer for " + packageName);
15283            }
15284
15285            if (ps.categoryHint != categoryHint) {
15286                ps.categoryHint = categoryHint;
15287                scheduleWriteSettingsLocked();
15288            }
15289        }
15290    }
15291
15292    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15293        // Queue up an async operation since the package installation may take a little while.
15294        mHandler.post(new Runnable() {
15295            public void run() {
15296                mHandler.removeCallbacks(this);
15297                 // Result object to be returned
15298                PackageInstalledInfo res = new PackageInstalledInfo();
15299                res.setReturnCode(currentStatus);
15300                res.uid = -1;
15301                res.pkg = null;
15302                res.removedInfo = null;
15303                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15304                    args.doPreInstall(res.returnCode);
15305                    synchronized (mInstallLock) {
15306                        installPackageTracedLI(args, res);
15307                    }
15308                    args.doPostInstall(res.returnCode, res.uid);
15309                }
15310
15311                // A restore should be performed at this point if (a) the install
15312                // succeeded, (b) the operation is not an update, and (c) the new
15313                // package has not opted out of backup participation.
15314                final boolean update = res.removedInfo != null
15315                        && res.removedInfo.removedPackage != null;
15316                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15317                boolean doRestore = !update
15318                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15319
15320                // Set up the post-install work request bookkeeping.  This will be used
15321                // and cleaned up by the post-install event handling regardless of whether
15322                // there's a restore pass performed.  Token values are >= 1.
15323                int token;
15324                if (mNextInstallToken < 0) mNextInstallToken = 1;
15325                token = mNextInstallToken++;
15326
15327                PostInstallData data = new PostInstallData(args, res);
15328                mRunningInstalls.put(token, data);
15329                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15330
15331                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15332                    // Pass responsibility to the Backup Manager.  It will perform a
15333                    // restore if appropriate, then pass responsibility back to the
15334                    // Package Manager to run the post-install observer callbacks
15335                    // and broadcasts.
15336                    IBackupManager bm = IBackupManager.Stub.asInterface(
15337                            ServiceManager.getService(Context.BACKUP_SERVICE));
15338                    if (bm != null) {
15339                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15340                                + " to BM for possible restore");
15341                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15342                        try {
15343                            // TODO: http://b/22388012
15344                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15345                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15346                            } else {
15347                                doRestore = false;
15348                            }
15349                        } catch (RemoteException e) {
15350                            // can't happen; the backup manager is local
15351                        } catch (Exception e) {
15352                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15353                            doRestore = false;
15354                        }
15355                    } else {
15356                        Slog.e(TAG, "Backup Manager not found!");
15357                        doRestore = false;
15358                    }
15359                }
15360
15361                if (!doRestore) {
15362                    // No restore possible, or the Backup Manager was mysteriously not
15363                    // available -- just fire the post-install work request directly.
15364                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15365
15366                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15367
15368                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15369                    mHandler.sendMessage(msg);
15370                }
15371            }
15372        });
15373    }
15374
15375    /**
15376     * Callback from PackageSettings whenever an app is first transitioned out of the
15377     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15378     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15379     * here whether the app is the target of an ongoing install, and only send the
15380     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15381     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15382     * handling.
15383     */
15384    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15385        // Serialize this with the rest of the install-process message chain.  In the
15386        // restore-at-install case, this Runnable will necessarily run before the
15387        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15388        // are coherent.  In the non-restore case, the app has already completed install
15389        // and been launched through some other means, so it is not in a problematic
15390        // state for observers to see the FIRST_LAUNCH signal.
15391        mHandler.post(new Runnable() {
15392            @Override
15393            public void run() {
15394                for (int i = 0; i < mRunningInstalls.size(); i++) {
15395                    final PostInstallData data = mRunningInstalls.valueAt(i);
15396                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15397                        continue;
15398                    }
15399                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15400                        // right package; but is it for the right user?
15401                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15402                            if (userId == data.res.newUsers[uIndex]) {
15403                                if (DEBUG_BACKUP) {
15404                                    Slog.i(TAG, "Package " + pkgName
15405                                            + " being restored so deferring FIRST_LAUNCH");
15406                                }
15407                                return;
15408                            }
15409                        }
15410                    }
15411                }
15412                // didn't find it, so not being restored
15413                if (DEBUG_BACKUP) {
15414                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15415                }
15416                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15417            }
15418        });
15419    }
15420
15421    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15422        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15423                installerPkg, null, userIds);
15424    }
15425
15426    private abstract class HandlerParams {
15427        private static final int MAX_RETRIES = 4;
15428
15429        /**
15430         * Number of times startCopy() has been attempted and had a non-fatal
15431         * error.
15432         */
15433        private int mRetries = 0;
15434
15435        /** User handle for the user requesting the information or installation. */
15436        private final UserHandle mUser;
15437        String traceMethod;
15438        int traceCookie;
15439
15440        HandlerParams(UserHandle user) {
15441            mUser = user;
15442        }
15443
15444        UserHandle getUser() {
15445            return mUser;
15446        }
15447
15448        HandlerParams setTraceMethod(String traceMethod) {
15449            this.traceMethod = traceMethod;
15450            return this;
15451        }
15452
15453        HandlerParams setTraceCookie(int traceCookie) {
15454            this.traceCookie = traceCookie;
15455            return this;
15456        }
15457
15458        final boolean startCopy() {
15459            boolean res;
15460            try {
15461                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15462
15463                if (++mRetries > MAX_RETRIES) {
15464                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15465                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15466                    handleServiceError();
15467                    return false;
15468                } else {
15469                    handleStartCopy();
15470                    res = true;
15471                }
15472            } catch (RemoteException e) {
15473                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15474                mHandler.sendEmptyMessage(MCS_RECONNECT);
15475                res = false;
15476            }
15477            handleReturnCode();
15478            return res;
15479        }
15480
15481        final void serviceError() {
15482            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15483            handleServiceError();
15484            handleReturnCode();
15485        }
15486
15487        abstract void handleStartCopy() throws RemoteException;
15488        abstract void handleServiceError();
15489        abstract void handleReturnCode();
15490    }
15491
15492    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15493        for (File path : paths) {
15494            try {
15495                mcs.clearDirectory(path.getAbsolutePath());
15496            } catch (RemoteException e) {
15497            }
15498        }
15499    }
15500
15501    static class OriginInfo {
15502        /**
15503         * Location where install is coming from, before it has been
15504         * copied/renamed into place. This could be a single monolithic APK
15505         * file, or a cluster directory. This location may be untrusted.
15506         */
15507        final File file;
15508        final String cid;
15509
15510        /**
15511         * Flag indicating that {@link #file} or {@link #cid} has already been
15512         * staged, meaning downstream users don't need to defensively copy the
15513         * contents.
15514         */
15515        final boolean staged;
15516
15517        /**
15518         * Flag indicating that {@link #file} or {@link #cid} is an already
15519         * installed app that is being moved.
15520         */
15521        final boolean existing;
15522
15523        final String resolvedPath;
15524        final File resolvedFile;
15525
15526        static OriginInfo fromNothing() {
15527            return new OriginInfo(null, null, false, false);
15528        }
15529
15530        static OriginInfo fromUntrustedFile(File file) {
15531            return new OriginInfo(file, null, false, false);
15532        }
15533
15534        static OriginInfo fromExistingFile(File file) {
15535            return new OriginInfo(file, null, false, true);
15536        }
15537
15538        static OriginInfo fromStagedFile(File file) {
15539            return new OriginInfo(file, null, true, false);
15540        }
15541
15542        static OriginInfo fromStagedContainer(String cid) {
15543            return new OriginInfo(null, cid, true, false);
15544        }
15545
15546        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15547            this.file = file;
15548            this.cid = cid;
15549            this.staged = staged;
15550            this.existing = existing;
15551
15552            if (cid != null) {
15553                resolvedPath = PackageHelper.getSdDir(cid);
15554                resolvedFile = new File(resolvedPath);
15555            } else if (file != null) {
15556                resolvedPath = file.getAbsolutePath();
15557                resolvedFile = file;
15558            } else {
15559                resolvedPath = null;
15560                resolvedFile = null;
15561            }
15562        }
15563    }
15564
15565    static class MoveInfo {
15566        final int moveId;
15567        final String fromUuid;
15568        final String toUuid;
15569        final String packageName;
15570        final String dataAppName;
15571        final int appId;
15572        final String seinfo;
15573        final int targetSdkVersion;
15574
15575        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15576                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15577            this.moveId = moveId;
15578            this.fromUuid = fromUuid;
15579            this.toUuid = toUuid;
15580            this.packageName = packageName;
15581            this.dataAppName = dataAppName;
15582            this.appId = appId;
15583            this.seinfo = seinfo;
15584            this.targetSdkVersion = targetSdkVersion;
15585        }
15586    }
15587
15588    static class VerificationInfo {
15589        /** A constant used to indicate that a uid value is not present. */
15590        public static final int NO_UID = -1;
15591
15592        /** URI referencing where the package was downloaded from. */
15593        final Uri originatingUri;
15594
15595        /** HTTP referrer URI associated with the originatingURI. */
15596        final Uri referrer;
15597
15598        /** UID of the application that the install request originated from. */
15599        final int originatingUid;
15600
15601        /** UID of application requesting the install */
15602        final int installerUid;
15603
15604        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15605            this.originatingUri = originatingUri;
15606            this.referrer = referrer;
15607            this.originatingUid = originatingUid;
15608            this.installerUid = installerUid;
15609        }
15610    }
15611
15612    class InstallParams extends HandlerParams {
15613        final OriginInfo origin;
15614        final MoveInfo move;
15615        final IPackageInstallObserver2 observer;
15616        int installFlags;
15617        final String installerPackageName;
15618        final String volumeUuid;
15619        private InstallArgs mArgs;
15620        private int mRet;
15621        final String packageAbiOverride;
15622        final String[] grantedRuntimePermissions;
15623        final VerificationInfo verificationInfo;
15624        final Certificate[][] certificates;
15625        final int installReason;
15626
15627        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15628                int installFlags, String installerPackageName, String volumeUuid,
15629                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15630                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15631            super(user);
15632            this.origin = origin;
15633            this.move = move;
15634            this.observer = observer;
15635            this.installFlags = installFlags;
15636            this.installerPackageName = installerPackageName;
15637            this.volumeUuid = volumeUuid;
15638            this.verificationInfo = verificationInfo;
15639            this.packageAbiOverride = packageAbiOverride;
15640            this.grantedRuntimePermissions = grantedPermissions;
15641            this.certificates = certificates;
15642            this.installReason = installReason;
15643        }
15644
15645        @Override
15646        public String toString() {
15647            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15648                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15649        }
15650
15651        private int installLocationPolicy(PackageInfoLite pkgLite) {
15652            String packageName = pkgLite.packageName;
15653            int installLocation = pkgLite.installLocation;
15654            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15655            // reader
15656            synchronized (mPackages) {
15657                // Currently installed package which the new package is attempting to replace or
15658                // null if no such package is installed.
15659                PackageParser.Package installedPkg = mPackages.get(packageName);
15660                // Package which currently owns the data which the new package will own if installed.
15661                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15662                // will be null whereas dataOwnerPkg will contain information about the package
15663                // which was uninstalled while keeping its data.
15664                PackageParser.Package dataOwnerPkg = installedPkg;
15665                if (dataOwnerPkg  == null) {
15666                    PackageSetting ps = mSettings.mPackages.get(packageName);
15667                    if (ps != null) {
15668                        dataOwnerPkg = ps.pkg;
15669                    }
15670                }
15671
15672                if (dataOwnerPkg != null) {
15673                    // If installed, the package will get access to data left on the device by its
15674                    // predecessor. As a security measure, this is permited only if this is not a
15675                    // version downgrade or if the predecessor package is marked as debuggable and
15676                    // a downgrade is explicitly requested.
15677                    //
15678                    // On debuggable platform builds, downgrades are permitted even for
15679                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15680                    // not offer security guarantees and thus it's OK to disable some security
15681                    // mechanisms to make debugging/testing easier on those builds. However, even on
15682                    // debuggable builds downgrades of packages are permitted only if requested via
15683                    // installFlags. This is because we aim to keep the behavior of debuggable
15684                    // platform builds as close as possible to the behavior of non-debuggable
15685                    // platform builds.
15686                    final boolean downgradeRequested =
15687                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15688                    final boolean packageDebuggable =
15689                                (dataOwnerPkg.applicationInfo.flags
15690                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15691                    final boolean downgradePermitted =
15692                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15693                    if (!downgradePermitted) {
15694                        try {
15695                            checkDowngrade(dataOwnerPkg, pkgLite);
15696                        } catch (PackageManagerException e) {
15697                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15698                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15699                        }
15700                    }
15701                }
15702
15703                if (installedPkg != null) {
15704                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15705                        // Check for updated system application.
15706                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15707                            if (onSd) {
15708                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15709                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15710                            }
15711                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15712                        } else {
15713                            if (onSd) {
15714                                // Install flag overrides everything.
15715                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15716                            }
15717                            // If current upgrade specifies particular preference
15718                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15719                                // Application explicitly specified internal.
15720                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15721                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15722                                // App explictly prefers external. Let policy decide
15723                            } else {
15724                                // Prefer previous location
15725                                if (isExternal(installedPkg)) {
15726                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15727                                }
15728                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15729                            }
15730                        }
15731                    } else {
15732                        // Invalid install. Return error code
15733                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15734                    }
15735                }
15736            }
15737            // All the special cases have been taken care of.
15738            // Return result based on recommended install location.
15739            if (onSd) {
15740                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15741            }
15742            return pkgLite.recommendedInstallLocation;
15743        }
15744
15745        /*
15746         * Invoke remote method to get package information and install
15747         * location values. Override install location based on default
15748         * policy if needed and then create install arguments based
15749         * on the install location.
15750         */
15751        public void handleStartCopy() throws RemoteException {
15752            int ret = PackageManager.INSTALL_SUCCEEDED;
15753
15754            // If we're already staged, we've firmly committed to an install location
15755            if (origin.staged) {
15756                if (origin.file != null) {
15757                    installFlags |= PackageManager.INSTALL_INTERNAL;
15758                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15759                } else if (origin.cid != null) {
15760                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15761                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15762                } else {
15763                    throw new IllegalStateException("Invalid stage location");
15764                }
15765            }
15766
15767            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15768            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15769            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15770            PackageInfoLite pkgLite = null;
15771
15772            if (onInt && onSd) {
15773                // Check if both bits are set.
15774                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15775                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15776            } else if (onSd && ephemeral) {
15777                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15778                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15779            } else {
15780                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15781                        packageAbiOverride);
15782
15783                if (DEBUG_EPHEMERAL && ephemeral) {
15784                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15785                }
15786
15787                /*
15788                 * If we have too little free space, try to free cache
15789                 * before giving up.
15790                 */
15791                if (!origin.staged && pkgLite.recommendedInstallLocation
15792                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15793                    // TODO: focus freeing disk space on the target device
15794                    final StorageManager storage = StorageManager.from(mContext);
15795                    final long lowThreshold = storage.getStorageLowBytes(
15796                            Environment.getDataDirectory());
15797
15798                    final long sizeBytes = mContainerService.calculateInstalledSize(
15799                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15800
15801                    try {
15802                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15803                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15804                                installFlags, packageAbiOverride);
15805                    } catch (InstallerException e) {
15806                        Slog.w(TAG, "Failed to free cache", e);
15807                    }
15808
15809                    /*
15810                     * The cache free must have deleted the file we
15811                     * downloaded to install.
15812                     *
15813                     * TODO: fix the "freeCache" call to not delete
15814                     *       the file we care about.
15815                     */
15816                    if (pkgLite.recommendedInstallLocation
15817                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15818                        pkgLite.recommendedInstallLocation
15819                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15820                    }
15821                }
15822            }
15823
15824            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15825                int loc = pkgLite.recommendedInstallLocation;
15826                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15827                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15828                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15829                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15830                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15831                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15832                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15833                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15834                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15835                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15836                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15837                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15838                } else {
15839                    // Override with defaults if needed.
15840                    loc = installLocationPolicy(pkgLite);
15841                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15842                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15843                    } else if (!onSd && !onInt) {
15844                        // Override install location with flags
15845                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15846                            // Set the flag to install on external media.
15847                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15848                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15849                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15850                            if (DEBUG_EPHEMERAL) {
15851                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15852                            }
15853                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15854                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15855                                    |PackageManager.INSTALL_INTERNAL);
15856                        } else {
15857                            // Make sure the flag for installing on external
15858                            // media is unset
15859                            installFlags |= PackageManager.INSTALL_INTERNAL;
15860                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15861                        }
15862                    }
15863                }
15864            }
15865
15866            final InstallArgs args = createInstallArgs(this);
15867            mArgs = args;
15868
15869            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15870                // TODO: http://b/22976637
15871                // Apps installed for "all" users use the device owner to verify the app
15872                UserHandle verifierUser = getUser();
15873                if (verifierUser == UserHandle.ALL) {
15874                    verifierUser = UserHandle.SYSTEM;
15875                }
15876
15877                /*
15878                 * Determine if we have any installed package verifiers. If we
15879                 * do, then we'll defer to them to verify the packages.
15880                 */
15881                final int requiredUid = mRequiredVerifierPackage == null ? -1
15882                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15883                                verifierUser.getIdentifier());
15884                final int installerUid =
15885                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15886                if (!origin.existing && requiredUid != -1
15887                        && isVerificationEnabled(
15888                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15889                    final Intent verification = new Intent(
15890                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15891                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15892                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15893                            PACKAGE_MIME_TYPE);
15894                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15895
15896                    // Query all live verifiers based on current user state
15897                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15898                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15899
15900                    if (DEBUG_VERIFY) {
15901                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15902                                + verification.toString() + " with " + pkgLite.verifiers.length
15903                                + " optional verifiers");
15904                    }
15905
15906                    final int verificationId = mPendingVerificationToken++;
15907
15908                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15909
15910                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15911                            installerPackageName);
15912
15913                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15914                            installFlags);
15915
15916                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15917                            pkgLite.packageName);
15918
15919                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15920                            pkgLite.versionCode);
15921
15922                    if (verificationInfo != null) {
15923                        if (verificationInfo.originatingUri != null) {
15924                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15925                                    verificationInfo.originatingUri);
15926                        }
15927                        if (verificationInfo.referrer != null) {
15928                            verification.putExtra(Intent.EXTRA_REFERRER,
15929                                    verificationInfo.referrer);
15930                        }
15931                        if (verificationInfo.originatingUid >= 0) {
15932                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15933                                    verificationInfo.originatingUid);
15934                        }
15935                        if (verificationInfo.installerUid >= 0) {
15936                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15937                                    verificationInfo.installerUid);
15938                        }
15939                    }
15940
15941                    final PackageVerificationState verificationState = new PackageVerificationState(
15942                            requiredUid, args);
15943
15944                    mPendingVerification.append(verificationId, verificationState);
15945
15946                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15947                            receivers, verificationState);
15948
15949                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15950                    final long idleDuration = getVerificationTimeout();
15951
15952                    /*
15953                     * If any sufficient verifiers were listed in the package
15954                     * manifest, attempt to ask them.
15955                     */
15956                    if (sufficientVerifiers != null) {
15957                        final int N = sufficientVerifiers.size();
15958                        if (N == 0) {
15959                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15960                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15961                        } else {
15962                            for (int i = 0; i < N; i++) {
15963                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15964                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15965                                        verifierComponent.getPackageName(), idleDuration,
15966                                        verifierUser.getIdentifier(), false, "package verifier");
15967
15968                                final Intent sufficientIntent = new Intent(verification);
15969                                sufficientIntent.setComponent(verifierComponent);
15970                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15971                            }
15972                        }
15973                    }
15974
15975                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15976                            mRequiredVerifierPackage, receivers);
15977                    if (ret == PackageManager.INSTALL_SUCCEEDED
15978                            && mRequiredVerifierPackage != null) {
15979                        Trace.asyncTraceBegin(
15980                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15981                        /*
15982                         * Send the intent to the required verification agent,
15983                         * but only start the verification timeout after the
15984                         * target BroadcastReceivers have run.
15985                         */
15986                        verification.setComponent(requiredVerifierComponent);
15987                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15988                                mRequiredVerifierPackage, idleDuration,
15989                                verifierUser.getIdentifier(), false, "package verifier");
15990                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15991                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15992                                new BroadcastReceiver() {
15993                                    @Override
15994                                    public void onReceive(Context context, Intent intent) {
15995                                        final Message msg = mHandler
15996                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15997                                        msg.arg1 = verificationId;
15998                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15999                                    }
16000                                }, null, 0, null, null);
16001
16002                        /*
16003                         * We don't want the copy to proceed until verification
16004                         * succeeds, so null out this field.
16005                         */
16006                        mArgs = null;
16007                    }
16008                } else {
16009                    /*
16010                     * No package verification is enabled, so immediately start
16011                     * the remote call to initiate copy using temporary file.
16012                     */
16013                    ret = args.copyApk(mContainerService, true);
16014                }
16015            }
16016
16017            mRet = ret;
16018        }
16019
16020        @Override
16021        void handleReturnCode() {
16022            // If mArgs is null, then MCS couldn't be reached. When it
16023            // reconnects, it will try again to install. At that point, this
16024            // will succeed.
16025            if (mArgs != null) {
16026                processPendingInstall(mArgs, mRet);
16027            }
16028        }
16029
16030        @Override
16031        void handleServiceError() {
16032            mArgs = createInstallArgs(this);
16033            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16034        }
16035
16036        public boolean isForwardLocked() {
16037            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16038        }
16039    }
16040
16041    /**
16042     * Used during creation of InstallArgs
16043     *
16044     * @param installFlags package installation flags
16045     * @return true if should be installed on external storage
16046     */
16047    private static boolean installOnExternalAsec(int installFlags) {
16048        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16049            return false;
16050        }
16051        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16052            return true;
16053        }
16054        return false;
16055    }
16056
16057    /**
16058     * Used during creation of InstallArgs
16059     *
16060     * @param installFlags package installation flags
16061     * @return true if should be installed as forward locked
16062     */
16063    private static boolean installForwardLocked(int installFlags) {
16064        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16065    }
16066
16067    private InstallArgs createInstallArgs(InstallParams params) {
16068        if (params.move != null) {
16069            return new MoveInstallArgs(params);
16070        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16071            return new AsecInstallArgs(params);
16072        } else {
16073            return new FileInstallArgs(params);
16074        }
16075    }
16076
16077    /**
16078     * Create args that describe an existing installed package. Typically used
16079     * when cleaning up old installs, or used as a move source.
16080     */
16081    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16082            String resourcePath, String[] instructionSets) {
16083        final boolean isInAsec;
16084        if (installOnExternalAsec(installFlags)) {
16085            /* Apps on SD card are always in ASEC containers. */
16086            isInAsec = true;
16087        } else if (installForwardLocked(installFlags)
16088                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16089            /*
16090             * Forward-locked apps are only in ASEC containers if they're the
16091             * new style
16092             */
16093            isInAsec = true;
16094        } else {
16095            isInAsec = false;
16096        }
16097
16098        if (isInAsec) {
16099            return new AsecInstallArgs(codePath, instructionSets,
16100                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16101        } else {
16102            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16103        }
16104    }
16105
16106    static abstract class InstallArgs {
16107        /** @see InstallParams#origin */
16108        final OriginInfo origin;
16109        /** @see InstallParams#move */
16110        final MoveInfo move;
16111
16112        final IPackageInstallObserver2 observer;
16113        // Always refers to PackageManager flags only
16114        final int installFlags;
16115        final String installerPackageName;
16116        final String volumeUuid;
16117        final UserHandle user;
16118        final String abiOverride;
16119        final String[] installGrantPermissions;
16120        /** If non-null, drop an async trace when the install completes */
16121        final String traceMethod;
16122        final int traceCookie;
16123        final Certificate[][] certificates;
16124        final int installReason;
16125
16126        // The list of instruction sets supported by this app. This is currently
16127        // only used during the rmdex() phase to clean up resources. We can get rid of this
16128        // if we move dex files under the common app path.
16129        /* nullable */ String[] instructionSets;
16130
16131        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16132                int installFlags, String installerPackageName, String volumeUuid,
16133                UserHandle user, String[] instructionSets,
16134                String abiOverride, String[] installGrantPermissions,
16135                String traceMethod, int traceCookie, Certificate[][] certificates,
16136                int installReason) {
16137            this.origin = origin;
16138            this.move = move;
16139            this.installFlags = installFlags;
16140            this.observer = observer;
16141            this.installerPackageName = installerPackageName;
16142            this.volumeUuid = volumeUuid;
16143            this.user = user;
16144            this.instructionSets = instructionSets;
16145            this.abiOverride = abiOverride;
16146            this.installGrantPermissions = installGrantPermissions;
16147            this.traceMethod = traceMethod;
16148            this.traceCookie = traceCookie;
16149            this.certificates = certificates;
16150            this.installReason = installReason;
16151        }
16152
16153        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16154        abstract int doPreInstall(int status);
16155
16156        /**
16157         * Rename package into final resting place. All paths on the given
16158         * scanned package should be updated to reflect the rename.
16159         */
16160        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16161        abstract int doPostInstall(int status, int uid);
16162
16163        /** @see PackageSettingBase#codePathString */
16164        abstract String getCodePath();
16165        /** @see PackageSettingBase#resourcePathString */
16166        abstract String getResourcePath();
16167
16168        // Need installer lock especially for dex file removal.
16169        abstract void cleanUpResourcesLI();
16170        abstract boolean doPostDeleteLI(boolean delete);
16171
16172        /**
16173         * Called before the source arguments are copied. This is used mostly
16174         * for MoveParams when it needs to read the source file to put it in the
16175         * destination.
16176         */
16177        int doPreCopy() {
16178            return PackageManager.INSTALL_SUCCEEDED;
16179        }
16180
16181        /**
16182         * Called after the source arguments are copied. This is used mostly for
16183         * MoveParams when it needs to read the source file to put it in the
16184         * destination.
16185         */
16186        int doPostCopy(int uid) {
16187            return PackageManager.INSTALL_SUCCEEDED;
16188        }
16189
16190        protected boolean isFwdLocked() {
16191            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16192        }
16193
16194        protected boolean isExternalAsec() {
16195            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16196        }
16197
16198        protected boolean isEphemeral() {
16199            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16200        }
16201
16202        UserHandle getUser() {
16203            return user;
16204        }
16205    }
16206
16207    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16208        if (!allCodePaths.isEmpty()) {
16209            if (instructionSets == null) {
16210                throw new IllegalStateException("instructionSet == null");
16211            }
16212            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16213            for (String codePath : allCodePaths) {
16214                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16215                    try {
16216                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16217                    } catch (InstallerException ignored) {
16218                    }
16219                }
16220            }
16221        }
16222    }
16223
16224    /**
16225     * Logic to handle installation of non-ASEC applications, including copying
16226     * and renaming logic.
16227     */
16228    class FileInstallArgs extends InstallArgs {
16229        private File codeFile;
16230        private File resourceFile;
16231
16232        // Example topology:
16233        // /data/app/com.example/base.apk
16234        // /data/app/com.example/split_foo.apk
16235        // /data/app/com.example/lib/arm/libfoo.so
16236        // /data/app/com.example/lib/arm64/libfoo.so
16237        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16238
16239        /** New install */
16240        FileInstallArgs(InstallParams params) {
16241            super(params.origin, params.move, params.observer, params.installFlags,
16242                    params.installerPackageName, params.volumeUuid,
16243                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16244                    params.grantedRuntimePermissions,
16245                    params.traceMethod, params.traceCookie, params.certificates,
16246                    params.installReason);
16247            if (isFwdLocked()) {
16248                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16249            }
16250        }
16251
16252        /** Existing install */
16253        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16254            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16255                    null, null, null, 0, null /*certificates*/,
16256                    PackageManager.INSTALL_REASON_UNKNOWN);
16257            this.codeFile = (codePath != null) ? new File(codePath) : null;
16258            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16259        }
16260
16261        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16262            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16263            try {
16264                return doCopyApk(imcs, temp);
16265            } finally {
16266                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16267            }
16268        }
16269
16270        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16271            if (origin.staged) {
16272                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16273                codeFile = origin.file;
16274                resourceFile = origin.file;
16275                return PackageManager.INSTALL_SUCCEEDED;
16276            }
16277
16278            try {
16279                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16280                final File tempDir =
16281                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16282                codeFile = tempDir;
16283                resourceFile = tempDir;
16284            } catch (IOException e) {
16285                Slog.w(TAG, "Failed to create copy file: " + e);
16286                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16287            }
16288
16289            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16290                @Override
16291                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16292                    if (!FileUtils.isValidExtFilename(name)) {
16293                        throw new IllegalArgumentException("Invalid filename: " + name);
16294                    }
16295                    try {
16296                        final File file = new File(codeFile, name);
16297                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16298                                O_RDWR | O_CREAT, 0644);
16299                        Os.chmod(file.getAbsolutePath(), 0644);
16300                        return new ParcelFileDescriptor(fd);
16301                    } catch (ErrnoException e) {
16302                        throw new RemoteException("Failed to open: " + e.getMessage());
16303                    }
16304                }
16305            };
16306
16307            int ret = PackageManager.INSTALL_SUCCEEDED;
16308            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16309            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16310                Slog.e(TAG, "Failed to copy package");
16311                return ret;
16312            }
16313
16314            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16315            NativeLibraryHelper.Handle handle = null;
16316            try {
16317                handle = NativeLibraryHelper.Handle.create(codeFile);
16318                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16319                        abiOverride);
16320            } catch (IOException e) {
16321                Slog.e(TAG, "Copying native libraries failed", e);
16322                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16323            } finally {
16324                IoUtils.closeQuietly(handle);
16325            }
16326
16327            return ret;
16328        }
16329
16330        int doPreInstall(int status) {
16331            if (status != PackageManager.INSTALL_SUCCEEDED) {
16332                cleanUp();
16333            }
16334            return status;
16335        }
16336
16337        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16338            if (status != PackageManager.INSTALL_SUCCEEDED) {
16339                cleanUp();
16340                return false;
16341            }
16342
16343            final File targetDir = codeFile.getParentFile();
16344            final File beforeCodeFile = codeFile;
16345            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16346
16347            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16348            try {
16349                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16350            } catch (ErrnoException e) {
16351                Slog.w(TAG, "Failed to rename", e);
16352                return false;
16353            }
16354
16355            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16356                Slog.w(TAG, "Failed to restorecon");
16357                return false;
16358            }
16359
16360            // Reflect the rename internally
16361            codeFile = afterCodeFile;
16362            resourceFile = afterCodeFile;
16363
16364            // Reflect the rename in scanned details
16365            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16366            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16367                    afterCodeFile, pkg.baseCodePath));
16368            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16369                    afterCodeFile, pkg.splitCodePaths));
16370
16371            // Reflect the rename in app info
16372            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16373            pkg.setApplicationInfoCodePath(pkg.codePath);
16374            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16375            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16376            pkg.setApplicationInfoResourcePath(pkg.codePath);
16377            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16378            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16379
16380            return true;
16381        }
16382
16383        int doPostInstall(int status, int uid) {
16384            if (status != PackageManager.INSTALL_SUCCEEDED) {
16385                cleanUp();
16386            }
16387            return status;
16388        }
16389
16390        @Override
16391        String getCodePath() {
16392            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16393        }
16394
16395        @Override
16396        String getResourcePath() {
16397            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16398        }
16399
16400        private boolean cleanUp() {
16401            if (codeFile == null || !codeFile.exists()) {
16402                return false;
16403            }
16404
16405            removeCodePathLI(codeFile);
16406
16407            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16408                resourceFile.delete();
16409            }
16410
16411            return true;
16412        }
16413
16414        void cleanUpResourcesLI() {
16415            // Try enumerating all code paths before deleting
16416            List<String> allCodePaths = Collections.EMPTY_LIST;
16417            if (codeFile != null && codeFile.exists()) {
16418                try {
16419                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16420                    allCodePaths = pkg.getAllCodePaths();
16421                } catch (PackageParserException e) {
16422                    // Ignored; we tried our best
16423                }
16424            }
16425
16426            cleanUp();
16427            removeDexFiles(allCodePaths, instructionSets);
16428        }
16429
16430        boolean doPostDeleteLI(boolean delete) {
16431            // XXX err, shouldn't we respect the delete flag?
16432            cleanUpResourcesLI();
16433            return true;
16434        }
16435    }
16436
16437    private boolean isAsecExternal(String cid) {
16438        final String asecPath = PackageHelper.getSdFilesystem(cid);
16439        return !asecPath.startsWith(mAsecInternalPath);
16440    }
16441
16442    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16443            PackageManagerException {
16444        if (copyRet < 0) {
16445            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16446                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16447                throw new PackageManagerException(copyRet, message);
16448            }
16449        }
16450    }
16451
16452    /**
16453     * Extract the StorageManagerService "container ID" from the full code path of an
16454     * .apk.
16455     */
16456    static String cidFromCodePath(String fullCodePath) {
16457        int eidx = fullCodePath.lastIndexOf("/");
16458        String subStr1 = fullCodePath.substring(0, eidx);
16459        int sidx = subStr1.lastIndexOf("/");
16460        return subStr1.substring(sidx+1, eidx);
16461    }
16462
16463    /**
16464     * Logic to handle installation of ASEC applications, including copying and
16465     * renaming logic.
16466     */
16467    class AsecInstallArgs extends InstallArgs {
16468        static final String RES_FILE_NAME = "pkg.apk";
16469        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16470
16471        String cid;
16472        String packagePath;
16473        String resourcePath;
16474
16475        /** New install */
16476        AsecInstallArgs(InstallParams params) {
16477            super(params.origin, params.move, params.observer, params.installFlags,
16478                    params.installerPackageName, params.volumeUuid,
16479                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16480                    params.grantedRuntimePermissions,
16481                    params.traceMethod, params.traceCookie, params.certificates,
16482                    params.installReason);
16483        }
16484
16485        /** Existing install */
16486        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16487                        boolean isExternal, boolean isForwardLocked) {
16488            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16489                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16490                    instructionSets, null, null, null, 0, null /*certificates*/,
16491                    PackageManager.INSTALL_REASON_UNKNOWN);
16492            // Hackily pretend we're still looking at a full code path
16493            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16494                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16495            }
16496
16497            // Extract cid from fullCodePath
16498            int eidx = fullCodePath.lastIndexOf("/");
16499            String subStr1 = fullCodePath.substring(0, eidx);
16500            int sidx = subStr1.lastIndexOf("/");
16501            cid = subStr1.substring(sidx+1, eidx);
16502            setMountPath(subStr1);
16503        }
16504
16505        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16506            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16507                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16508                    instructionSets, null, null, null, 0, null /*certificates*/,
16509                    PackageManager.INSTALL_REASON_UNKNOWN);
16510            this.cid = cid;
16511            setMountPath(PackageHelper.getSdDir(cid));
16512        }
16513
16514        void createCopyFile() {
16515            cid = mInstallerService.allocateExternalStageCidLegacy();
16516        }
16517
16518        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16519            if (origin.staged && origin.cid != null) {
16520                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16521                cid = origin.cid;
16522                setMountPath(PackageHelper.getSdDir(cid));
16523                return PackageManager.INSTALL_SUCCEEDED;
16524            }
16525
16526            if (temp) {
16527                createCopyFile();
16528            } else {
16529                /*
16530                 * Pre-emptively destroy the container since it's destroyed if
16531                 * copying fails due to it existing anyway.
16532                 */
16533                PackageHelper.destroySdDir(cid);
16534            }
16535
16536            final String newMountPath = imcs.copyPackageToContainer(
16537                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16538                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16539
16540            if (newMountPath != null) {
16541                setMountPath(newMountPath);
16542                return PackageManager.INSTALL_SUCCEEDED;
16543            } else {
16544                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16545            }
16546        }
16547
16548        @Override
16549        String getCodePath() {
16550            return packagePath;
16551        }
16552
16553        @Override
16554        String getResourcePath() {
16555            return resourcePath;
16556        }
16557
16558        int doPreInstall(int status) {
16559            if (status != PackageManager.INSTALL_SUCCEEDED) {
16560                // Destroy container
16561                PackageHelper.destroySdDir(cid);
16562            } else {
16563                boolean mounted = PackageHelper.isContainerMounted(cid);
16564                if (!mounted) {
16565                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16566                            Process.SYSTEM_UID);
16567                    if (newMountPath != null) {
16568                        setMountPath(newMountPath);
16569                    } else {
16570                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16571                    }
16572                }
16573            }
16574            return status;
16575        }
16576
16577        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16578            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16579            String newMountPath = null;
16580            if (PackageHelper.isContainerMounted(cid)) {
16581                // Unmount the container
16582                if (!PackageHelper.unMountSdDir(cid)) {
16583                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16584                    return false;
16585                }
16586            }
16587            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16588                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16589                        " which might be stale. Will try to clean up.");
16590                // Clean up the stale container and proceed to recreate.
16591                if (!PackageHelper.destroySdDir(newCacheId)) {
16592                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16593                    return false;
16594                }
16595                // Successfully cleaned up stale container. Try to rename again.
16596                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16597                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16598                            + " inspite of cleaning it up.");
16599                    return false;
16600                }
16601            }
16602            if (!PackageHelper.isContainerMounted(newCacheId)) {
16603                Slog.w(TAG, "Mounting container " + newCacheId);
16604                newMountPath = PackageHelper.mountSdDir(newCacheId,
16605                        getEncryptKey(), Process.SYSTEM_UID);
16606            } else {
16607                newMountPath = PackageHelper.getSdDir(newCacheId);
16608            }
16609            if (newMountPath == null) {
16610                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16611                return false;
16612            }
16613            Log.i(TAG, "Succesfully renamed " + cid +
16614                    " to " + newCacheId +
16615                    " at new path: " + newMountPath);
16616            cid = newCacheId;
16617
16618            final File beforeCodeFile = new File(packagePath);
16619            setMountPath(newMountPath);
16620            final File afterCodeFile = new File(packagePath);
16621
16622            // Reflect the rename in scanned details
16623            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16624            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16625                    afterCodeFile, pkg.baseCodePath));
16626            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16627                    afterCodeFile, pkg.splitCodePaths));
16628
16629            // Reflect the rename in app info
16630            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16631            pkg.setApplicationInfoCodePath(pkg.codePath);
16632            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16633            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16634            pkg.setApplicationInfoResourcePath(pkg.codePath);
16635            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16636            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16637
16638            return true;
16639        }
16640
16641        private void setMountPath(String mountPath) {
16642            final File mountFile = new File(mountPath);
16643
16644            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16645            if (monolithicFile.exists()) {
16646                packagePath = monolithicFile.getAbsolutePath();
16647                if (isFwdLocked()) {
16648                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16649                } else {
16650                    resourcePath = packagePath;
16651                }
16652            } else {
16653                packagePath = mountFile.getAbsolutePath();
16654                resourcePath = packagePath;
16655            }
16656        }
16657
16658        int doPostInstall(int status, int uid) {
16659            if (status != PackageManager.INSTALL_SUCCEEDED) {
16660                cleanUp();
16661            } else {
16662                final int groupOwner;
16663                final String protectedFile;
16664                if (isFwdLocked()) {
16665                    groupOwner = UserHandle.getSharedAppGid(uid);
16666                    protectedFile = RES_FILE_NAME;
16667                } else {
16668                    groupOwner = -1;
16669                    protectedFile = null;
16670                }
16671
16672                if (uid < Process.FIRST_APPLICATION_UID
16673                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16674                    Slog.e(TAG, "Failed to finalize " + cid);
16675                    PackageHelper.destroySdDir(cid);
16676                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16677                }
16678
16679                boolean mounted = PackageHelper.isContainerMounted(cid);
16680                if (!mounted) {
16681                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16682                }
16683            }
16684            return status;
16685        }
16686
16687        private void cleanUp() {
16688            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16689
16690            // Destroy secure container
16691            PackageHelper.destroySdDir(cid);
16692        }
16693
16694        private List<String> getAllCodePaths() {
16695            final File codeFile = new File(getCodePath());
16696            if (codeFile != null && codeFile.exists()) {
16697                try {
16698                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16699                    return pkg.getAllCodePaths();
16700                } catch (PackageParserException e) {
16701                    // Ignored; we tried our best
16702                }
16703            }
16704            return Collections.EMPTY_LIST;
16705        }
16706
16707        void cleanUpResourcesLI() {
16708            // Enumerate all code paths before deleting
16709            cleanUpResourcesLI(getAllCodePaths());
16710        }
16711
16712        private void cleanUpResourcesLI(List<String> allCodePaths) {
16713            cleanUp();
16714            removeDexFiles(allCodePaths, instructionSets);
16715        }
16716
16717        String getPackageName() {
16718            return getAsecPackageName(cid);
16719        }
16720
16721        boolean doPostDeleteLI(boolean delete) {
16722            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16723            final List<String> allCodePaths = getAllCodePaths();
16724            boolean mounted = PackageHelper.isContainerMounted(cid);
16725            if (mounted) {
16726                // Unmount first
16727                if (PackageHelper.unMountSdDir(cid)) {
16728                    mounted = false;
16729                }
16730            }
16731            if (!mounted && delete) {
16732                cleanUpResourcesLI(allCodePaths);
16733            }
16734            return !mounted;
16735        }
16736
16737        @Override
16738        int doPreCopy() {
16739            if (isFwdLocked()) {
16740                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16741                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16742                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16743                }
16744            }
16745
16746            return PackageManager.INSTALL_SUCCEEDED;
16747        }
16748
16749        @Override
16750        int doPostCopy(int uid) {
16751            if (isFwdLocked()) {
16752                if (uid < Process.FIRST_APPLICATION_UID
16753                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16754                                RES_FILE_NAME)) {
16755                    Slog.e(TAG, "Failed to finalize " + cid);
16756                    PackageHelper.destroySdDir(cid);
16757                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16758                }
16759            }
16760
16761            return PackageManager.INSTALL_SUCCEEDED;
16762        }
16763    }
16764
16765    /**
16766     * Logic to handle movement of existing installed applications.
16767     */
16768    class MoveInstallArgs extends InstallArgs {
16769        private File codeFile;
16770        private File resourceFile;
16771
16772        /** New install */
16773        MoveInstallArgs(InstallParams params) {
16774            super(params.origin, params.move, params.observer, params.installFlags,
16775                    params.installerPackageName, params.volumeUuid,
16776                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16777                    params.grantedRuntimePermissions,
16778                    params.traceMethod, params.traceCookie, params.certificates,
16779                    params.installReason);
16780        }
16781
16782        int copyApk(IMediaContainerService imcs, boolean temp) {
16783            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16784                    + move.fromUuid + " to " + move.toUuid);
16785            synchronized (mInstaller) {
16786                try {
16787                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16788                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16789                } catch (InstallerException e) {
16790                    Slog.w(TAG, "Failed to move app", e);
16791                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16792                }
16793            }
16794
16795            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16796            resourceFile = codeFile;
16797            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16798
16799            return PackageManager.INSTALL_SUCCEEDED;
16800        }
16801
16802        int doPreInstall(int status) {
16803            if (status != PackageManager.INSTALL_SUCCEEDED) {
16804                cleanUp(move.toUuid);
16805            }
16806            return status;
16807        }
16808
16809        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16810            if (status != PackageManager.INSTALL_SUCCEEDED) {
16811                cleanUp(move.toUuid);
16812                return false;
16813            }
16814
16815            // Reflect the move in app info
16816            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16817            pkg.setApplicationInfoCodePath(pkg.codePath);
16818            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16819            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16820            pkg.setApplicationInfoResourcePath(pkg.codePath);
16821            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16822            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16823
16824            return true;
16825        }
16826
16827        int doPostInstall(int status, int uid) {
16828            if (status == PackageManager.INSTALL_SUCCEEDED) {
16829                cleanUp(move.fromUuid);
16830            } else {
16831                cleanUp(move.toUuid);
16832            }
16833            return status;
16834        }
16835
16836        @Override
16837        String getCodePath() {
16838            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16839        }
16840
16841        @Override
16842        String getResourcePath() {
16843            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16844        }
16845
16846        private boolean cleanUp(String volumeUuid) {
16847            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16848                    move.dataAppName);
16849            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16850            final int[] userIds = sUserManager.getUserIds();
16851            synchronized (mInstallLock) {
16852                // Clean up both app data and code
16853                // All package moves are frozen until finished
16854                for (int userId : userIds) {
16855                    try {
16856                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16857                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16858                    } catch (InstallerException e) {
16859                        Slog.w(TAG, String.valueOf(e));
16860                    }
16861                }
16862                removeCodePathLI(codeFile);
16863            }
16864            return true;
16865        }
16866
16867        void cleanUpResourcesLI() {
16868            throw new UnsupportedOperationException();
16869        }
16870
16871        boolean doPostDeleteLI(boolean delete) {
16872            throw new UnsupportedOperationException();
16873        }
16874    }
16875
16876    static String getAsecPackageName(String packageCid) {
16877        int idx = packageCid.lastIndexOf("-");
16878        if (idx == -1) {
16879            return packageCid;
16880        }
16881        return packageCid.substring(0, idx);
16882    }
16883
16884    // Utility method used to create code paths based on package name and available index.
16885    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16886        String idxStr = "";
16887        int idx = 1;
16888        // Fall back to default value of idx=1 if prefix is not
16889        // part of oldCodePath
16890        if (oldCodePath != null) {
16891            String subStr = oldCodePath;
16892            // Drop the suffix right away
16893            if (suffix != null && subStr.endsWith(suffix)) {
16894                subStr = subStr.substring(0, subStr.length() - suffix.length());
16895            }
16896            // If oldCodePath already contains prefix find out the
16897            // ending index to either increment or decrement.
16898            int sidx = subStr.lastIndexOf(prefix);
16899            if (sidx != -1) {
16900                subStr = subStr.substring(sidx + prefix.length());
16901                if (subStr != null) {
16902                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16903                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16904                    }
16905                    try {
16906                        idx = Integer.parseInt(subStr);
16907                        if (idx <= 1) {
16908                            idx++;
16909                        } else {
16910                            idx--;
16911                        }
16912                    } catch(NumberFormatException e) {
16913                    }
16914                }
16915            }
16916        }
16917        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16918        return prefix + idxStr;
16919    }
16920
16921    private File getNextCodePath(File targetDir, String packageName) {
16922        File result;
16923        SecureRandom random = new SecureRandom();
16924        byte[] bytes = new byte[16];
16925        do {
16926            random.nextBytes(bytes);
16927            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16928            result = new File(targetDir, packageName + "-" + suffix);
16929        } while (result.exists());
16930        return result;
16931    }
16932
16933    // Utility method that returns the relative package path with respect
16934    // to the installation directory. Like say for /data/data/com.test-1.apk
16935    // string com.test-1 is returned.
16936    static String deriveCodePathName(String codePath) {
16937        if (codePath == null) {
16938            return null;
16939        }
16940        final File codeFile = new File(codePath);
16941        final String name = codeFile.getName();
16942        if (codeFile.isDirectory()) {
16943            return name;
16944        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16945            final int lastDot = name.lastIndexOf('.');
16946            return name.substring(0, lastDot);
16947        } else {
16948            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16949            return null;
16950        }
16951    }
16952
16953    static class PackageInstalledInfo {
16954        String name;
16955        int uid;
16956        // The set of users that originally had this package installed.
16957        int[] origUsers;
16958        // The set of users that now have this package installed.
16959        int[] newUsers;
16960        PackageParser.Package pkg;
16961        int returnCode;
16962        String returnMsg;
16963        PackageRemovedInfo removedInfo;
16964        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16965
16966        public void setError(int code, String msg) {
16967            setReturnCode(code);
16968            setReturnMessage(msg);
16969            Slog.w(TAG, msg);
16970        }
16971
16972        public void setError(String msg, PackageParserException e) {
16973            setReturnCode(e.error);
16974            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16975            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16976            for (int i = 0; i < childCount; i++) {
16977                addedChildPackages.valueAt(i).setError(msg, e);
16978            }
16979            Slog.w(TAG, msg, e);
16980        }
16981
16982        public void setError(String msg, PackageManagerException e) {
16983            returnCode = e.error;
16984            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16985            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16986            for (int i = 0; i < childCount; i++) {
16987                addedChildPackages.valueAt(i).setError(msg, e);
16988            }
16989            Slog.w(TAG, msg, e);
16990        }
16991
16992        public void setReturnCode(int returnCode) {
16993            this.returnCode = returnCode;
16994            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16995            for (int i = 0; i < childCount; i++) {
16996                addedChildPackages.valueAt(i).returnCode = returnCode;
16997            }
16998        }
16999
17000        private void setReturnMessage(String returnMsg) {
17001            this.returnMsg = returnMsg;
17002            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17003            for (int i = 0; i < childCount; i++) {
17004                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17005            }
17006        }
17007
17008        // In some error cases we want to convey more info back to the observer
17009        String origPackage;
17010        String origPermission;
17011    }
17012
17013    /*
17014     * Install a non-existing package.
17015     */
17016    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17017            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17018            PackageInstalledInfo res, int installReason) {
17019        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17020
17021        // Remember this for later, in case we need to rollback this install
17022        String pkgName = pkg.packageName;
17023
17024        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17025
17026        synchronized(mPackages) {
17027            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17028            if (renamedPackage != null) {
17029                // A package with the same name is already installed, though
17030                // it has been renamed to an older name.  The package we
17031                // are trying to install should be installed as an update to
17032                // the existing one, but that has not been requested, so bail.
17033                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17034                        + " without first uninstalling package running as "
17035                        + renamedPackage);
17036                return;
17037            }
17038            if (mPackages.containsKey(pkgName)) {
17039                // Don't allow installation over an existing package with the same name.
17040                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17041                        + " without first uninstalling.");
17042                return;
17043            }
17044        }
17045
17046        try {
17047            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17048                    System.currentTimeMillis(), user);
17049
17050            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17051
17052            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17053                prepareAppDataAfterInstallLIF(newPackage);
17054
17055            } else {
17056                // Remove package from internal structures, but keep around any
17057                // data that might have already existed
17058                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17059                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17060            }
17061        } catch (PackageManagerException e) {
17062            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17063        }
17064
17065        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17066    }
17067
17068    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17069        // Can't rotate keys during boot or if sharedUser.
17070        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17071                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17072            return false;
17073        }
17074        // app is using upgradeKeySets; make sure all are valid
17075        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17076        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17077        for (int i = 0; i < upgradeKeySets.length; i++) {
17078            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17079                Slog.wtf(TAG, "Package "
17080                         + (oldPs.name != null ? oldPs.name : "<null>")
17081                         + " contains upgrade-key-set reference to unknown key-set: "
17082                         + upgradeKeySets[i]
17083                         + " reverting to signatures check.");
17084                return false;
17085            }
17086        }
17087        return true;
17088    }
17089
17090    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17091        // Upgrade keysets are being used.  Determine if new package has a superset of the
17092        // required keys.
17093        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17094        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17095        for (int i = 0; i < upgradeKeySets.length; i++) {
17096            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17097            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17098                return true;
17099            }
17100        }
17101        return false;
17102    }
17103
17104    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17105        try (DigestInputStream digestStream =
17106                new DigestInputStream(new FileInputStream(file), digest)) {
17107            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17108        }
17109    }
17110
17111    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17112            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17113            int installReason) {
17114        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17115
17116        final PackageParser.Package oldPackage;
17117        final PackageSetting ps;
17118        final String pkgName = pkg.packageName;
17119        final int[] allUsers;
17120        final int[] installedUsers;
17121
17122        synchronized(mPackages) {
17123            oldPackage = mPackages.get(pkgName);
17124            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17125
17126            // don't allow upgrade to target a release SDK from a pre-release SDK
17127            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17128                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17129            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17130                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17131            if (oldTargetsPreRelease
17132                    && !newTargetsPreRelease
17133                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17134                Slog.w(TAG, "Can't install package targeting released sdk");
17135                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17136                return;
17137            }
17138
17139            ps = mSettings.mPackages.get(pkgName);
17140
17141            // verify signatures are valid
17142            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17143                if (!checkUpgradeKeySetLP(ps, pkg)) {
17144                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17145                            "New package not signed by keys specified by upgrade-keysets: "
17146                                    + pkgName);
17147                    return;
17148                }
17149            } else {
17150                // default to original signature matching
17151                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17152                        != PackageManager.SIGNATURE_MATCH) {
17153                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17154                            "New package has a different signature: " + pkgName);
17155                    return;
17156                }
17157            }
17158
17159            // don't allow a system upgrade unless the upgrade hash matches
17160            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17161                byte[] digestBytes = null;
17162                try {
17163                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17164                    updateDigest(digest, new File(pkg.baseCodePath));
17165                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17166                        for (String path : pkg.splitCodePaths) {
17167                            updateDigest(digest, new File(path));
17168                        }
17169                    }
17170                    digestBytes = digest.digest();
17171                } catch (NoSuchAlgorithmException | IOException e) {
17172                    res.setError(INSTALL_FAILED_INVALID_APK,
17173                            "Could not compute hash: " + pkgName);
17174                    return;
17175                }
17176                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17177                    res.setError(INSTALL_FAILED_INVALID_APK,
17178                            "New package fails restrict-update check: " + pkgName);
17179                    return;
17180                }
17181                // retain upgrade restriction
17182                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17183            }
17184
17185            // Check for shared user id changes
17186            String invalidPackageName =
17187                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17188            if (invalidPackageName != null) {
17189                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17190                        "Package " + invalidPackageName + " tried to change user "
17191                                + oldPackage.mSharedUserId);
17192                return;
17193            }
17194
17195            // In case of rollback, remember per-user/profile install state
17196            allUsers = sUserManager.getUserIds();
17197            installedUsers = ps.queryInstalledUsers(allUsers, true);
17198
17199            // don't allow an upgrade from full to ephemeral
17200            if (isInstantApp) {
17201                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17202                    for (int currentUser : allUsers) {
17203                        if (!ps.getInstantApp(currentUser)) {
17204                            // can't downgrade from full to instant
17205                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17206                                    + " for user: " + currentUser);
17207                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17208                            return;
17209                        }
17210                    }
17211                } else if (!ps.getInstantApp(user.getIdentifier())) {
17212                    // can't downgrade from full to instant
17213                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17214                            + " for user: " + user.getIdentifier());
17215                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17216                    return;
17217                }
17218            }
17219        }
17220
17221        // Update what is removed
17222        res.removedInfo = new PackageRemovedInfo(this);
17223        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17224        res.removedInfo.removedPackage = oldPackage.packageName;
17225        res.removedInfo.installerPackageName = ps.installerPackageName;
17226        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17227        res.removedInfo.isUpdate = true;
17228        res.removedInfo.origUsers = installedUsers;
17229        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17230        for (int i = 0; i < installedUsers.length; i++) {
17231            final int userId = installedUsers[i];
17232            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17233        }
17234
17235        final int childCount = (oldPackage.childPackages != null)
17236                ? oldPackage.childPackages.size() : 0;
17237        for (int i = 0; i < childCount; i++) {
17238            boolean childPackageUpdated = false;
17239            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17240            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17241            if (res.addedChildPackages != null) {
17242                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17243                if (childRes != null) {
17244                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17245                    childRes.removedInfo.removedPackage = childPkg.packageName;
17246                    if (childPs != null) {
17247                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17248                    }
17249                    childRes.removedInfo.isUpdate = true;
17250                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17251                    childPackageUpdated = true;
17252                }
17253            }
17254            if (!childPackageUpdated) {
17255                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17256                childRemovedRes.removedPackage = childPkg.packageName;
17257                if (childPs != null) {
17258                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17259                }
17260                childRemovedRes.isUpdate = false;
17261                childRemovedRes.dataRemoved = true;
17262                synchronized (mPackages) {
17263                    if (childPs != null) {
17264                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17265                    }
17266                }
17267                if (res.removedInfo.removedChildPackages == null) {
17268                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17269                }
17270                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17271            }
17272        }
17273
17274        boolean sysPkg = (isSystemApp(oldPackage));
17275        if (sysPkg) {
17276            // Set the system/privileged flags as needed
17277            final boolean privileged =
17278                    (oldPackage.applicationInfo.privateFlags
17279                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17280            final int systemPolicyFlags = policyFlags
17281                    | PackageParser.PARSE_IS_SYSTEM
17282                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17283
17284            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17285                    user, allUsers, installerPackageName, res, installReason);
17286        } else {
17287            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17288                    user, allUsers, installerPackageName, res, installReason);
17289        }
17290    }
17291
17292    @Override
17293    public List<String> getPreviousCodePaths(String packageName) {
17294        final int callingUid = Binder.getCallingUid();
17295        final List<String> result = new ArrayList<>();
17296        if (getInstantAppPackageName(callingUid) != null) {
17297            return result;
17298        }
17299        final PackageSetting ps = mSettings.mPackages.get(packageName);
17300        if (ps != null
17301                && ps.oldCodePaths != null
17302                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17303            result.addAll(ps.oldCodePaths);
17304        }
17305        return result;
17306    }
17307
17308    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17309            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17310            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17311            int installReason) {
17312        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17313                + deletedPackage);
17314
17315        String pkgName = deletedPackage.packageName;
17316        boolean deletedPkg = true;
17317        boolean addedPkg = false;
17318        boolean updatedSettings = false;
17319        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17320        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17321                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17322
17323        final long origUpdateTime = (pkg.mExtras != null)
17324                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17325
17326        // First delete the existing package while retaining the data directory
17327        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17328                res.removedInfo, true, pkg)) {
17329            // If the existing package wasn't successfully deleted
17330            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17331            deletedPkg = false;
17332        } else {
17333            // Successfully deleted the old package; proceed with replace.
17334
17335            // If deleted package lived in a container, give users a chance to
17336            // relinquish resources before killing.
17337            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17338                if (DEBUG_INSTALL) {
17339                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17340                }
17341                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17342                final ArrayList<String> pkgList = new ArrayList<String>(1);
17343                pkgList.add(deletedPackage.applicationInfo.packageName);
17344                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17345            }
17346
17347            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17348                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17349            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17350
17351            try {
17352                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17353                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17354                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17355                        installReason);
17356
17357                // Update the in-memory copy of the previous code paths.
17358                PackageSetting ps = mSettings.mPackages.get(pkgName);
17359                if (!killApp) {
17360                    if (ps.oldCodePaths == null) {
17361                        ps.oldCodePaths = new ArraySet<>();
17362                    }
17363                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17364                    if (deletedPackage.splitCodePaths != null) {
17365                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17366                    }
17367                } else {
17368                    ps.oldCodePaths = null;
17369                }
17370                if (ps.childPackageNames != null) {
17371                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17372                        final String childPkgName = ps.childPackageNames.get(i);
17373                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17374                        childPs.oldCodePaths = ps.oldCodePaths;
17375                    }
17376                }
17377                // set instant app status, but, only if it's explicitly specified
17378                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17379                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17380                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17381                prepareAppDataAfterInstallLIF(newPackage);
17382                addedPkg = true;
17383                mDexManager.notifyPackageUpdated(newPackage.packageName,
17384                        newPackage.baseCodePath, newPackage.splitCodePaths);
17385            } catch (PackageManagerException e) {
17386                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17387            }
17388        }
17389
17390        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17391            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17392
17393            // Revert all internal state mutations and added folders for the failed install
17394            if (addedPkg) {
17395                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17396                        res.removedInfo, true, null);
17397            }
17398
17399            // Restore the old package
17400            if (deletedPkg) {
17401                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17402                File restoreFile = new File(deletedPackage.codePath);
17403                // Parse old package
17404                boolean oldExternal = isExternal(deletedPackage);
17405                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17406                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17407                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17408                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17409                try {
17410                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17411                            null);
17412                } catch (PackageManagerException e) {
17413                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17414                            + e.getMessage());
17415                    return;
17416                }
17417
17418                synchronized (mPackages) {
17419                    // Ensure the installer package name up to date
17420                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17421
17422                    // Update permissions for restored package
17423                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17424
17425                    mSettings.writeLPr();
17426                }
17427
17428                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17429            }
17430        } else {
17431            synchronized (mPackages) {
17432                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17433                if (ps != null) {
17434                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17435                    if (res.removedInfo.removedChildPackages != null) {
17436                        final int childCount = res.removedInfo.removedChildPackages.size();
17437                        // Iterate in reverse as we may modify the collection
17438                        for (int i = childCount - 1; i >= 0; i--) {
17439                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17440                            if (res.addedChildPackages.containsKey(childPackageName)) {
17441                                res.removedInfo.removedChildPackages.removeAt(i);
17442                            } else {
17443                                PackageRemovedInfo childInfo = res.removedInfo
17444                                        .removedChildPackages.valueAt(i);
17445                                childInfo.removedForAllUsers = mPackages.get(
17446                                        childInfo.removedPackage) == null;
17447                            }
17448                        }
17449                    }
17450                }
17451            }
17452        }
17453    }
17454
17455    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17456            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17457            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17458            int installReason) {
17459        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17460                + ", old=" + deletedPackage);
17461
17462        final boolean disabledSystem;
17463
17464        // Remove existing system package
17465        removePackageLI(deletedPackage, true);
17466
17467        synchronized (mPackages) {
17468            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17469        }
17470        if (!disabledSystem) {
17471            // We didn't need to disable the .apk as a current system package,
17472            // which means we are replacing another update that is already
17473            // installed.  We need to make sure to delete the older one's .apk.
17474            res.removedInfo.args = createInstallArgsForExisting(0,
17475                    deletedPackage.applicationInfo.getCodePath(),
17476                    deletedPackage.applicationInfo.getResourcePath(),
17477                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17478        } else {
17479            res.removedInfo.args = null;
17480        }
17481
17482        // Successfully disabled the old package. Now proceed with re-installation
17483        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17484                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17485        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17486
17487        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17488        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17489                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17490
17491        PackageParser.Package newPackage = null;
17492        try {
17493            // Add the package to the internal data structures
17494            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17495
17496            // Set the update and install times
17497            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17498            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17499                    System.currentTimeMillis());
17500
17501            // Update the package dynamic state if succeeded
17502            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17503                // Now that the install succeeded make sure we remove data
17504                // directories for any child package the update removed.
17505                final int deletedChildCount = (deletedPackage.childPackages != null)
17506                        ? deletedPackage.childPackages.size() : 0;
17507                final int newChildCount = (newPackage.childPackages != null)
17508                        ? newPackage.childPackages.size() : 0;
17509                for (int i = 0; i < deletedChildCount; i++) {
17510                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17511                    boolean childPackageDeleted = true;
17512                    for (int j = 0; j < newChildCount; j++) {
17513                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17514                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17515                            childPackageDeleted = false;
17516                            break;
17517                        }
17518                    }
17519                    if (childPackageDeleted) {
17520                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17521                                deletedChildPkg.packageName);
17522                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17523                            PackageRemovedInfo removedChildRes = res.removedInfo
17524                                    .removedChildPackages.get(deletedChildPkg.packageName);
17525                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17526                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17527                        }
17528                    }
17529                }
17530
17531                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17532                        installReason);
17533                prepareAppDataAfterInstallLIF(newPackage);
17534
17535                mDexManager.notifyPackageUpdated(newPackage.packageName,
17536                            newPackage.baseCodePath, newPackage.splitCodePaths);
17537            }
17538        } catch (PackageManagerException e) {
17539            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17540            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17541        }
17542
17543        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17544            // Re installation failed. Restore old information
17545            // Remove new pkg information
17546            if (newPackage != null) {
17547                removeInstalledPackageLI(newPackage, true);
17548            }
17549            // Add back the old system package
17550            try {
17551                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17552            } catch (PackageManagerException e) {
17553                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17554            }
17555
17556            synchronized (mPackages) {
17557                if (disabledSystem) {
17558                    enableSystemPackageLPw(deletedPackage);
17559                }
17560
17561                // Ensure the installer package name up to date
17562                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17563
17564                // Update permissions for restored package
17565                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17566
17567                mSettings.writeLPr();
17568            }
17569
17570            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17571                    + " after failed upgrade");
17572        }
17573    }
17574
17575    /**
17576     * Checks whether the parent or any of the child packages have a change shared
17577     * user. For a package to be a valid update the shred users of the parent and
17578     * the children should match. We may later support changing child shared users.
17579     * @param oldPkg The updated package.
17580     * @param newPkg The update package.
17581     * @return The shared user that change between the versions.
17582     */
17583    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17584            PackageParser.Package newPkg) {
17585        // Check parent shared user
17586        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17587            return newPkg.packageName;
17588        }
17589        // Check child shared users
17590        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17591        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17592        for (int i = 0; i < newChildCount; i++) {
17593            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17594            // If this child was present, did it have the same shared user?
17595            for (int j = 0; j < oldChildCount; j++) {
17596                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17597                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17598                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17599                    return newChildPkg.packageName;
17600                }
17601            }
17602        }
17603        return null;
17604    }
17605
17606    private void removeNativeBinariesLI(PackageSetting ps) {
17607        // Remove the lib path for the parent package
17608        if (ps != null) {
17609            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17610            // Remove the lib path for the child packages
17611            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17612            for (int i = 0; i < childCount; i++) {
17613                PackageSetting childPs = null;
17614                synchronized (mPackages) {
17615                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17616                }
17617                if (childPs != null) {
17618                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17619                            .legacyNativeLibraryPathString);
17620                }
17621            }
17622        }
17623    }
17624
17625    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17626        // Enable the parent package
17627        mSettings.enableSystemPackageLPw(pkg.packageName);
17628        // Enable the child packages
17629        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17630        for (int i = 0; i < childCount; i++) {
17631            PackageParser.Package childPkg = pkg.childPackages.get(i);
17632            mSettings.enableSystemPackageLPw(childPkg.packageName);
17633        }
17634    }
17635
17636    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17637            PackageParser.Package newPkg) {
17638        // Disable the parent package (parent always replaced)
17639        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17640        // Disable the child packages
17641        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17642        for (int i = 0; i < childCount; i++) {
17643            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17644            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17645            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17646        }
17647        return disabled;
17648    }
17649
17650    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17651            String installerPackageName) {
17652        // Enable the parent package
17653        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17654        // Enable the child packages
17655        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17656        for (int i = 0; i < childCount; i++) {
17657            PackageParser.Package childPkg = pkg.childPackages.get(i);
17658            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17659        }
17660    }
17661
17662    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17663        // Collect all used permissions in the UID
17664        ArraySet<String> usedPermissions = new ArraySet<>();
17665        final int packageCount = su.packages.size();
17666        for (int i = 0; i < packageCount; i++) {
17667            PackageSetting ps = su.packages.valueAt(i);
17668            if (ps.pkg == null) {
17669                continue;
17670            }
17671            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17672            for (int j = 0; j < requestedPermCount; j++) {
17673                String permission = ps.pkg.requestedPermissions.get(j);
17674                BasePermission bp = mSettings.mPermissions.get(permission);
17675                if (bp != null) {
17676                    usedPermissions.add(permission);
17677                }
17678            }
17679        }
17680
17681        PermissionsState permissionsState = su.getPermissionsState();
17682        // Prune install permissions
17683        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17684        final int installPermCount = installPermStates.size();
17685        for (int i = installPermCount - 1; i >= 0;  i--) {
17686            PermissionState permissionState = installPermStates.get(i);
17687            if (!usedPermissions.contains(permissionState.getName())) {
17688                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17689                if (bp != null) {
17690                    permissionsState.revokeInstallPermission(bp);
17691                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17692                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17693                }
17694            }
17695        }
17696
17697        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17698
17699        // Prune runtime permissions
17700        for (int userId : allUserIds) {
17701            List<PermissionState> runtimePermStates = permissionsState
17702                    .getRuntimePermissionStates(userId);
17703            final int runtimePermCount = runtimePermStates.size();
17704            for (int i = runtimePermCount - 1; i >= 0; i--) {
17705                PermissionState permissionState = runtimePermStates.get(i);
17706                if (!usedPermissions.contains(permissionState.getName())) {
17707                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17708                    if (bp != null) {
17709                        permissionsState.revokeRuntimePermission(bp, userId);
17710                        permissionsState.updatePermissionFlags(bp, userId,
17711                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17712                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17713                                runtimePermissionChangedUserIds, userId);
17714                    }
17715                }
17716            }
17717        }
17718
17719        return runtimePermissionChangedUserIds;
17720    }
17721
17722    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17723            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17724        // Update the parent package setting
17725        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17726                res, user, installReason);
17727        // Update the child packages setting
17728        final int childCount = (newPackage.childPackages != null)
17729                ? newPackage.childPackages.size() : 0;
17730        for (int i = 0; i < childCount; i++) {
17731            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17732            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17733            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17734                    childRes.origUsers, childRes, user, installReason);
17735        }
17736    }
17737
17738    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17739            String installerPackageName, int[] allUsers, int[] installedForUsers,
17740            PackageInstalledInfo res, UserHandle user, int installReason) {
17741        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17742
17743        String pkgName = newPackage.packageName;
17744        synchronized (mPackages) {
17745            //write settings. the installStatus will be incomplete at this stage.
17746            //note that the new package setting would have already been
17747            //added to mPackages. It hasn't been persisted yet.
17748            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17749            // TODO: Remove this write? It's also written at the end of this method
17750            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17751            mSettings.writeLPr();
17752            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17753        }
17754
17755        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17756        synchronized (mPackages) {
17757            updatePermissionsLPw(newPackage.packageName, newPackage,
17758                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17759                            ? UPDATE_PERMISSIONS_ALL : 0));
17760            // For system-bundled packages, we assume that installing an upgraded version
17761            // of the package implies that the user actually wants to run that new code,
17762            // so we enable the package.
17763            PackageSetting ps = mSettings.mPackages.get(pkgName);
17764            final int userId = user.getIdentifier();
17765            if (ps != null) {
17766                if (isSystemApp(newPackage)) {
17767                    if (DEBUG_INSTALL) {
17768                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17769                    }
17770                    // Enable system package for requested users
17771                    if (res.origUsers != null) {
17772                        for (int origUserId : res.origUsers) {
17773                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17774                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17775                                        origUserId, installerPackageName);
17776                            }
17777                        }
17778                    }
17779                    // Also convey the prior install/uninstall state
17780                    if (allUsers != null && installedForUsers != null) {
17781                        for (int currentUserId : allUsers) {
17782                            final boolean installed = ArrayUtils.contains(
17783                                    installedForUsers, currentUserId);
17784                            if (DEBUG_INSTALL) {
17785                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17786                            }
17787                            ps.setInstalled(installed, currentUserId);
17788                        }
17789                        // these install state changes will be persisted in the
17790                        // upcoming call to mSettings.writeLPr().
17791                    }
17792                }
17793                // It's implied that when a user requests installation, they want the app to be
17794                // installed and enabled.
17795                if (userId != UserHandle.USER_ALL) {
17796                    ps.setInstalled(true, userId);
17797                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17798                }
17799
17800                // When replacing an existing package, preserve the original install reason for all
17801                // users that had the package installed before.
17802                final Set<Integer> previousUserIds = new ArraySet<>();
17803                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17804                    final int installReasonCount = res.removedInfo.installReasons.size();
17805                    for (int i = 0; i < installReasonCount; i++) {
17806                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17807                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17808                        ps.setInstallReason(previousInstallReason, previousUserId);
17809                        previousUserIds.add(previousUserId);
17810                    }
17811                }
17812
17813                // Set install reason for users that are having the package newly installed.
17814                if (userId == UserHandle.USER_ALL) {
17815                    for (int currentUserId : sUserManager.getUserIds()) {
17816                        if (!previousUserIds.contains(currentUserId)) {
17817                            ps.setInstallReason(installReason, currentUserId);
17818                        }
17819                    }
17820                } else if (!previousUserIds.contains(userId)) {
17821                    ps.setInstallReason(installReason, userId);
17822                }
17823                mSettings.writeKernelMappingLPr(ps);
17824            }
17825            res.name = pkgName;
17826            res.uid = newPackage.applicationInfo.uid;
17827            res.pkg = newPackage;
17828            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17829            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17830            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17831            //to update install status
17832            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17833            mSettings.writeLPr();
17834            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17835        }
17836
17837        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17838    }
17839
17840    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17841        try {
17842            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17843            installPackageLI(args, res);
17844        } finally {
17845            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17846        }
17847    }
17848
17849    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17850        final int installFlags = args.installFlags;
17851        final String installerPackageName = args.installerPackageName;
17852        final String volumeUuid = args.volumeUuid;
17853        final File tmpPackageFile = new File(args.getCodePath());
17854        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17855        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17856                || (args.volumeUuid != null));
17857        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17858        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17859        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17860        boolean replace = false;
17861        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17862        if (args.move != null) {
17863            // moving a complete application; perform an initial scan on the new install location
17864            scanFlags |= SCAN_INITIAL;
17865        }
17866        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17867            scanFlags |= SCAN_DONT_KILL_APP;
17868        }
17869        if (instantApp) {
17870            scanFlags |= SCAN_AS_INSTANT_APP;
17871        }
17872        if (fullApp) {
17873            scanFlags |= SCAN_AS_FULL_APP;
17874        }
17875
17876        // Result object to be returned
17877        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17878
17879        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17880
17881        // Sanity check
17882        if (instantApp && (forwardLocked || onExternal)) {
17883            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17884                    + " external=" + onExternal);
17885            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17886            return;
17887        }
17888
17889        // Retrieve PackageSettings and parse package
17890        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17891                | PackageParser.PARSE_ENFORCE_CODE
17892                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17893                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17894                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17895                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17896        PackageParser pp = new PackageParser();
17897        pp.setSeparateProcesses(mSeparateProcesses);
17898        pp.setDisplayMetrics(mMetrics);
17899        pp.setCallback(mPackageParserCallback);
17900
17901        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17902        final PackageParser.Package pkg;
17903        try {
17904            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17905        } catch (PackageParserException e) {
17906            res.setError("Failed parse during installPackageLI", e);
17907            return;
17908        } finally {
17909            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17910        }
17911
17912        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17913        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17914            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17915            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17916                    "Instant app package must target O");
17917            return;
17918        }
17919        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17920            Slog.w(TAG, "Instant app package " + pkg.packageName
17921                    + " does not target targetSandboxVersion 2");
17922            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17923                    "Instant app package must use targetSanboxVersion 2");
17924            return;
17925        }
17926
17927        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17928            // Static shared libraries have synthetic package names
17929            renameStaticSharedLibraryPackage(pkg);
17930
17931            // No static shared libs on external storage
17932            if (onExternal) {
17933                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17934                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17935                        "Packages declaring static-shared libs cannot be updated");
17936                return;
17937            }
17938        }
17939
17940        // If we are installing a clustered package add results for the children
17941        if (pkg.childPackages != null) {
17942            synchronized (mPackages) {
17943                final int childCount = pkg.childPackages.size();
17944                for (int i = 0; i < childCount; i++) {
17945                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17946                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17947                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17948                    childRes.pkg = childPkg;
17949                    childRes.name = childPkg.packageName;
17950                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17951                    if (childPs != null) {
17952                        childRes.origUsers = childPs.queryInstalledUsers(
17953                                sUserManager.getUserIds(), true);
17954                    }
17955                    if ((mPackages.containsKey(childPkg.packageName))) {
17956                        childRes.removedInfo = new PackageRemovedInfo(this);
17957                        childRes.removedInfo.removedPackage = childPkg.packageName;
17958                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17959                    }
17960                    if (res.addedChildPackages == null) {
17961                        res.addedChildPackages = new ArrayMap<>();
17962                    }
17963                    res.addedChildPackages.put(childPkg.packageName, childRes);
17964                }
17965            }
17966        }
17967
17968        // If package doesn't declare API override, mark that we have an install
17969        // time CPU ABI override.
17970        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17971            pkg.cpuAbiOverride = args.abiOverride;
17972        }
17973
17974        String pkgName = res.name = pkg.packageName;
17975        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17976            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17977                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17978                return;
17979            }
17980        }
17981
17982        try {
17983            // either use what we've been given or parse directly from the APK
17984            if (args.certificates != null) {
17985                try {
17986                    PackageParser.populateCertificates(pkg, args.certificates);
17987                } catch (PackageParserException e) {
17988                    // there was something wrong with the certificates we were given;
17989                    // try to pull them from the APK
17990                    PackageParser.collectCertificates(pkg, parseFlags);
17991                }
17992            } else {
17993                PackageParser.collectCertificates(pkg, parseFlags);
17994            }
17995        } catch (PackageParserException e) {
17996            res.setError("Failed collect during installPackageLI", e);
17997            return;
17998        }
17999
18000        // Get rid of all references to package scan path via parser.
18001        pp = null;
18002        String oldCodePath = null;
18003        boolean systemApp = false;
18004        synchronized (mPackages) {
18005            // Check if installing already existing package
18006            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18007                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18008                if (pkg.mOriginalPackages != null
18009                        && pkg.mOriginalPackages.contains(oldName)
18010                        && mPackages.containsKey(oldName)) {
18011                    // This package is derived from an original package,
18012                    // and this device has been updating from that original
18013                    // name.  We must continue using the original name, so
18014                    // rename the new package here.
18015                    pkg.setPackageName(oldName);
18016                    pkgName = pkg.packageName;
18017                    replace = true;
18018                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18019                            + oldName + " pkgName=" + pkgName);
18020                } else if (mPackages.containsKey(pkgName)) {
18021                    // This package, under its official name, already exists
18022                    // on the device; we should replace it.
18023                    replace = true;
18024                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18025                }
18026
18027                // Child packages are installed through the parent package
18028                if (pkg.parentPackage != null) {
18029                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18030                            "Package " + pkg.packageName + " is child of package "
18031                                    + pkg.parentPackage.parentPackage + ". Child packages "
18032                                    + "can be updated only through the parent package.");
18033                    return;
18034                }
18035
18036                if (replace) {
18037                    // Prevent apps opting out from runtime permissions
18038                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18039                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18040                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18041                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18042                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18043                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18044                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18045                                        + " doesn't support runtime permissions but the old"
18046                                        + " target SDK " + oldTargetSdk + " does.");
18047                        return;
18048                    }
18049                    // Prevent apps from downgrading their targetSandbox.
18050                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18051                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18052                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18053                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18054                                "Package " + pkg.packageName + " new target sandbox "
18055                                + newTargetSandbox + " is incompatible with the previous value of"
18056                                + oldTargetSandbox + ".");
18057                        return;
18058                    }
18059
18060                    // Prevent installing of child packages
18061                    if (oldPackage.parentPackage != null) {
18062                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18063                                "Package " + pkg.packageName + " is child of package "
18064                                        + oldPackage.parentPackage + ". Child packages "
18065                                        + "can be updated only through the parent package.");
18066                        return;
18067                    }
18068                }
18069            }
18070
18071            PackageSetting ps = mSettings.mPackages.get(pkgName);
18072            if (ps != null) {
18073                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18074
18075                // Static shared libs have same package with different versions where
18076                // we internally use a synthetic package name to allow multiple versions
18077                // of the same package, therefore we need to compare signatures against
18078                // the package setting for the latest library version.
18079                PackageSetting signatureCheckPs = ps;
18080                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18081                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18082                    if (libraryEntry != null) {
18083                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18084                    }
18085                }
18086
18087                // Quick sanity check that we're signed correctly if updating;
18088                // we'll check this again later when scanning, but we want to
18089                // bail early here before tripping over redefined permissions.
18090                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18091                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18092                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18093                                + pkg.packageName + " upgrade keys do not match the "
18094                                + "previously installed version");
18095                        return;
18096                    }
18097                } else {
18098                    try {
18099                        verifySignaturesLP(signatureCheckPs, pkg);
18100                    } catch (PackageManagerException e) {
18101                        res.setError(e.error, e.getMessage());
18102                        return;
18103                    }
18104                }
18105
18106                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18107                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18108                    systemApp = (ps.pkg.applicationInfo.flags &
18109                            ApplicationInfo.FLAG_SYSTEM) != 0;
18110                }
18111                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18112            }
18113
18114            int N = pkg.permissions.size();
18115            for (int i = N-1; i >= 0; i--) {
18116                PackageParser.Permission perm = pkg.permissions.get(i);
18117                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18118
18119                // Don't allow anyone but the system to define ephemeral permissions.
18120                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18121                        && !systemApp) {
18122                    Slog.w(TAG, "Non-System package " + pkg.packageName
18123                            + " attempting to delcare ephemeral permission "
18124                            + perm.info.name + "; Removing ephemeral.");
18125                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18126                }
18127                // Check whether the newly-scanned package wants to define an already-defined perm
18128                if (bp != null) {
18129                    // If the defining package is signed with our cert, it's okay.  This
18130                    // also includes the "updating the same package" case, of course.
18131                    // "updating same package" could also involve key-rotation.
18132                    final boolean sigsOk;
18133                    if (bp.sourcePackage.equals(pkg.packageName)
18134                            && (bp.packageSetting instanceof PackageSetting)
18135                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18136                                    scanFlags))) {
18137                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18138                    } else {
18139                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18140                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18141                    }
18142                    if (!sigsOk) {
18143                        // If the owning package is the system itself, we log but allow
18144                        // install to proceed; we fail the install on all other permission
18145                        // redefinitions.
18146                        if (!bp.sourcePackage.equals("android")) {
18147                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18148                                    + pkg.packageName + " attempting to redeclare permission "
18149                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18150                            res.origPermission = perm.info.name;
18151                            res.origPackage = bp.sourcePackage;
18152                            return;
18153                        } else {
18154                            Slog.w(TAG, "Package " + pkg.packageName
18155                                    + " attempting to redeclare system permission "
18156                                    + perm.info.name + "; ignoring new declaration");
18157                            pkg.permissions.remove(i);
18158                        }
18159                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18160                        // Prevent apps to change protection level to dangerous from any other
18161                        // type as this would allow a privilege escalation where an app adds a
18162                        // normal/signature permission in other app's group and later redefines
18163                        // it as dangerous leading to the group auto-grant.
18164                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18165                                == PermissionInfo.PROTECTION_DANGEROUS) {
18166                            if (bp != null && !bp.isRuntime()) {
18167                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18168                                        + "non-runtime permission " + perm.info.name
18169                                        + " to runtime; keeping old protection level");
18170                                perm.info.protectionLevel = bp.protectionLevel;
18171                            }
18172                        }
18173                    }
18174                }
18175            }
18176        }
18177
18178        if (systemApp) {
18179            if (onExternal) {
18180                // Abort update; system app can't be replaced with app on sdcard
18181                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18182                        "Cannot install updates to system apps on sdcard");
18183                return;
18184            } else if (instantApp) {
18185                // Abort update; system app can't be replaced with an instant app
18186                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18187                        "Cannot update a system app with an instant app");
18188                return;
18189            }
18190        }
18191
18192        if (args.move != null) {
18193            // We did an in-place move, so dex is ready to roll
18194            scanFlags |= SCAN_NO_DEX;
18195            scanFlags |= SCAN_MOVE;
18196
18197            synchronized (mPackages) {
18198                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18199                if (ps == null) {
18200                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18201                            "Missing settings for moved package " + pkgName);
18202                }
18203
18204                // We moved the entire application as-is, so bring over the
18205                // previously derived ABI information.
18206                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18207                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18208            }
18209
18210        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18211            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18212            scanFlags |= SCAN_NO_DEX;
18213
18214            try {
18215                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18216                    args.abiOverride : pkg.cpuAbiOverride);
18217                final boolean extractNativeLibs = !pkg.isLibrary();
18218                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18219                        extractNativeLibs, mAppLib32InstallDir);
18220            } catch (PackageManagerException pme) {
18221                Slog.e(TAG, "Error deriving application ABI", pme);
18222                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18223                return;
18224            }
18225
18226            // Shared libraries for the package need to be updated.
18227            synchronized (mPackages) {
18228                try {
18229                    updateSharedLibrariesLPr(pkg, null);
18230                } catch (PackageManagerException e) {
18231                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18232                }
18233            }
18234
18235            // dexopt can take some time to complete, so, for instant apps, we skip this
18236            // step during installation. Instead, we'll take extra time the first time the
18237            // instant app starts. It's preferred to do it this way to provide continuous
18238            // progress to the user instead of mysteriously blocking somewhere in the
18239            // middle of running an instant app. The default behaviour can be overridden
18240            // via gservices.
18241            if (!instantApp || Global.getInt(
18242                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18243                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18244                // Do not run PackageDexOptimizer through the local performDexOpt
18245                // method because `pkg` may not be in `mPackages` yet.
18246                //
18247                // Also, don't fail application installs if the dexopt step fails.
18248                DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18249                        REASON_INSTALL,
18250                        DexoptOptions.DEXOPT_BOOT_COMPLETE);
18251                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18252                        null /* instructionSets */,
18253                        getOrCreateCompilerPackageStats(pkg),
18254                        mDexManager.isUsedByOtherApps(pkg.packageName),
18255                        dexoptOptions);
18256                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18257            }
18258
18259            // Notify BackgroundDexOptService that the package has been changed.
18260            // If this is an update of a package which used to fail to compile,
18261            // BDOS will remove it from its blacklist.
18262            // TODO: Layering violation
18263            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18264        }
18265
18266        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18267            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18268            return;
18269        }
18270
18271        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18272
18273        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18274                "installPackageLI")) {
18275            if (replace) {
18276                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18277                    // Static libs have a synthetic package name containing the version
18278                    // and cannot be updated as an update would get a new package name,
18279                    // unless this is the exact same version code which is useful for
18280                    // development.
18281                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18282                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18283                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18284                                + "static-shared libs cannot be updated");
18285                        return;
18286                    }
18287                }
18288                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18289                        installerPackageName, res, args.installReason);
18290            } else {
18291                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18292                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18293            }
18294        }
18295
18296        synchronized (mPackages) {
18297            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18298            if (ps != null) {
18299                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18300                ps.setUpdateAvailable(false /*updateAvailable*/);
18301            }
18302
18303            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18304            for (int i = 0; i < childCount; i++) {
18305                PackageParser.Package childPkg = pkg.childPackages.get(i);
18306                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18307                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18308                if (childPs != null) {
18309                    childRes.newUsers = childPs.queryInstalledUsers(
18310                            sUserManager.getUserIds(), true);
18311                }
18312            }
18313
18314            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18315                updateSequenceNumberLP(ps, res.newUsers);
18316                updateInstantAppInstallerLocked(pkgName);
18317            }
18318        }
18319    }
18320
18321    private void startIntentFilterVerifications(int userId, boolean replacing,
18322            PackageParser.Package pkg) {
18323        if (mIntentFilterVerifierComponent == null) {
18324            Slog.w(TAG, "No IntentFilter verification will not be done as "
18325                    + "there is no IntentFilterVerifier available!");
18326            return;
18327        }
18328
18329        final int verifierUid = getPackageUid(
18330                mIntentFilterVerifierComponent.getPackageName(),
18331                MATCH_DEBUG_TRIAGED_MISSING,
18332                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18333
18334        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18335        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18336        mHandler.sendMessage(msg);
18337
18338        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18339        for (int i = 0; i < childCount; i++) {
18340            PackageParser.Package childPkg = pkg.childPackages.get(i);
18341            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18342            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18343            mHandler.sendMessage(msg);
18344        }
18345    }
18346
18347    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18348            PackageParser.Package pkg) {
18349        int size = pkg.activities.size();
18350        if (size == 0) {
18351            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18352                    "No activity, so no need to verify any IntentFilter!");
18353            return;
18354        }
18355
18356        final boolean hasDomainURLs = hasDomainURLs(pkg);
18357        if (!hasDomainURLs) {
18358            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18359                    "No domain URLs, so no need to verify any IntentFilter!");
18360            return;
18361        }
18362
18363        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18364                + " if any IntentFilter from the " + size
18365                + " Activities needs verification ...");
18366
18367        int count = 0;
18368        final String packageName = pkg.packageName;
18369
18370        synchronized (mPackages) {
18371            // If this is a new install and we see that we've already run verification for this
18372            // package, we have nothing to do: it means the state was restored from backup.
18373            if (!replacing) {
18374                IntentFilterVerificationInfo ivi =
18375                        mSettings.getIntentFilterVerificationLPr(packageName);
18376                if (ivi != null) {
18377                    if (DEBUG_DOMAIN_VERIFICATION) {
18378                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18379                                + ivi.getStatusString());
18380                    }
18381                    return;
18382                }
18383            }
18384
18385            // If any filters need to be verified, then all need to be.
18386            boolean needToVerify = false;
18387            for (PackageParser.Activity a : pkg.activities) {
18388                for (ActivityIntentInfo filter : a.intents) {
18389                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18390                        if (DEBUG_DOMAIN_VERIFICATION) {
18391                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18392                        }
18393                        needToVerify = true;
18394                        break;
18395                    }
18396                }
18397            }
18398
18399            if (needToVerify) {
18400                final int verificationId = mIntentFilterVerificationToken++;
18401                for (PackageParser.Activity a : pkg.activities) {
18402                    for (ActivityIntentInfo filter : a.intents) {
18403                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18404                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18405                                    "Verification needed for IntentFilter:" + filter.toString());
18406                            mIntentFilterVerifier.addOneIntentFilterVerification(
18407                                    verifierUid, userId, verificationId, filter, packageName);
18408                            count++;
18409                        }
18410                    }
18411                }
18412            }
18413        }
18414
18415        if (count > 0) {
18416            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18417                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18418                    +  " for userId:" + userId);
18419            mIntentFilterVerifier.startVerifications(userId);
18420        } else {
18421            if (DEBUG_DOMAIN_VERIFICATION) {
18422                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18423            }
18424        }
18425    }
18426
18427    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18428        final ComponentName cn  = filter.activity.getComponentName();
18429        final String packageName = cn.getPackageName();
18430
18431        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18432                packageName);
18433        if (ivi == null) {
18434            return true;
18435        }
18436        int status = ivi.getStatus();
18437        switch (status) {
18438            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18439            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18440                return true;
18441
18442            default:
18443                // Nothing to do
18444                return false;
18445        }
18446    }
18447
18448    private static boolean isMultiArch(ApplicationInfo info) {
18449        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18450    }
18451
18452    private static boolean isExternal(PackageParser.Package pkg) {
18453        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18454    }
18455
18456    private static boolean isExternal(PackageSetting ps) {
18457        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18458    }
18459
18460    private static boolean isSystemApp(PackageParser.Package pkg) {
18461        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18462    }
18463
18464    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18465        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18466    }
18467
18468    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18469        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18470    }
18471
18472    private static boolean isSystemApp(PackageSetting ps) {
18473        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18474    }
18475
18476    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18477        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18478    }
18479
18480    private int packageFlagsToInstallFlags(PackageSetting ps) {
18481        int installFlags = 0;
18482        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18483            // This existing package was an external ASEC install when we have
18484            // the external flag without a UUID
18485            installFlags |= PackageManager.INSTALL_EXTERNAL;
18486        }
18487        if (ps.isForwardLocked()) {
18488            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18489        }
18490        return installFlags;
18491    }
18492
18493    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18494        if (isExternal(pkg)) {
18495            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18496                return StorageManager.UUID_PRIMARY_PHYSICAL;
18497            } else {
18498                return pkg.volumeUuid;
18499            }
18500        } else {
18501            return StorageManager.UUID_PRIVATE_INTERNAL;
18502        }
18503    }
18504
18505    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18506        if (isExternal(pkg)) {
18507            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18508                return mSettings.getExternalVersion();
18509            } else {
18510                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18511            }
18512        } else {
18513            return mSettings.getInternalVersion();
18514        }
18515    }
18516
18517    private void deleteTempPackageFiles() {
18518        final FilenameFilter filter = new FilenameFilter() {
18519            public boolean accept(File dir, String name) {
18520                return name.startsWith("vmdl") && name.endsWith(".tmp");
18521            }
18522        };
18523        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18524            file.delete();
18525        }
18526    }
18527
18528    @Override
18529    public void deletePackageAsUser(String packageName, int versionCode,
18530            IPackageDeleteObserver observer, int userId, int flags) {
18531        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18532                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18533    }
18534
18535    @Override
18536    public void deletePackageVersioned(VersionedPackage versionedPackage,
18537            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18538        final int callingUid = Binder.getCallingUid();
18539        mContext.enforceCallingOrSelfPermission(
18540                android.Manifest.permission.DELETE_PACKAGES, null);
18541        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18542        Preconditions.checkNotNull(versionedPackage);
18543        Preconditions.checkNotNull(observer);
18544        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18545                PackageManager.VERSION_CODE_HIGHEST,
18546                Integer.MAX_VALUE, "versionCode must be >= -1");
18547
18548        final String packageName = versionedPackage.getPackageName();
18549        final int versionCode = versionedPackage.getVersionCode();
18550        final String internalPackageName;
18551        synchronized (mPackages) {
18552            // Normalize package name to handle renamed packages and static libs
18553            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18554                    versionedPackage.getVersionCode());
18555        }
18556
18557        final int uid = Binder.getCallingUid();
18558        if (!isOrphaned(internalPackageName)
18559                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18560            try {
18561                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18562                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18563                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18564                observer.onUserActionRequired(intent);
18565            } catch (RemoteException re) {
18566            }
18567            return;
18568        }
18569        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18570        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18571        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18572            mContext.enforceCallingOrSelfPermission(
18573                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18574                    "deletePackage for user " + userId);
18575        }
18576
18577        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18578            try {
18579                observer.onPackageDeleted(packageName,
18580                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18581            } catch (RemoteException re) {
18582            }
18583            return;
18584        }
18585
18586        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18587            try {
18588                observer.onPackageDeleted(packageName,
18589                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18590            } catch (RemoteException re) {
18591            }
18592            return;
18593        }
18594
18595        if (DEBUG_REMOVE) {
18596            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18597                    + " deleteAllUsers: " + deleteAllUsers + " version="
18598                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18599                    ? "VERSION_CODE_HIGHEST" : versionCode));
18600        }
18601        // Queue up an async operation since the package deletion may take a little while.
18602        mHandler.post(new Runnable() {
18603            public void run() {
18604                mHandler.removeCallbacks(this);
18605                int returnCode;
18606                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18607                boolean doDeletePackage = true;
18608                if (ps != null) {
18609                    final boolean targetIsInstantApp =
18610                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18611                    doDeletePackage = !targetIsInstantApp
18612                            || canViewInstantApps;
18613                }
18614                if (doDeletePackage) {
18615                    if (!deleteAllUsers) {
18616                        returnCode = deletePackageX(internalPackageName, versionCode,
18617                                userId, deleteFlags);
18618                    } else {
18619                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18620                                internalPackageName, users);
18621                        // If nobody is blocking uninstall, proceed with delete for all users
18622                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18623                            returnCode = deletePackageX(internalPackageName, versionCode,
18624                                    userId, deleteFlags);
18625                        } else {
18626                            // Otherwise uninstall individually for users with blockUninstalls=false
18627                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18628                            for (int userId : users) {
18629                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18630                                    returnCode = deletePackageX(internalPackageName, versionCode,
18631                                            userId, userFlags);
18632                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18633                                        Slog.w(TAG, "Package delete failed for user " + userId
18634                                                + ", returnCode " + returnCode);
18635                                    }
18636                                }
18637                            }
18638                            // The app has only been marked uninstalled for certain users.
18639                            // We still need to report that delete was blocked
18640                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18641                        }
18642                    }
18643                } else {
18644                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18645                }
18646                try {
18647                    observer.onPackageDeleted(packageName, returnCode, null);
18648                } catch (RemoteException e) {
18649                    Log.i(TAG, "Observer no longer exists.");
18650                } //end catch
18651            } //end run
18652        });
18653    }
18654
18655    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18656        if (pkg.staticSharedLibName != null) {
18657            return pkg.manifestPackageName;
18658        }
18659        return pkg.packageName;
18660    }
18661
18662    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18663        // Handle renamed packages
18664        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18665        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18666
18667        // Is this a static library?
18668        SparseArray<SharedLibraryEntry> versionedLib =
18669                mStaticLibsByDeclaringPackage.get(packageName);
18670        if (versionedLib == null || versionedLib.size() <= 0) {
18671            return packageName;
18672        }
18673
18674        // Figure out which lib versions the caller can see
18675        SparseIntArray versionsCallerCanSee = null;
18676        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18677        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18678                && callingAppId != Process.ROOT_UID) {
18679            versionsCallerCanSee = new SparseIntArray();
18680            String libName = versionedLib.valueAt(0).info.getName();
18681            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18682            if (uidPackages != null) {
18683                for (String uidPackage : uidPackages) {
18684                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18685                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18686                    if (libIdx >= 0) {
18687                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18688                        versionsCallerCanSee.append(libVersion, libVersion);
18689                    }
18690                }
18691            }
18692        }
18693
18694        // Caller can see nothing - done
18695        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18696            return packageName;
18697        }
18698
18699        // Find the version the caller can see and the app version code
18700        SharedLibraryEntry highestVersion = null;
18701        final int versionCount = versionedLib.size();
18702        for (int i = 0; i < versionCount; i++) {
18703            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18704            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18705                    libEntry.info.getVersion()) < 0) {
18706                continue;
18707            }
18708            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18709            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18710                if (libVersionCode == versionCode) {
18711                    return libEntry.apk;
18712                }
18713            } else if (highestVersion == null) {
18714                highestVersion = libEntry;
18715            } else if (libVersionCode  > highestVersion.info
18716                    .getDeclaringPackage().getVersionCode()) {
18717                highestVersion = libEntry;
18718            }
18719        }
18720
18721        if (highestVersion != null) {
18722            return highestVersion.apk;
18723        }
18724
18725        return packageName;
18726    }
18727
18728    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18729        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18730              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18731            return true;
18732        }
18733        final int callingUserId = UserHandle.getUserId(callingUid);
18734        // If the caller installed the pkgName, then allow it to silently uninstall.
18735        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18736            return true;
18737        }
18738
18739        // Allow package verifier to silently uninstall.
18740        if (mRequiredVerifierPackage != null &&
18741                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18742            return true;
18743        }
18744
18745        // Allow package uninstaller to silently uninstall.
18746        if (mRequiredUninstallerPackage != null &&
18747                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18748            return true;
18749        }
18750
18751        // Allow storage manager to silently uninstall.
18752        if (mStorageManagerPackage != null &&
18753                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18754            return true;
18755        }
18756
18757        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18758        // uninstall for device owner provisioning.
18759        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18760                == PERMISSION_GRANTED) {
18761            return true;
18762        }
18763
18764        return false;
18765    }
18766
18767    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18768        int[] result = EMPTY_INT_ARRAY;
18769        for (int userId : userIds) {
18770            if (getBlockUninstallForUser(packageName, userId)) {
18771                result = ArrayUtils.appendInt(result, userId);
18772            }
18773        }
18774        return result;
18775    }
18776
18777    @Override
18778    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18779        final int callingUid = Binder.getCallingUid();
18780        if (getInstantAppPackageName(callingUid) != null
18781                && !isCallerSameApp(packageName, callingUid)) {
18782            return false;
18783        }
18784        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18785    }
18786
18787    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18788        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18789                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18790        try {
18791            if (dpm != null) {
18792                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18793                        /* callingUserOnly =*/ false);
18794                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18795                        : deviceOwnerComponentName.getPackageName();
18796                // Does the package contains the device owner?
18797                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18798                // this check is probably not needed, since DO should be registered as a device
18799                // admin on some user too. (Original bug for this: b/17657954)
18800                if (packageName.equals(deviceOwnerPackageName)) {
18801                    return true;
18802                }
18803                // Does it contain a device admin for any user?
18804                int[] users;
18805                if (userId == UserHandle.USER_ALL) {
18806                    users = sUserManager.getUserIds();
18807                } else {
18808                    users = new int[]{userId};
18809                }
18810                for (int i = 0; i < users.length; ++i) {
18811                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18812                        return true;
18813                    }
18814                }
18815            }
18816        } catch (RemoteException e) {
18817        }
18818        return false;
18819    }
18820
18821    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18822        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18823    }
18824
18825    /**
18826     *  This method is an internal method that could be get invoked either
18827     *  to delete an installed package or to clean up a failed installation.
18828     *  After deleting an installed package, a broadcast is sent to notify any
18829     *  listeners that the package has been removed. For cleaning up a failed
18830     *  installation, the broadcast is not necessary since the package's
18831     *  installation wouldn't have sent the initial broadcast either
18832     *  The key steps in deleting a package are
18833     *  deleting the package information in internal structures like mPackages,
18834     *  deleting the packages base directories through installd
18835     *  updating mSettings to reflect current status
18836     *  persisting settings for later use
18837     *  sending a broadcast if necessary
18838     */
18839    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18840        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18841        final boolean res;
18842
18843        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18844                ? UserHandle.USER_ALL : userId;
18845
18846        if (isPackageDeviceAdmin(packageName, removeUser)) {
18847            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18848            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18849        }
18850
18851        PackageSetting uninstalledPs = null;
18852        PackageParser.Package pkg = null;
18853
18854        // for the uninstall-updates case and restricted profiles, remember the per-
18855        // user handle installed state
18856        int[] allUsers;
18857        synchronized (mPackages) {
18858            uninstalledPs = mSettings.mPackages.get(packageName);
18859            if (uninstalledPs == null) {
18860                Slog.w(TAG, "Not removing non-existent package " + packageName);
18861                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18862            }
18863
18864            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18865                    && uninstalledPs.versionCode != versionCode) {
18866                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18867                        + uninstalledPs.versionCode + " != " + versionCode);
18868                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18869            }
18870
18871            // Static shared libs can be declared by any package, so let us not
18872            // allow removing a package if it provides a lib others depend on.
18873            pkg = mPackages.get(packageName);
18874
18875            allUsers = sUserManager.getUserIds();
18876
18877            if (pkg != null && pkg.staticSharedLibName != null) {
18878                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18879                        pkg.staticSharedLibVersion);
18880                if (libEntry != null) {
18881                    for (int currUserId : allUsers) {
18882                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18883                            continue;
18884                        }
18885                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18886                                libEntry.info, 0, currUserId);
18887                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18888                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18889                                    + " hosting lib " + libEntry.info.getName() + " version "
18890                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18891                                    + " for user " + currUserId);
18892                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18893                        }
18894                    }
18895                }
18896            }
18897
18898            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18899        }
18900
18901        final int freezeUser;
18902        if (isUpdatedSystemApp(uninstalledPs)
18903                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18904            // We're downgrading a system app, which will apply to all users, so
18905            // freeze them all during the downgrade
18906            freezeUser = UserHandle.USER_ALL;
18907        } else {
18908            freezeUser = removeUser;
18909        }
18910
18911        synchronized (mInstallLock) {
18912            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18913            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18914                    deleteFlags, "deletePackageX")) {
18915                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18916                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18917            }
18918            synchronized (mPackages) {
18919                if (res) {
18920                    if (pkg != null) {
18921                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18922                    }
18923                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18924                    updateInstantAppInstallerLocked(packageName);
18925                }
18926            }
18927        }
18928
18929        if (res) {
18930            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18931            info.sendPackageRemovedBroadcasts(killApp);
18932            info.sendSystemPackageUpdatedBroadcasts();
18933            info.sendSystemPackageAppearedBroadcasts();
18934        }
18935        // Force a gc here.
18936        Runtime.getRuntime().gc();
18937        // Delete the resources here after sending the broadcast to let
18938        // other processes clean up before deleting resources.
18939        if (info.args != null) {
18940            synchronized (mInstallLock) {
18941                info.args.doPostDeleteLI(true);
18942            }
18943        }
18944
18945        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18946    }
18947
18948    static class PackageRemovedInfo {
18949        final PackageSender packageSender;
18950        String removedPackage;
18951        String installerPackageName;
18952        int uid = -1;
18953        int removedAppId = -1;
18954        int[] origUsers;
18955        int[] removedUsers = null;
18956        int[] broadcastUsers = null;
18957        SparseArray<Integer> installReasons;
18958        boolean isRemovedPackageSystemUpdate = false;
18959        boolean isUpdate;
18960        boolean dataRemoved;
18961        boolean removedForAllUsers;
18962        boolean isStaticSharedLib;
18963        // Clean up resources deleted packages.
18964        InstallArgs args = null;
18965        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18966        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18967
18968        PackageRemovedInfo(PackageSender packageSender) {
18969            this.packageSender = packageSender;
18970        }
18971
18972        void sendPackageRemovedBroadcasts(boolean killApp) {
18973            sendPackageRemovedBroadcastInternal(killApp);
18974            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18975            for (int i = 0; i < childCount; i++) {
18976                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18977                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18978            }
18979        }
18980
18981        void sendSystemPackageUpdatedBroadcasts() {
18982            if (isRemovedPackageSystemUpdate) {
18983                sendSystemPackageUpdatedBroadcastsInternal();
18984                final int childCount = (removedChildPackages != null)
18985                        ? removedChildPackages.size() : 0;
18986                for (int i = 0; i < childCount; i++) {
18987                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18988                    if (childInfo.isRemovedPackageSystemUpdate) {
18989                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18990                    }
18991                }
18992            }
18993        }
18994
18995        void sendSystemPackageAppearedBroadcasts() {
18996            final int packageCount = (appearedChildPackages != null)
18997                    ? appearedChildPackages.size() : 0;
18998            for (int i = 0; i < packageCount; i++) {
18999                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19000                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19001                    true, UserHandle.getAppId(installedInfo.uid),
19002                    installedInfo.newUsers);
19003            }
19004        }
19005
19006        private void sendSystemPackageUpdatedBroadcastsInternal() {
19007            Bundle extras = new Bundle(2);
19008            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19009            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19010            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19011                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19012            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19013                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19014            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19015                null, null, 0, removedPackage, null, null);
19016            if (installerPackageName != null) {
19017                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19018                        removedPackage, extras, 0 /*flags*/,
19019                        installerPackageName, null, null);
19020                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19021                        removedPackage, extras, 0 /*flags*/,
19022                        installerPackageName, null, null);
19023            }
19024        }
19025
19026        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19027            // Don't send static shared library removal broadcasts as these
19028            // libs are visible only the the apps that depend on them an one
19029            // cannot remove the library if it has a dependency.
19030            if (isStaticSharedLib) {
19031                return;
19032            }
19033            Bundle extras = new Bundle(2);
19034            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19035            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19036            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19037            if (isUpdate || isRemovedPackageSystemUpdate) {
19038                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19039            }
19040            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19041            if (removedPackage != null) {
19042                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19043                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19044                if (installerPackageName != null) {
19045                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19046                            removedPackage, extras, 0 /*flags*/,
19047                            installerPackageName, null, broadcastUsers);
19048                }
19049                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19050                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19051                        removedPackage, extras,
19052                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19053                        null, null, broadcastUsers);
19054                }
19055            }
19056            if (removedAppId >= 0) {
19057                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19058                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19059                    null, null, broadcastUsers);
19060            }
19061        }
19062
19063        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19064            removedUsers = userIds;
19065            if (removedUsers == null) {
19066                broadcastUsers = null;
19067                return;
19068            }
19069
19070            broadcastUsers = EMPTY_INT_ARRAY;
19071            for (int i = userIds.length - 1; i >= 0; --i) {
19072                final int userId = userIds[i];
19073                if (deletedPackageSetting.getInstantApp(userId)) {
19074                    continue;
19075                }
19076                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19077            }
19078        }
19079    }
19080
19081    /*
19082     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19083     * flag is not set, the data directory is removed as well.
19084     * make sure this flag is set for partially installed apps. If not its meaningless to
19085     * delete a partially installed application.
19086     */
19087    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19088            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19089        String packageName = ps.name;
19090        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19091        // Retrieve object to delete permissions for shared user later on
19092        final PackageParser.Package deletedPkg;
19093        final PackageSetting deletedPs;
19094        // reader
19095        synchronized (mPackages) {
19096            deletedPkg = mPackages.get(packageName);
19097            deletedPs = mSettings.mPackages.get(packageName);
19098            if (outInfo != null) {
19099                outInfo.removedPackage = packageName;
19100                outInfo.installerPackageName = ps.installerPackageName;
19101                outInfo.isStaticSharedLib = deletedPkg != null
19102                        && deletedPkg.staticSharedLibName != null;
19103                outInfo.populateUsers(deletedPs == null ? null
19104                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19105            }
19106        }
19107
19108        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19109
19110        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19111            final PackageParser.Package resolvedPkg;
19112            if (deletedPkg != null) {
19113                resolvedPkg = deletedPkg;
19114            } else {
19115                // We don't have a parsed package when it lives on an ejected
19116                // adopted storage device, so fake something together
19117                resolvedPkg = new PackageParser.Package(ps.name);
19118                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19119            }
19120            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19121                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19122            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19123            if (outInfo != null) {
19124                outInfo.dataRemoved = true;
19125            }
19126            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19127        }
19128
19129        int removedAppId = -1;
19130
19131        // writer
19132        synchronized (mPackages) {
19133            boolean installedStateChanged = false;
19134            if (deletedPs != null) {
19135                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19136                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19137                    clearDefaultBrowserIfNeeded(packageName);
19138                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19139                    removedAppId = mSettings.removePackageLPw(packageName);
19140                    if (outInfo != null) {
19141                        outInfo.removedAppId = removedAppId;
19142                    }
19143                    updatePermissionsLPw(deletedPs.name, null, 0);
19144                    if (deletedPs.sharedUser != null) {
19145                        // Remove permissions associated with package. Since runtime
19146                        // permissions are per user we have to kill the removed package
19147                        // or packages running under the shared user of the removed
19148                        // package if revoking the permissions requested only by the removed
19149                        // package is successful and this causes a change in gids.
19150                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19151                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19152                                    userId);
19153                            if (userIdToKill == UserHandle.USER_ALL
19154                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19155                                // If gids changed for this user, kill all affected packages.
19156                                mHandler.post(new Runnable() {
19157                                    @Override
19158                                    public void run() {
19159                                        // This has to happen with no lock held.
19160                                        killApplication(deletedPs.name, deletedPs.appId,
19161                                                KILL_APP_REASON_GIDS_CHANGED);
19162                                    }
19163                                });
19164                                break;
19165                            }
19166                        }
19167                    }
19168                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19169                }
19170                // make sure to preserve per-user disabled state if this removal was just
19171                // a downgrade of a system app to the factory package
19172                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19173                    if (DEBUG_REMOVE) {
19174                        Slog.d(TAG, "Propagating install state across downgrade");
19175                    }
19176                    for (int userId : allUserHandles) {
19177                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19178                        if (DEBUG_REMOVE) {
19179                            Slog.d(TAG, "    user " + userId + " => " + installed);
19180                        }
19181                        if (installed != ps.getInstalled(userId)) {
19182                            installedStateChanged = true;
19183                        }
19184                        ps.setInstalled(installed, userId);
19185                    }
19186                }
19187            }
19188            // can downgrade to reader
19189            if (writeSettings) {
19190                // Save settings now
19191                mSettings.writeLPr();
19192            }
19193            if (installedStateChanged) {
19194                mSettings.writeKernelMappingLPr(ps);
19195            }
19196        }
19197        if (removedAppId != -1) {
19198            // A user ID was deleted here. Go through all users and remove it
19199            // from KeyStore.
19200            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19201        }
19202    }
19203
19204    static boolean locationIsPrivileged(File path) {
19205        try {
19206            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19207                    .getCanonicalPath();
19208            return path.getCanonicalPath().startsWith(privilegedAppDir);
19209        } catch (IOException e) {
19210            Slog.e(TAG, "Unable to access code path " + path);
19211        }
19212        return false;
19213    }
19214
19215    /*
19216     * Tries to delete system package.
19217     */
19218    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19219            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19220            boolean writeSettings) {
19221        if (deletedPs.parentPackageName != null) {
19222            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19223            return false;
19224        }
19225
19226        final boolean applyUserRestrictions
19227                = (allUserHandles != null) && (outInfo.origUsers != null);
19228        final PackageSetting disabledPs;
19229        // Confirm if the system package has been updated
19230        // An updated system app can be deleted. This will also have to restore
19231        // the system pkg from system partition
19232        // reader
19233        synchronized (mPackages) {
19234            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19235        }
19236
19237        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19238                + " disabledPs=" + disabledPs);
19239
19240        if (disabledPs == null) {
19241            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19242            return false;
19243        } else if (DEBUG_REMOVE) {
19244            Slog.d(TAG, "Deleting system pkg from data partition");
19245        }
19246
19247        if (DEBUG_REMOVE) {
19248            if (applyUserRestrictions) {
19249                Slog.d(TAG, "Remembering install states:");
19250                for (int userId : allUserHandles) {
19251                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19252                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19253                }
19254            }
19255        }
19256
19257        // Delete the updated package
19258        outInfo.isRemovedPackageSystemUpdate = true;
19259        if (outInfo.removedChildPackages != null) {
19260            final int childCount = (deletedPs.childPackageNames != null)
19261                    ? deletedPs.childPackageNames.size() : 0;
19262            for (int i = 0; i < childCount; i++) {
19263                String childPackageName = deletedPs.childPackageNames.get(i);
19264                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19265                        .contains(childPackageName)) {
19266                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19267                            childPackageName);
19268                    if (childInfo != null) {
19269                        childInfo.isRemovedPackageSystemUpdate = true;
19270                    }
19271                }
19272            }
19273        }
19274
19275        if (disabledPs.versionCode < deletedPs.versionCode) {
19276            // Delete data for downgrades
19277            flags &= ~PackageManager.DELETE_KEEP_DATA;
19278        } else {
19279            // Preserve data by setting flag
19280            flags |= PackageManager.DELETE_KEEP_DATA;
19281        }
19282
19283        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19284                outInfo, writeSettings, disabledPs.pkg);
19285        if (!ret) {
19286            return false;
19287        }
19288
19289        // writer
19290        synchronized (mPackages) {
19291            // Reinstate the old system package
19292            enableSystemPackageLPw(disabledPs.pkg);
19293            // Remove any native libraries from the upgraded package.
19294            removeNativeBinariesLI(deletedPs);
19295        }
19296
19297        // Install the system package
19298        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19299        int parseFlags = mDefParseFlags
19300                | PackageParser.PARSE_MUST_BE_APK
19301                | PackageParser.PARSE_IS_SYSTEM
19302                | PackageParser.PARSE_IS_SYSTEM_DIR;
19303        if (locationIsPrivileged(disabledPs.codePath)) {
19304            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19305        }
19306
19307        final PackageParser.Package newPkg;
19308        try {
19309            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19310                0 /* currentTime */, null);
19311        } catch (PackageManagerException e) {
19312            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19313                    + e.getMessage());
19314            return false;
19315        }
19316
19317        try {
19318            // update shared libraries for the newly re-installed system package
19319            updateSharedLibrariesLPr(newPkg, null);
19320        } catch (PackageManagerException e) {
19321            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19322        }
19323
19324        prepareAppDataAfterInstallLIF(newPkg);
19325
19326        // writer
19327        synchronized (mPackages) {
19328            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19329
19330            // Propagate the permissions state as we do not want to drop on the floor
19331            // runtime permissions. The update permissions method below will take
19332            // care of removing obsolete permissions and grant install permissions.
19333            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19334            updatePermissionsLPw(newPkg.packageName, newPkg,
19335                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19336
19337            if (applyUserRestrictions) {
19338                boolean installedStateChanged = false;
19339                if (DEBUG_REMOVE) {
19340                    Slog.d(TAG, "Propagating install state across reinstall");
19341                }
19342                for (int userId : allUserHandles) {
19343                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19344                    if (DEBUG_REMOVE) {
19345                        Slog.d(TAG, "    user " + userId + " => " + installed);
19346                    }
19347                    if (installed != ps.getInstalled(userId)) {
19348                        installedStateChanged = true;
19349                    }
19350                    ps.setInstalled(installed, userId);
19351
19352                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19353                }
19354                // Regardless of writeSettings we need to ensure that this restriction
19355                // state propagation is persisted
19356                mSettings.writeAllUsersPackageRestrictionsLPr();
19357                if (installedStateChanged) {
19358                    mSettings.writeKernelMappingLPr(ps);
19359                }
19360            }
19361            // can downgrade to reader here
19362            if (writeSettings) {
19363                mSettings.writeLPr();
19364            }
19365        }
19366        return true;
19367    }
19368
19369    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19370            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19371            PackageRemovedInfo outInfo, boolean writeSettings,
19372            PackageParser.Package replacingPackage) {
19373        synchronized (mPackages) {
19374            if (outInfo != null) {
19375                outInfo.uid = ps.appId;
19376            }
19377
19378            if (outInfo != null && outInfo.removedChildPackages != null) {
19379                final int childCount = (ps.childPackageNames != null)
19380                        ? ps.childPackageNames.size() : 0;
19381                for (int i = 0; i < childCount; i++) {
19382                    String childPackageName = ps.childPackageNames.get(i);
19383                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19384                    if (childPs == null) {
19385                        return false;
19386                    }
19387                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19388                            childPackageName);
19389                    if (childInfo != null) {
19390                        childInfo.uid = childPs.appId;
19391                    }
19392                }
19393            }
19394        }
19395
19396        // Delete package data from internal structures and also remove data if flag is set
19397        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19398
19399        // Delete the child packages data
19400        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19401        for (int i = 0; i < childCount; i++) {
19402            PackageSetting childPs;
19403            synchronized (mPackages) {
19404                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19405            }
19406            if (childPs != null) {
19407                PackageRemovedInfo childOutInfo = (outInfo != null
19408                        && outInfo.removedChildPackages != null)
19409                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19410                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19411                        && (replacingPackage != null
19412                        && !replacingPackage.hasChildPackage(childPs.name))
19413                        ? flags & ~DELETE_KEEP_DATA : flags;
19414                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19415                        deleteFlags, writeSettings);
19416            }
19417        }
19418
19419        // Delete application code and resources only for parent packages
19420        if (ps.parentPackageName == null) {
19421            if (deleteCodeAndResources && (outInfo != null)) {
19422                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19423                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19424                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19425            }
19426        }
19427
19428        return true;
19429    }
19430
19431    @Override
19432    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19433            int userId) {
19434        mContext.enforceCallingOrSelfPermission(
19435                android.Manifest.permission.DELETE_PACKAGES, null);
19436        synchronized (mPackages) {
19437            // Cannot block uninstall of static shared libs as they are
19438            // considered a part of the using app (emulating static linking).
19439            // Also static libs are installed always on internal storage.
19440            PackageParser.Package pkg = mPackages.get(packageName);
19441            if (pkg != null && pkg.staticSharedLibName != null) {
19442                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19443                        + " providing static shared library: " + pkg.staticSharedLibName);
19444                return false;
19445            }
19446            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19447            mSettings.writePackageRestrictionsLPr(userId);
19448        }
19449        return true;
19450    }
19451
19452    @Override
19453    public boolean getBlockUninstallForUser(String packageName, int userId) {
19454        synchronized (mPackages) {
19455            final PackageSetting ps = mSettings.mPackages.get(packageName);
19456            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19457                return false;
19458            }
19459            return mSettings.getBlockUninstallLPr(userId, packageName);
19460        }
19461    }
19462
19463    @Override
19464    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19465        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19466        synchronized (mPackages) {
19467            PackageSetting ps = mSettings.mPackages.get(packageName);
19468            if (ps == null) {
19469                Log.w(TAG, "Package doesn't exist: " + packageName);
19470                return false;
19471            }
19472            if (systemUserApp) {
19473                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19474            } else {
19475                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19476            }
19477            mSettings.writeLPr();
19478        }
19479        return true;
19480    }
19481
19482    /*
19483     * This method handles package deletion in general
19484     */
19485    private boolean deletePackageLIF(String packageName, UserHandle user,
19486            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19487            PackageRemovedInfo outInfo, boolean writeSettings,
19488            PackageParser.Package replacingPackage) {
19489        if (packageName == null) {
19490            Slog.w(TAG, "Attempt to delete null packageName.");
19491            return false;
19492        }
19493
19494        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19495
19496        PackageSetting ps;
19497        synchronized (mPackages) {
19498            ps = mSettings.mPackages.get(packageName);
19499            if (ps == null) {
19500                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19501                return false;
19502            }
19503
19504            if (ps.parentPackageName != null && (!isSystemApp(ps)
19505                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19506                if (DEBUG_REMOVE) {
19507                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19508                            + ((user == null) ? UserHandle.USER_ALL : user));
19509                }
19510                final int removedUserId = (user != null) ? user.getIdentifier()
19511                        : UserHandle.USER_ALL;
19512                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19513                    return false;
19514                }
19515                markPackageUninstalledForUserLPw(ps, user);
19516                scheduleWritePackageRestrictionsLocked(user);
19517                return true;
19518            }
19519        }
19520
19521        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19522                && user.getIdentifier() != UserHandle.USER_ALL)) {
19523            // The caller is asking that the package only be deleted for a single
19524            // user.  To do this, we just mark its uninstalled state and delete
19525            // its data. If this is a system app, we only allow this to happen if
19526            // they have set the special DELETE_SYSTEM_APP which requests different
19527            // semantics than normal for uninstalling system apps.
19528            markPackageUninstalledForUserLPw(ps, user);
19529
19530            if (!isSystemApp(ps)) {
19531                // Do not uninstall the APK if an app should be cached
19532                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19533                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19534                    // Other user still have this package installed, so all
19535                    // we need to do is clear this user's data and save that
19536                    // it is uninstalled.
19537                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19538                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19539                        return false;
19540                    }
19541                    scheduleWritePackageRestrictionsLocked(user);
19542                    return true;
19543                } else {
19544                    // We need to set it back to 'installed' so the uninstall
19545                    // broadcasts will be sent correctly.
19546                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19547                    ps.setInstalled(true, user.getIdentifier());
19548                    mSettings.writeKernelMappingLPr(ps);
19549                }
19550            } else {
19551                // This is a system app, so we assume that the
19552                // other users still have this package installed, so all
19553                // we need to do is clear this user's data and save that
19554                // it is uninstalled.
19555                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19556                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19557                    return false;
19558                }
19559                scheduleWritePackageRestrictionsLocked(user);
19560                return true;
19561            }
19562        }
19563
19564        // If we are deleting a composite package for all users, keep track
19565        // of result for each child.
19566        if (ps.childPackageNames != null && outInfo != null) {
19567            synchronized (mPackages) {
19568                final int childCount = ps.childPackageNames.size();
19569                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19570                for (int i = 0; i < childCount; i++) {
19571                    String childPackageName = ps.childPackageNames.get(i);
19572                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19573                    childInfo.removedPackage = childPackageName;
19574                    childInfo.installerPackageName = ps.installerPackageName;
19575                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19576                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19577                    if (childPs != null) {
19578                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19579                    }
19580                }
19581            }
19582        }
19583
19584        boolean ret = false;
19585        if (isSystemApp(ps)) {
19586            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19587            // When an updated system application is deleted we delete the existing resources
19588            // as well and fall back to existing code in system partition
19589            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19590        } else {
19591            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19592            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19593                    outInfo, writeSettings, replacingPackage);
19594        }
19595
19596        // Take a note whether we deleted the package for all users
19597        if (outInfo != null) {
19598            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19599            if (outInfo.removedChildPackages != null) {
19600                synchronized (mPackages) {
19601                    final int childCount = outInfo.removedChildPackages.size();
19602                    for (int i = 0; i < childCount; i++) {
19603                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19604                        if (childInfo != null) {
19605                            childInfo.removedForAllUsers = mPackages.get(
19606                                    childInfo.removedPackage) == null;
19607                        }
19608                    }
19609                }
19610            }
19611            // If we uninstalled an update to a system app there may be some
19612            // child packages that appeared as they are declared in the system
19613            // app but were not declared in the update.
19614            if (isSystemApp(ps)) {
19615                synchronized (mPackages) {
19616                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19617                    final int childCount = (updatedPs.childPackageNames != null)
19618                            ? updatedPs.childPackageNames.size() : 0;
19619                    for (int i = 0; i < childCount; i++) {
19620                        String childPackageName = updatedPs.childPackageNames.get(i);
19621                        if (outInfo.removedChildPackages == null
19622                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19623                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19624                            if (childPs == null) {
19625                                continue;
19626                            }
19627                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19628                            installRes.name = childPackageName;
19629                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19630                            installRes.pkg = mPackages.get(childPackageName);
19631                            installRes.uid = childPs.pkg.applicationInfo.uid;
19632                            if (outInfo.appearedChildPackages == null) {
19633                                outInfo.appearedChildPackages = new ArrayMap<>();
19634                            }
19635                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19636                        }
19637                    }
19638                }
19639            }
19640        }
19641
19642        return ret;
19643    }
19644
19645    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19646        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19647                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19648        for (int nextUserId : userIds) {
19649            if (DEBUG_REMOVE) {
19650                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19651            }
19652            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19653                    false /*installed*/,
19654                    true /*stopped*/,
19655                    true /*notLaunched*/,
19656                    false /*hidden*/,
19657                    false /*suspended*/,
19658                    false /*instantApp*/,
19659                    null /*lastDisableAppCaller*/,
19660                    null /*enabledComponents*/,
19661                    null /*disabledComponents*/,
19662                    ps.readUserState(nextUserId).domainVerificationStatus,
19663                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19664        }
19665        mSettings.writeKernelMappingLPr(ps);
19666    }
19667
19668    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19669            PackageRemovedInfo outInfo) {
19670        final PackageParser.Package pkg;
19671        synchronized (mPackages) {
19672            pkg = mPackages.get(ps.name);
19673        }
19674
19675        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19676                : new int[] {userId};
19677        for (int nextUserId : userIds) {
19678            if (DEBUG_REMOVE) {
19679                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19680                        + nextUserId);
19681            }
19682
19683            destroyAppDataLIF(pkg, userId,
19684                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19685            destroyAppProfilesLIF(pkg, userId);
19686            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19687            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19688            schedulePackageCleaning(ps.name, nextUserId, false);
19689            synchronized (mPackages) {
19690                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19691                    scheduleWritePackageRestrictionsLocked(nextUserId);
19692                }
19693                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19694            }
19695        }
19696
19697        if (outInfo != null) {
19698            outInfo.removedPackage = ps.name;
19699            outInfo.installerPackageName = ps.installerPackageName;
19700            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19701            outInfo.removedAppId = ps.appId;
19702            outInfo.removedUsers = userIds;
19703            outInfo.broadcastUsers = userIds;
19704        }
19705
19706        return true;
19707    }
19708
19709    private final class ClearStorageConnection implements ServiceConnection {
19710        IMediaContainerService mContainerService;
19711
19712        @Override
19713        public void onServiceConnected(ComponentName name, IBinder service) {
19714            synchronized (this) {
19715                mContainerService = IMediaContainerService.Stub
19716                        .asInterface(Binder.allowBlocking(service));
19717                notifyAll();
19718            }
19719        }
19720
19721        @Override
19722        public void onServiceDisconnected(ComponentName name) {
19723        }
19724    }
19725
19726    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19727        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19728
19729        final boolean mounted;
19730        if (Environment.isExternalStorageEmulated()) {
19731            mounted = true;
19732        } else {
19733            final String status = Environment.getExternalStorageState();
19734
19735            mounted = status.equals(Environment.MEDIA_MOUNTED)
19736                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19737        }
19738
19739        if (!mounted) {
19740            return;
19741        }
19742
19743        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19744        int[] users;
19745        if (userId == UserHandle.USER_ALL) {
19746            users = sUserManager.getUserIds();
19747        } else {
19748            users = new int[] { userId };
19749        }
19750        final ClearStorageConnection conn = new ClearStorageConnection();
19751        if (mContext.bindServiceAsUser(
19752                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19753            try {
19754                for (int curUser : users) {
19755                    long timeout = SystemClock.uptimeMillis() + 5000;
19756                    synchronized (conn) {
19757                        long now;
19758                        while (conn.mContainerService == null &&
19759                                (now = SystemClock.uptimeMillis()) < timeout) {
19760                            try {
19761                                conn.wait(timeout - now);
19762                            } catch (InterruptedException e) {
19763                            }
19764                        }
19765                    }
19766                    if (conn.mContainerService == null) {
19767                        return;
19768                    }
19769
19770                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19771                    clearDirectory(conn.mContainerService,
19772                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19773                    if (allData) {
19774                        clearDirectory(conn.mContainerService,
19775                                userEnv.buildExternalStorageAppDataDirs(packageName));
19776                        clearDirectory(conn.mContainerService,
19777                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19778                    }
19779                }
19780            } finally {
19781                mContext.unbindService(conn);
19782            }
19783        }
19784    }
19785
19786    @Override
19787    public void clearApplicationProfileData(String packageName) {
19788        enforceSystemOrRoot("Only the system can clear all profile data");
19789
19790        final PackageParser.Package pkg;
19791        synchronized (mPackages) {
19792            pkg = mPackages.get(packageName);
19793        }
19794
19795        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19796            synchronized (mInstallLock) {
19797                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19798            }
19799        }
19800    }
19801
19802    @Override
19803    public void clearApplicationUserData(final String packageName,
19804            final IPackageDataObserver observer, final int userId) {
19805        mContext.enforceCallingOrSelfPermission(
19806                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19807
19808        final int callingUid = Binder.getCallingUid();
19809        enforceCrossUserPermission(callingUid, userId,
19810                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19811
19812        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19813        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19814            return;
19815        }
19816        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19817            throw new SecurityException("Cannot clear data for a protected package: "
19818                    + packageName);
19819        }
19820        // Queue up an async operation since the package deletion may take a little while.
19821        mHandler.post(new Runnable() {
19822            public void run() {
19823                mHandler.removeCallbacks(this);
19824                final boolean succeeded;
19825                try (PackageFreezer freezer = freezePackage(packageName,
19826                        "clearApplicationUserData")) {
19827                    synchronized (mInstallLock) {
19828                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19829                    }
19830                    clearExternalStorageDataSync(packageName, userId, true);
19831                    synchronized (mPackages) {
19832                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19833                                packageName, userId);
19834                    }
19835                }
19836                if (succeeded) {
19837                    // invoke DeviceStorageMonitor's update method to clear any notifications
19838                    DeviceStorageMonitorInternal dsm = LocalServices
19839                            .getService(DeviceStorageMonitorInternal.class);
19840                    if (dsm != null) {
19841                        dsm.checkMemory();
19842                    }
19843                }
19844                if(observer != null) {
19845                    try {
19846                        observer.onRemoveCompleted(packageName, succeeded);
19847                    } catch (RemoteException e) {
19848                        Log.i(TAG, "Observer no longer exists.");
19849                    }
19850                } //end if observer
19851            } //end run
19852        });
19853    }
19854
19855    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19856        if (packageName == null) {
19857            Slog.w(TAG, "Attempt to delete null packageName.");
19858            return false;
19859        }
19860
19861        // Try finding details about the requested package
19862        PackageParser.Package pkg;
19863        synchronized (mPackages) {
19864            pkg = mPackages.get(packageName);
19865            if (pkg == null) {
19866                final PackageSetting ps = mSettings.mPackages.get(packageName);
19867                if (ps != null) {
19868                    pkg = ps.pkg;
19869                }
19870            }
19871
19872            if (pkg == null) {
19873                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19874                return false;
19875            }
19876
19877            PackageSetting ps = (PackageSetting) pkg.mExtras;
19878            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19879        }
19880
19881        clearAppDataLIF(pkg, userId,
19882                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19883
19884        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19885        removeKeystoreDataIfNeeded(userId, appId);
19886
19887        UserManagerInternal umInternal = getUserManagerInternal();
19888        final int flags;
19889        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19890            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19891        } else if (umInternal.isUserRunning(userId)) {
19892            flags = StorageManager.FLAG_STORAGE_DE;
19893        } else {
19894            flags = 0;
19895        }
19896        prepareAppDataContentsLIF(pkg, userId, flags);
19897
19898        return true;
19899    }
19900
19901    /**
19902     * Reverts user permission state changes (permissions and flags) in
19903     * all packages for a given user.
19904     *
19905     * @param userId The device user for which to do a reset.
19906     */
19907    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19908        final int packageCount = mPackages.size();
19909        for (int i = 0; i < packageCount; i++) {
19910            PackageParser.Package pkg = mPackages.valueAt(i);
19911            PackageSetting ps = (PackageSetting) pkg.mExtras;
19912            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19913        }
19914    }
19915
19916    private void resetNetworkPolicies(int userId) {
19917        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19918    }
19919
19920    /**
19921     * Reverts user permission state changes (permissions and flags).
19922     *
19923     * @param ps The package for which to reset.
19924     * @param userId The device user for which to do a reset.
19925     */
19926    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19927            final PackageSetting ps, final int userId) {
19928        if (ps.pkg == null) {
19929            return;
19930        }
19931
19932        // These are flags that can change base on user actions.
19933        final int userSettableMask = FLAG_PERMISSION_USER_SET
19934                | FLAG_PERMISSION_USER_FIXED
19935                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19936                | FLAG_PERMISSION_REVIEW_REQUIRED;
19937
19938        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19939                | FLAG_PERMISSION_POLICY_FIXED;
19940
19941        boolean writeInstallPermissions = false;
19942        boolean writeRuntimePermissions = false;
19943
19944        final int permissionCount = ps.pkg.requestedPermissions.size();
19945        for (int i = 0; i < permissionCount; i++) {
19946            String permission = ps.pkg.requestedPermissions.get(i);
19947
19948            BasePermission bp = mSettings.mPermissions.get(permission);
19949            if (bp == null) {
19950                continue;
19951            }
19952
19953            // If shared user we just reset the state to which only this app contributed.
19954            if (ps.sharedUser != null) {
19955                boolean used = false;
19956                final int packageCount = ps.sharedUser.packages.size();
19957                for (int j = 0; j < packageCount; j++) {
19958                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19959                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19960                            && pkg.pkg.requestedPermissions.contains(permission)) {
19961                        used = true;
19962                        break;
19963                    }
19964                }
19965                if (used) {
19966                    continue;
19967                }
19968            }
19969
19970            PermissionsState permissionsState = ps.getPermissionsState();
19971
19972            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19973
19974            // Always clear the user settable flags.
19975            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19976                    bp.name) != null;
19977            // If permission review is enabled and this is a legacy app, mark the
19978            // permission as requiring a review as this is the initial state.
19979            int flags = 0;
19980            if (mPermissionReviewRequired
19981                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19982                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19983            }
19984            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19985                if (hasInstallState) {
19986                    writeInstallPermissions = true;
19987                } else {
19988                    writeRuntimePermissions = true;
19989                }
19990            }
19991
19992            // Below is only runtime permission handling.
19993            if (!bp.isRuntime()) {
19994                continue;
19995            }
19996
19997            // Never clobber system or policy.
19998            if ((oldFlags & policyOrSystemFlags) != 0) {
19999                continue;
20000            }
20001
20002            // If this permission was granted by default, make sure it is.
20003            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20004                if (permissionsState.grantRuntimePermission(bp, userId)
20005                        != PERMISSION_OPERATION_FAILURE) {
20006                    writeRuntimePermissions = true;
20007                }
20008            // If permission review is enabled the permissions for a legacy apps
20009            // are represented as constantly granted runtime ones, so don't revoke.
20010            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20011                // Otherwise, reset the permission.
20012                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20013                switch (revokeResult) {
20014                    case PERMISSION_OPERATION_SUCCESS:
20015                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20016                        writeRuntimePermissions = true;
20017                        final int appId = ps.appId;
20018                        mHandler.post(new Runnable() {
20019                            @Override
20020                            public void run() {
20021                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20022                            }
20023                        });
20024                    } break;
20025                }
20026            }
20027        }
20028
20029        // Synchronously write as we are taking permissions away.
20030        if (writeRuntimePermissions) {
20031            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20032        }
20033
20034        // Synchronously write as we are taking permissions away.
20035        if (writeInstallPermissions) {
20036            mSettings.writeLPr();
20037        }
20038    }
20039
20040    /**
20041     * Remove entries from the keystore daemon. Will only remove it if the
20042     * {@code appId} is valid.
20043     */
20044    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20045        if (appId < 0) {
20046            return;
20047        }
20048
20049        final KeyStore keyStore = KeyStore.getInstance();
20050        if (keyStore != null) {
20051            if (userId == UserHandle.USER_ALL) {
20052                for (final int individual : sUserManager.getUserIds()) {
20053                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20054                }
20055            } else {
20056                keyStore.clearUid(UserHandle.getUid(userId, appId));
20057            }
20058        } else {
20059            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20060        }
20061    }
20062
20063    @Override
20064    public void deleteApplicationCacheFiles(final String packageName,
20065            final IPackageDataObserver observer) {
20066        final int userId = UserHandle.getCallingUserId();
20067        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20068    }
20069
20070    @Override
20071    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20072            final IPackageDataObserver observer) {
20073        final int callingUid = Binder.getCallingUid();
20074        mContext.enforceCallingOrSelfPermission(
20075                android.Manifest.permission.DELETE_CACHE_FILES, null);
20076        enforceCrossUserPermission(callingUid, userId,
20077                /* requireFullPermission= */ true, /* checkShell= */ false,
20078                "delete application cache files");
20079        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20080                android.Manifest.permission.ACCESS_INSTANT_APPS);
20081
20082        final PackageParser.Package pkg;
20083        synchronized (mPackages) {
20084            pkg = mPackages.get(packageName);
20085        }
20086
20087        // Queue up an async operation since the package deletion may take a little while.
20088        mHandler.post(new Runnable() {
20089            public void run() {
20090                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20091                boolean doClearData = true;
20092                if (ps != null) {
20093                    final boolean targetIsInstantApp =
20094                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20095                    doClearData = !targetIsInstantApp
20096                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20097                }
20098                if (doClearData) {
20099                    synchronized (mInstallLock) {
20100                        final int flags = StorageManager.FLAG_STORAGE_DE
20101                                | StorageManager.FLAG_STORAGE_CE;
20102                        // We're only clearing cache files, so we don't care if the
20103                        // app is unfrozen and still able to run
20104                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20105                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20106                    }
20107                    clearExternalStorageDataSync(packageName, userId, false);
20108                }
20109                if (observer != null) {
20110                    try {
20111                        observer.onRemoveCompleted(packageName, true);
20112                    } catch (RemoteException e) {
20113                        Log.i(TAG, "Observer no longer exists.");
20114                    }
20115                }
20116            }
20117        });
20118    }
20119
20120    @Override
20121    public void getPackageSizeInfo(final String packageName, int userHandle,
20122            final IPackageStatsObserver observer) {
20123        throw new UnsupportedOperationException(
20124                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20125    }
20126
20127    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20128        final PackageSetting ps;
20129        synchronized (mPackages) {
20130            ps = mSettings.mPackages.get(packageName);
20131            if (ps == null) {
20132                Slog.w(TAG, "Failed to find settings for " + packageName);
20133                return false;
20134            }
20135        }
20136
20137        final String[] packageNames = { packageName };
20138        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20139        final String[] codePaths = { ps.codePathString };
20140
20141        try {
20142            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20143                    ps.appId, ceDataInodes, codePaths, stats);
20144
20145            // For now, ignore code size of packages on system partition
20146            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20147                stats.codeSize = 0;
20148            }
20149
20150            // External clients expect these to be tracked separately
20151            stats.dataSize -= stats.cacheSize;
20152
20153        } catch (InstallerException e) {
20154            Slog.w(TAG, String.valueOf(e));
20155            return false;
20156        }
20157
20158        return true;
20159    }
20160
20161    private int getUidTargetSdkVersionLockedLPr(int uid) {
20162        Object obj = mSettings.getUserIdLPr(uid);
20163        if (obj instanceof SharedUserSetting) {
20164            final SharedUserSetting sus = (SharedUserSetting) obj;
20165            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20166            final Iterator<PackageSetting> it = sus.packages.iterator();
20167            while (it.hasNext()) {
20168                final PackageSetting ps = it.next();
20169                if (ps.pkg != null) {
20170                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20171                    if (v < vers) vers = v;
20172                }
20173            }
20174            return vers;
20175        } else if (obj instanceof PackageSetting) {
20176            final PackageSetting ps = (PackageSetting) obj;
20177            if (ps.pkg != null) {
20178                return ps.pkg.applicationInfo.targetSdkVersion;
20179            }
20180        }
20181        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20182    }
20183
20184    @Override
20185    public void addPreferredActivity(IntentFilter filter, int match,
20186            ComponentName[] set, ComponentName activity, int userId) {
20187        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20188                "Adding preferred");
20189    }
20190
20191    private void addPreferredActivityInternal(IntentFilter filter, int match,
20192            ComponentName[] set, ComponentName activity, boolean always, int userId,
20193            String opname) {
20194        // writer
20195        int callingUid = Binder.getCallingUid();
20196        enforceCrossUserPermission(callingUid, userId,
20197                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20198        if (filter.countActions() == 0) {
20199            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20200            return;
20201        }
20202        synchronized (mPackages) {
20203            if (mContext.checkCallingOrSelfPermission(
20204                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20205                    != PackageManager.PERMISSION_GRANTED) {
20206                if (getUidTargetSdkVersionLockedLPr(callingUid)
20207                        < Build.VERSION_CODES.FROYO) {
20208                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20209                            + callingUid);
20210                    return;
20211                }
20212                mContext.enforceCallingOrSelfPermission(
20213                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20214            }
20215
20216            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20217            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20218                    + userId + ":");
20219            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20220            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20221            scheduleWritePackageRestrictionsLocked(userId);
20222            postPreferredActivityChangedBroadcast(userId);
20223        }
20224    }
20225
20226    private void postPreferredActivityChangedBroadcast(int userId) {
20227        mHandler.post(() -> {
20228            final IActivityManager am = ActivityManager.getService();
20229            if (am == null) {
20230                return;
20231            }
20232
20233            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20234            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20235            try {
20236                am.broadcastIntent(null, intent, null, null,
20237                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20238                        null, false, false, userId);
20239            } catch (RemoteException e) {
20240            }
20241        });
20242    }
20243
20244    @Override
20245    public void replacePreferredActivity(IntentFilter filter, int match,
20246            ComponentName[] set, ComponentName activity, int userId) {
20247        if (filter.countActions() != 1) {
20248            throw new IllegalArgumentException(
20249                    "replacePreferredActivity expects filter to have only 1 action.");
20250        }
20251        if (filter.countDataAuthorities() != 0
20252                || filter.countDataPaths() != 0
20253                || filter.countDataSchemes() > 1
20254                || filter.countDataTypes() != 0) {
20255            throw new IllegalArgumentException(
20256                    "replacePreferredActivity expects filter to have no data authorities, " +
20257                    "paths, or types; and at most one scheme.");
20258        }
20259
20260        final int callingUid = Binder.getCallingUid();
20261        enforceCrossUserPermission(callingUid, userId,
20262                true /* requireFullPermission */, false /* checkShell */,
20263                "replace preferred activity");
20264        synchronized (mPackages) {
20265            if (mContext.checkCallingOrSelfPermission(
20266                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20267                    != PackageManager.PERMISSION_GRANTED) {
20268                if (getUidTargetSdkVersionLockedLPr(callingUid)
20269                        < Build.VERSION_CODES.FROYO) {
20270                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20271                            + Binder.getCallingUid());
20272                    return;
20273                }
20274                mContext.enforceCallingOrSelfPermission(
20275                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20276            }
20277
20278            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20279            if (pir != null) {
20280                // Get all of the existing entries that exactly match this filter.
20281                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20282                if (existing != null && existing.size() == 1) {
20283                    PreferredActivity cur = existing.get(0);
20284                    if (DEBUG_PREFERRED) {
20285                        Slog.i(TAG, "Checking replace of preferred:");
20286                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20287                        if (!cur.mPref.mAlways) {
20288                            Slog.i(TAG, "  -- CUR; not mAlways!");
20289                        } else {
20290                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20291                            Slog.i(TAG, "  -- CUR: mSet="
20292                                    + Arrays.toString(cur.mPref.mSetComponents));
20293                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20294                            Slog.i(TAG, "  -- NEW: mMatch="
20295                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20296                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20297                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20298                        }
20299                    }
20300                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20301                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20302                            && cur.mPref.sameSet(set)) {
20303                        // Setting the preferred activity to what it happens to be already
20304                        if (DEBUG_PREFERRED) {
20305                            Slog.i(TAG, "Replacing with same preferred activity "
20306                                    + cur.mPref.mShortComponent + " for user "
20307                                    + userId + ":");
20308                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20309                        }
20310                        return;
20311                    }
20312                }
20313
20314                if (existing != null) {
20315                    if (DEBUG_PREFERRED) {
20316                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20317                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20318                    }
20319                    for (int i = 0; i < existing.size(); i++) {
20320                        PreferredActivity pa = existing.get(i);
20321                        if (DEBUG_PREFERRED) {
20322                            Slog.i(TAG, "Removing existing preferred activity "
20323                                    + pa.mPref.mComponent + ":");
20324                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20325                        }
20326                        pir.removeFilter(pa);
20327                    }
20328                }
20329            }
20330            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20331                    "Replacing preferred");
20332        }
20333    }
20334
20335    @Override
20336    public void clearPackagePreferredActivities(String packageName) {
20337        final int callingUid = Binder.getCallingUid();
20338        if (getInstantAppPackageName(callingUid) != null) {
20339            return;
20340        }
20341        // writer
20342        synchronized (mPackages) {
20343            PackageParser.Package pkg = mPackages.get(packageName);
20344            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20345                if (mContext.checkCallingOrSelfPermission(
20346                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20347                        != PackageManager.PERMISSION_GRANTED) {
20348                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20349                            < Build.VERSION_CODES.FROYO) {
20350                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20351                                + callingUid);
20352                        return;
20353                    }
20354                    mContext.enforceCallingOrSelfPermission(
20355                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20356                }
20357            }
20358            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20359            if (ps != null
20360                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20361                return;
20362            }
20363            int user = UserHandle.getCallingUserId();
20364            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20365                scheduleWritePackageRestrictionsLocked(user);
20366            }
20367        }
20368    }
20369
20370    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20371    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20372        ArrayList<PreferredActivity> removed = null;
20373        boolean changed = false;
20374        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20375            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20376            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20377            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20378                continue;
20379            }
20380            Iterator<PreferredActivity> it = pir.filterIterator();
20381            while (it.hasNext()) {
20382                PreferredActivity pa = it.next();
20383                // Mark entry for removal only if it matches the package name
20384                // and the entry is of type "always".
20385                if (packageName == null ||
20386                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20387                                && pa.mPref.mAlways)) {
20388                    if (removed == null) {
20389                        removed = new ArrayList<PreferredActivity>();
20390                    }
20391                    removed.add(pa);
20392                }
20393            }
20394            if (removed != null) {
20395                for (int j=0; j<removed.size(); j++) {
20396                    PreferredActivity pa = removed.get(j);
20397                    pir.removeFilter(pa);
20398                }
20399                changed = true;
20400            }
20401        }
20402        if (changed) {
20403            postPreferredActivityChangedBroadcast(userId);
20404        }
20405        return changed;
20406    }
20407
20408    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20409    private void clearIntentFilterVerificationsLPw(int userId) {
20410        final int packageCount = mPackages.size();
20411        for (int i = 0; i < packageCount; i++) {
20412            PackageParser.Package pkg = mPackages.valueAt(i);
20413            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20414        }
20415    }
20416
20417    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20418    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20419        if (userId == UserHandle.USER_ALL) {
20420            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20421                    sUserManager.getUserIds())) {
20422                for (int oneUserId : sUserManager.getUserIds()) {
20423                    scheduleWritePackageRestrictionsLocked(oneUserId);
20424                }
20425            }
20426        } else {
20427            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20428                scheduleWritePackageRestrictionsLocked(userId);
20429            }
20430        }
20431    }
20432
20433    /** Clears state for all users, and touches intent filter verification policy */
20434    void clearDefaultBrowserIfNeeded(String packageName) {
20435        for (int oneUserId : sUserManager.getUserIds()) {
20436            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20437        }
20438    }
20439
20440    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20441        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20442        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20443            if (packageName.equals(defaultBrowserPackageName)) {
20444                setDefaultBrowserPackageName(null, userId);
20445            }
20446        }
20447    }
20448
20449    @Override
20450    public void resetApplicationPreferences(int userId) {
20451        mContext.enforceCallingOrSelfPermission(
20452                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20453        final long identity = Binder.clearCallingIdentity();
20454        // writer
20455        try {
20456            synchronized (mPackages) {
20457                clearPackagePreferredActivitiesLPw(null, userId);
20458                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20459                // TODO: We have to reset the default SMS and Phone. This requires
20460                // significant refactoring to keep all default apps in the package
20461                // manager (cleaner but more work) or have the services provide
20462                // callbacks to the package manager to request a default app reset.
20463                applyFactoryDefaultBrowserLPw(userId);
20464                clearIntentFilterVerificationsLPw(userId);
20465                primeDomainVerificationsLPw(userId);
20466                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20467                scheduleWritePackageRestrictionsLocked(userId);
20468            }
20469            resetNetworkPolicies(userId);
20470        } finally {
20471            Binder.restoreCallingIdentity(identity);
20472        }
20473    }
20474
20475    @Override
20476    public int getPreferredActivities(List<IntentFilter> outFilters,
20477            List<ComponentName> outActivities, String packageName) {
20478        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20479            return 0;
20480        }
20481        int num = 0;
20482        final int userId = UserHandle.getCallingUserId();
20483        // reader
20484        synchronized (mPackages) {
20485            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20486            if (pir != null) {
20487                final Iterator<PreferredActivity> it = pir.filterIterator();
20488                while (it.hasNext()) {
20489                    final PreferredActivity pa = it.next();
20490                    if (packageName == null
20491                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20492                                    && pa.mPref.mAlways)) {
20493                        if (outFilters != null) {
20494                            outFilters.add(new IntentFilter(pa));
20495                        }
20496                        if (outActivities != null) {
20497                            outActivities.add(pa.mPref.mComponent);
20498                        }
20499                    }
20500                }
20501            }
20502        }
20503
20504        return num;
20505    }
20506
20507    @Override
20508    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20509            int userId) {
20510        int callingUid = Binder.getCallingUid();
20511        if (callingUid != Process.SYSTEM_UID) {
20512            throw new SecurityException(
20513                    "addPersistentPreferredActivity can only be run by the system");
20514        }
20515        if (filter.countActions() == 0) {
20516            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20517            return;
20518        }
20519        synchronized (mPackages) {
20520            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20521                    ":");
20522            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20523            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20524                    new PersistentPreferredActivity(filter, activity));
20525            scheduleWritePackageRestrictionsLocked(userId);
20526            postPreferredActivityChangedBroadcast(userId);
20527        }
20528    }
20529
20530    @Override
20531    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20532        int callingUid = Binder.getCallingUid();
20533        if (callingUid != Process.SYSTEM_UID) {
20534            throw new SecurityException(
20535                    "clearPackagePersistentPreferredActivities can only be run by the system");
20536        }
20537        ArrayList<PersistentPreferredActivity> removed = null;
20538        boolean changed = false;
20539        synchronized (mPackages) {
20540            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20541                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20542                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20543                        .valueAt(i);
20544                if (userId != thisUserId) {
20545                    continue;
20546                }
20547                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20548                while (it.hasNext()) {
20549                    PersistentPreferredActivity ppa = it.next();
20550                    // Mark entry for removal only if it matches the package name.
20551                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20552                        if (removed == null) {
20553                            removed = new ArrayList<PersistentPreferredActivity>();
20554                        }
20555                        removed.add(ppa);
20556                    }
20557                }
20558                if (removed != null) {
20559                    for (int j=0; j<removed.size(); j++) {
20560                        PersistentPreferredActivity ppa = removed.get(j);
20561                        ppir.removeFilter(ppa);
20562                    }
20563                    changed = true;
20564                }
20565            }
20566
20567            if (changed) {
20568                scheduleWritePackageRestrictionsLocked(userId);
20569                postPreferredActivityChangedBroadcast(userId);
20570            }
20571        }
20572    }
20573
20574    /**
20575     * Common machinery for picking apart a restored XML blob and passing
20576     * it to a caller-supplied functor to be applied to the running system.
20577     */
20578    private void restoreFromXml(XmlPullParser parser, int userId,
20579            String expectedStartTag, BlobXmlRestorer functor)
20580            throws IOException, XmlPullParserException {
20581        int type;
20582        while ((type = parser.next()) != XmlPullParser.START_TAG
20583                && type != XmlPullParser.END_DOCUMENT) {
20584        }
20585        if (type != XmlPullParser.START_TAG) {
20586            // oops didn't find a start tag?!
20587            if (DEBUG_BACKUP) {
20588                Slog.e(TAG, "Didn't find start tag during restore");
20589            }
20590            return;
20591        }
20592Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20593        // this is supposed to be TAG_PREFERRED_BACKUP
20594        if (!expectedStartTag.equals(parser.getName())) {
20595            if (DEBUG_BACKUP) {
20596                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20597            }
20598            return;
20599        }
20600
20601        // skip interfering stuff, then we're aligned with the backing implementation
20602        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20603Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20604        functor.apply(parser, userId);
20605    }
20606
20607    private interface BlobXmlRestorer {
20608        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20609    }
20610
20611    /**
20612     * Non-Binder method, support for the backup/restore mechanism: write the
20613     * full set of preferred activities in its canonical XML format.  Returns the
20614     * XML output as a byte array, or null if there is none.
20615     */
20616    @Override
20617    public byte[] getPreferredActivityBackup(int userId) {
20618        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20619            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20620        }
20621
20622        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20623        try {
20624            final XmlSerializer serializer = new FastXmlSerializer();
20625            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20626            serializer.startDocument(null, true);
20627            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20628
20629            synchronized (mPackages) {
20630                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20631            }
20632
20633            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20634            serializer.endDocument();
20635            serializer.flush();
20636        } catch (Exception e) {
20637            if (DEBUG_BACKUP) {
20638                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20639            }
20640            return null;
20641        }
20642
20643        return dataStream.toByteArray();
20644    }
20645
20646    @Override
20647    public void restorePreferredActivities(byte[] backup, int userId) {
20648        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20649            throw new SecurityException("Only the system may call restorePreferredActivities()");
20650        }
20651
20652        try {
20653            final XmlPullParser parser = Xml.newPullParser();
20654            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20655            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20656                    new BlobXmlRestorer() {
20657                        @Override
20658                        public void apply(XmlPullParser parser, int userId)
20659                                throws XmlPullParserException, IOException {
20660                            synchronized (mPackages) {
20661                                mSettings.readPreferredActivitiesLPw(parser, userId);
20662                            }
20663                        }
20664                    } );
20665        } catch (Exception e) {
20666            if (DEBUG_BACKUP) {
20667                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20668            }
20669        }
20670    }
20671
20672    /**
20673     * Non-Binder method, support for the backup/restore mechanism: write the
20674     * default browser (etc) settings in its canonical XML format.  Returns the default
20675     * browser XML representation as a byte array, or null if there is none.
20676     */
20677    @Override
20678    public byte[] getDefaultAppsBackup(int userId) {
20679        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20680            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20681        }
20682
20683        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20684        try {
20685            final XmlSerializer serializer = new FastXmlSerializer();
20686            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20687            serializer.startDocument(null, true);
20688            serializer.startTag(null, TAG_DEFAULT_APPS);
20689
20690            synchronized (mPackages) {
20691                mSettings.writeDefaultAppsLPr(serializer, userId);
20692            }
20693
20694            serializer.endTag(null, TAG_DEFAULT_APPS);
20695            serializer.endDocument();
20696            serializer.flush();
20697        } catch (Exception e) {
20698            if (DEBUG_BACKUP) {
20699                Slog.e(TAG, "Unable to write default apps for backup", e);
20700            }
20701            return null;
20702        }
20703
20704        return dataStream.toByteArray();
20705    }
20706
20707    @Override
20708    public void restoreDefaultApps(byte[] backup, int userId) {
20709        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20710            throw new SecurityException("Only the system may call restoreDefaultApps()");
20711        }
20712
20713        try {
20714            final XmlPullParser parser = Xml.newPullParser();
20715            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20716            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20717                    new BlobXmlRestorer() {
20718                        @Override
20719                        public void apply(XmlPullParser parser, int userId)
20720                                throws XmlPullParserException, IOException {
20721                            synchronized (mPackages) {
20722                                mSettings.readDefaultAppsLPw(parser, userId);
20723                            }
20724                        }
20725                    } );
20726        } catch (Exception e) {
20727            if (DEBUG_BACKUP) {
20728                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20729            }
20730        }
20731    }
20732
20733    @Override
20734    public byte[] getIntentFilterVerificationBackup(int userId) {
20735        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20736            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20737        }
20738
20739        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20740        try {
20741            final XmlSerializer serializer = new FastXmlSerializer();
20742            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20743            serializer.startDocument(null, true);
20744            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20745
20746            synchronized (mPackages) {
20747                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20748            }
20749
20750            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20751            serializer.endDocument();
20752            serializer.flush();
20753        } catch (Exception e) {
20754            if (DEBUG_BACKUP) {
20755                Slog.e(TAG, "Unable to write default apps for backup", e);
20756            }
20757            return null;
20758        }
20759
20760        return dataStream.toByteArray();
20761    }
20762
20763    @Override
20764    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20765        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20766            throw new SecurityException("Only the system may call restorePreferredActivities()");
20767        }
20768
20769        try {
20770            final XmlPullParser parser = Xml.newPullParser();
20771            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20772            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20773                    new BlobXmlRestorer() {
20774                        @Override
20775                        public void apply(XmlPullParser parser, int userId)
20776                                throws XmlPullParserException, IOException {
20777                            synchronized (mPackages) {
20778                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20779                                mSettings.writeLPr();
20780                            }
20781                        }
20782                    } );
20783        } catch (Exception e) {
20784            if (DEBUG_BACKUP) {
20785                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20786            }
20787        }
20788    }
20789
20790    @Override
20791    public byte[] getPermissionGrantBackup(int userId) {
20792        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20793            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20794        }
20795
20796        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20797        try {
20798            final XmlSerializer serializer = new FastXmlSerializer();
20799            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20800            serializer.startDocument(null, true);
20801            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20802
20803            synchronized (mPackages) {
20804                serializeRuntimePermissionGrantsLPr(serializer, userId);
20805            }
20806
20807            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20808            serializer.endDocument();
20809            serializer.flush();
20810        } catch (Exception e) {
20811            if (DEBUG_BACKUP) {
20812                Slog.e(TAG, "Unable to write default apps for backup", e);
20813            }
20814            return null;
20815        }
20816
20817        return dataStream.toByteArray();
20818    }
20819
20820    @Override
20821    public void restorePermissionGrants(byte[] backup, int userId) {
20822        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20823            throw new SecurityException("Only the system may call restorePermissionGrants()");
20824        }
20825
20826        try {
20827            final XmlPullParser parser = Xml.newPullParser();
20828            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20829            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20830                    new BlobXmlRestorer() {
20831                        @Override
20832                        public void apply(XmlPullParser parser, int userId)
20833                                throws XmlPullParserException, IOException {
20834                            synchronized (mPackages) {
20835                                processRestoredPermissionGrantsLPr(parser, userId);
20836                            }
20837                        }
20838                    } );
20839        } catch (Exception e) {
20840            if (DEBUG_BACKUP) {
20841                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20842            }
20843        }
20844    }
20845
20846    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20847            throws IOException {
20848        serializer.startTag(null, TAG_ALL_GRANTS);
20849
20850        final int N = mSettings.mPackages.size();
20851        for (int i = 0; i < N; i++) {
20852            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20853            boolean pkgGrantsKnown = false;
20854
20855            PermissionsState packagePerms = ps.getPermissionsState();
20856
20857            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20858                final int grantFlags = state.getFlags();
20859                // only look at grants that are not system/policy fixed
20860                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20861                    final boolean isGranted = state.isGranted();
20862                    // And only back up the user-twiddled state bits
20863                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20864                        final String packageName = mSettings.mPackages.keyAt(i);
20865                        if (!pkgGrantsKnown) {
20866                            serializer.startTag(null, TAG_GRANT);
20867                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20868                            pkgGrantsKnown = true;
20869                        }
20870
20871                        final boolean userSet =
20872                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20873                        final boolean userFixed =
20874                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20875                        final boolean revoke =
20876                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20877
20878                        serializer.startTag(null, TAG_PERMISSION);
20879                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20880                        if (isGranted) {
20881                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20882                        }
20883                        if (userSet) {
20884                            serializer.attribute(null, ATTR_USER_SET, "true");
20885                        }
20886                        if (userFixed) {
20887                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20888                        }
20889                        if (revoke) {
20890                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20891                        }
20892                        serializer.endTag(null, TAG_PERMISSION);
20893                    }
20894                }
20895            }
20896
20897            if (pkgGrantsKnown) {
20898                serializer.endTag(null, TAG_GRANT);
20899            }
20900        }
20901
20902        serializer.endTag(null, TAG_ALL_GRANTS);
20903    }
20904
20905    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20906            throws XmlPullParserException, IOException {
20907        String pkgName = null;
20908        int outerDepth = parser.getDepth();
20909        int type;
20910        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20911                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20912            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20913                continue;
20914            }
20915
20916            final String tagName = parser.getName();
20917            if (tagName.equals(TAG_GRANT)) {
20918                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20919                if (DEBUG_BACKUP) {
20920                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20921                }
20922            } else if (tagName.equals(TAG_PERMISSION)) {
20923
20924                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20925                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20926
20927                int newFlagSet = 0;
20928                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20929                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20930                }
20931                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20932                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20933                }
20934                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20935                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20936                }
20937                if (DEBUG_BACKUP) {
20938                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20939                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20940                }
20941                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20942                if (ps != null) {
20943                    // Already installed so we apply the grant immediately
20944                    if (DEBUG_BACKUP) {
20945                        Slog.v(TAG, "        + already installed; applying");
20946                    }
20947                    PermissionsState perms = ps.getPermissionsState();
20948                    BasePermission bp = mSettings.mPermissions.get(permName);
20949                    if (bp != null) {
20950                        if (isGranted) {
20951                            perms.grantRuntimePermission(bp, userId);
20952                        }
20953                        if (newFlagSet != 0) {
20954                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20955                        }
20956                    }
20957                } else {
20958                    // Need to wait for post-restore install to apply the grant
20959                    if (DEBUG_BACKUP) {
20960                        Slog.v(TAG, "        - not yet installed; saving for later");
20961                    }
20962                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20963                            isGranted, newFlagSet, userId);
20964                }
20965            } else {
20966                PackageManagerService.reportSettingsProblem(Log.WARN,
20967                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20968                XmlUtils.skipCurrentTag(parser);
20969            }
20970        }
20971
20972        scheduleWriteSettingsLocked();
20973        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20974    }
20975
20976    @Override
20977    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20978            int sourceUserId, int targetUserId, int flags) {
20979        mContext.enforceCallingOrSelfPermission(
20980                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20981        int callingUid = Binder.getCallingUid();
20982        enforceOwnerRights(ownerPackage, callingUid);
20983        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20984        if (intentFilter.countActions() == 0) {
20985            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20986            return;
20987        }
20988        synchronized (mPackages) {
20989            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20990                    ownerPackage, targetUserId, flags);
20991            CrossProfileIntentResolver resolver =
20992                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20993            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20994            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20995            if (existing != null) {
20996                int size = existing.size();
20997                for (int i = 0; i < size; i++) {
20998                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20999                        return;
21000                    }
21001                }
21002            }
21003            resolver.addFilter(newFilter);
21004            scheduleWritePackageRestrictionsLocked(sourceUserId);
21005        }
21006    }
21007
21008    @Override
21009    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21010        mContext.enforceCallingOrSelfPermission(
21011                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21012        final int callingUid = Binder.getCallingUid();
21013        enforceOwnerRights(ownerPackage, callingUid);
21014        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21015        synchronized (mPackages) {
21016            CrossProfileIntentResolver resolver =
21017                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21018            ArraySet<CrossProfileIntentFilter> set =
21019                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21020            for (CrossProfileIntentFilter filter : set) {
21021                if (filter.getOwnerPackage().equals(ownerPackage)) {
21022                    resolver.removeFilter(filter);
21023                }
21024            }
21025            scheduleWritePackageRestrictionsLocked(sourceUserId);
21026        }
21027    }
21028
21029    // Enforcing that callingUid is owning pkg on userId
21030    private void enforceOwnerRights(String pkg, int callingUid) {
21031        // The system owns everything.
21032        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21033            return;
21034        }
21035        final int callingUserId = UserHandle.getUserId(callingUid);
21036        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21037        if (pi == null) {
21038            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21039                    + callingUserId);
21040        }
21041        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21042            throw new SecurityException("Calling uid " + callingUid
21043                    + " does not own package " + pkg);
21044        }
21045    }
21046
21047    @Override
21048    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21049        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21050            return null;
21051        }
21052        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21053    }
21054
21055    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21056        UserManagerService ums = UserManagerService.getInstance();
21057        if (ums != null) {
21058            final UserInfo parent = ums.getProfileParent(userId);
21059            final int launcherUid = (parent != null) ? parent.id : userId;
21060            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21061            if (launcherComponent != null) {
21062                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21063                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21064                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21065                        .setPackage(launcherComponent.getPackageName());
21066                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21067            }
21068        }
21069    }
21070
21071    /**
21072     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21073     * then reports the most likely home activity or null if there are more than one.
21074     */
21075    private ComponentName getDefaultHomeActivity(int userId) {
21076        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21077        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21078        if (cn != null) {
21079            return cn;
21080        }
21081
21082        // Find the launcher with the highest priority and return that component if there are no
21083        // other home activity with the same priority.
21084        int lastPriority = Integer.MIN_VALUE;
21085        ComponentName lastComponent = null;
21086        final int size = allHomeCandidates.size();
21087        for (int i = 0; i < size; i++) {
21088            final ResolveInfo ri = allHomeCandidates.get(i);
21089            if (ri.priority > lastPriority) {
21090                lastComponent = ri.activityInfo.getComponentName();
21091                lastPriority = ri.priority;
21092            } else if (ri.priority == lastPriority) {
21093                // Two components found with same priority.
21094                lastComponent = null;
21095            }
21096        }
21097        return lastComponent;
21098    }
21099
21100    private Intent getHomeIntent() {
21101        Intent intent = new Intent(Intent.ACTION_MAIN);
21102        intent.addCategory(Intent.CATEGORY_HOME);
21103        intent.addCategory(Intent.CATEGORY_DEFAULT);
21104        return intent;
21105    }
21106
21107    private IntentFilter getHomeFilter() {
21108        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21109        filter.addCategory(Intent.CATEGORY_HOME);
21110        filter.addCategory(Intent.CATEGORY_DEFAULT);
21111        return filter;
21112    }
21113
21114    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21115            int userId) {
21116        Intent intent  = getHomeIntent();
21117        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21118                PackageManager.GET_META_DATA, userId);
21119        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21120                true, false, false, userId);
21121
21122        allHomeCandidates.clear();
21123        if (list != null) {
21124            for (ResolveInfo ri : list) {
21125                allHomeCandidates.add(ri);
21126            }
21127        }
21128        return (preferred == null || preferred.activityInfo == null)
21129                ? null
21130                : new ComponentName(preferred.activityInfo.packageName,
21131                        preferred.activityInfo.name);
21132    }
21133
21134    @Override
21135    public void setHomeActivity(ComponentName comp, int userId) {
21136        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21137            return;
21138        }
21139        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21140        getHomeActivitiesAsUser(homeActivities, userId);
21141
21142        boolean found = false;
21143
21144        final int size = homeActivities.size();
21145        final ComponentName[] set = new ComponentName[size];
21146        for (int i = 0; i < size; i++) {
21147            final ResolveInfo candidate = homeActivities.get(i);
21148            final ActivityInfo info = candidate.activityInfo;
21149            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21150            set[i] = activityName;
21151            if (!found && activityName.equals(comp)) {
21152                found = true;
21153            }
21154        }
21155        if (!found) {
21156            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21157                    + userId);
21158        }
21159        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21160                set, comp, userId);
21161    }
21162
21163    private @Nullable String getSetupWizardPackageName() {
21164        final Intent intent = new Intent(Intent.ACTION_MAIN);
21165        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21166
21167        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21168                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21169                        | MATCH_DISABLED_COMPONENTS,
21170                UserHandle.myUserId());
21171        if (matches.size() == 1) {
21172            return matches.get(0).getComponentInfo().packageName;
21173        } else {
21174            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21175                    + ": matches=" + matches);
21176            return null;
21177        }
21178    }
21179
21180    private @Nullable String getStorageManagerPackageName() {
21181        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21182
21183        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21184                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21185                        | MATCH_DISABLED_COMPONENTS,
21186                UserHandle.myUserId());
21187        if (matches.size() == 1) {
21188            return matches.get(0).getComponentInfo().packageName;
21189        } else {
21190            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21191                    + matches.size() + ": matches=" + matches);
21192            return null;
21193        }
21194    }
21195
21196    @Override
21197    public void setApplicationEnabledSetting(String appPackageName,
21198            int newState, int flags, int userId, String callingPackage) {
21199        if (!sUserManager.exists(userId)) return;
21200        if (callingPackage == null) {
21201            callingPackage = Integer.toString(Binder.getCallingUid());
21202        }
21203        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21204    }
21205
21206    @Override
21207    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21208        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21209        synchronized (mPackages) {
21210            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21211            if (pkgSetting != null) {
21212                pkgSetting.setUpdateAvailable(updateAvailable);
21213            }
21214        }
21215    }
21216
21217    @Override
21218    public void setComponentEnabledSetting(ComponentName componentName,
21219            int newState, int flags, int userId) {
21220        if (!sUserManager.exists(userId)) return;
21221        setEnabledSetting(componentName.getPackageName(),
21222                componentName.getClassName(), newState, flags, userId, null);
21223    }
21224
21225    private void setEnabledSetting(final String packageName, String className, int newState,
21226            final int flags, int userId, String callingPackage) {
21227        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21228              || newState == COMPONENT_ENABLED_STATE_ENABLED
21229              || newState == COMPONENT_ENABLED_STATE_DISABLED
21230              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21231              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21232            throw new IllegalArgumentException("Invalid new component state: "
21233                    + newState);
21234        }
21235        PackageSetting pkgSetting;
21236        final int callingUid = Binder.getCallingUid();
21237        final int permission;
21238        if (callingUid == Process.SYSTEM_UID) {
21239            permission = PackageManager.PERMISSION_GRANTED;
21240        } else {
21241            permission = mContext.checkCallingOrSelfPermission(
21242                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21243        }
21244        enforceCrossUserPermission(callingUid, userId,
21245                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21246        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21247        boolean sendNow = false;
21248        boolean isApp = (className == null);
21249        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21250        String componentName = isApp ? packageName : className;
21251        int packageUid = -1;
21252        ArrayList<String> components;
21253
21254        // reader
21255        synchronized (mPackages) {
21256            pkgSetting = mSettings.mPackages.get(packageName);
21257            if (pkgSetting == null) {
21258                if (!isCallerInstantApp) {
21259                    if (className == null) {
21260                        throw new IllegalArgumentException("Unknown package: " + packageName);
21261                    }
21262                    throw new IllegalArgumentException(
21263                            "Unknown component: " + packageName + "/" + className);
21264                } else {
21265                    // throw SecurityException to prevent leaking package information
21266                    throw new SecurityException(
21267                            "Attempt to change component state; "
21268                            + "pid=" + Binder.getCallingPid()
21269                            + ", uid=" + callingUid
21270                            + (className == null
21271                                    ? ", package=" + packageName
21272                                    : ", component=" + packageName + "/" + className));
21273                }
21274            }
21275        }
21276
21277        // Limit who can change which apps
21278        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21279            // Don't allow apps that don't have permission to modify other apps
21280            if (!allowedByPermission
21281                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21282                throw new SecurityException(
21283                        "Attempt to change component state; "
21284                        + "pid=" + Binder.getCallingPid()
21285                        + ", uid=" + callingUid
21286                        + (className == null
21287                                ? ", package=" + packageName
21288                                : ", component=" + packageName + "/" + className));
21289            }
21290            // Don't allow changing protected packages.
21291            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21292                throw new SecurityException("Cannot disable a protected package: " + packageName);
21293            }
21294        }
21295
21296        synchronized (mPackages) {
21297            if (callingUid == Process.SHELL_UID
21298                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21299                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21300                // unless it is a test package.
21301                int oldState = pkgSetting.getEnabled(userId);
21302                if (className == null
21303                    &&
21304                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21305                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21306                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21307                    &&
21308                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21309                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21310                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21311                    // ok
21312                } else {
21313                    throw new SecurityException(
21314                            "Shell cannot change component state for " + packageName + "/"
21315                            + className + " to " + newState);
21316                }
21317            }
21318            if (className == null) {
21319                // We're dealing with an application/package level state change
21320                if (pkgSetting.getEnabled(userId) == newState) {
21321                    // Nothing to do
21322                    return;
21323                }
21324                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21325                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21326                    // Don't care about who enables an app.
21327                    callingPackage = null;
21328                }
21329                pkgSetting.setEnabled(newState, userId, callingPackage);
21330                // pkgSetting.pkg.mSetEnabled = newState;
21331            } else {
21332                // We're dealing with a component level state change
21333                // First, verify that this is a valid class name.
21334                PackageParser.Package pkg = pkgSetting.pkg;
21335                if (pkg == null || !pkg.hasComponentClassName(className)) {
21336                    if (pkg != null &&
21337                            pkg.applicationInfo.targetSdkVersion >=
21338                                    Build.VERSION_CODES.JELLY_BEAN) {
21339                        throw new IllegalArgumentException("Component class " + className
21340                                + " does not exist in " + packageName);
21341                    } else {
21342                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21343                                + className + " does not exist in " + packageName);
21344                    }
21345                }
21346                switch (newState) {
21347                case COMPONENT_ENABLED_STATE_ENABLED:
21348                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21349                        return;
21350                    }
21351                    break;
21352                case COMPONENT_ENABLED_STATE_DISABLED:
21353                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21354                        return;
21355                    }
21356                    break;
21357                case COMPONENT_ENABLED_STATE_DEFAULT:
21358                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21359                        return;
21360                    }
21361                    break;
21362                default:
21363                    Slog.e(TAG, "Invalid new component state: " + newState);
21364                    return;
21365                }
21366            }
21367            scheduleWritePackageRestrictionsLocked(userId);
21368            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21369            final long callingId = Binder.clearCallingIdentity();
21370            try {
21371                updateInstantAppInstallerLocked(packageName);
21372            } finally {
21373                Binder.restoreCallingIdentity(callingId);
21374            }
21375            components = mPendingBroadcasts.get(userId, packageName);
21376            final boolean newPackage = components == null;
21377            if (newPackage) {
21378                components = new ArrayList<String>();
21379            }
21380            if (!components.contains(componentName)) {
21381                components.add(componentName);
21382            }
21383            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21384                sendNow = true;
21385                // Purge entry from pending broadcast list if another one exists already
21386                // since we are sending one right away.
21387                mPendingBroadcasts.remove(userId, packageName);
21388            } else {
21389                if (newPackage) {
21390                    mPendingBroadcasts.put(userId, packageName, components);
21391                }
21392                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21393                    // Schedule a message
21394                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21395                }
21396            }
21397        }
21398
21399        long callingId = Binder.clearCallingIdentity();
21400        try {
21401            if (sendNow) {
21402                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21403                sendPackageChangedBroadcast(packageName,
21404                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21405            }
21406        } finally {
21407            Binder.restoreCallingIdentity(callingId);
21408        }
21409    }
21410
21411    @Override
21412    public void flushPackageRestrictionsAsUser(int userId) {
21413        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21414            return;
21415        }
21416        if (!sUserManager.exists(userId)) {
21417            return;
21418        }
21419        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21420                false /* checkShell */, "flushPackageRestrictions");
21421        synchronized (mPackages) {
21422            mSettings.writePackageRestrictionsLPr(userId);
21423            mDirtyUsers.remove(userId);
21424            if (mDirtyUsers.isEmpty()) {
21425                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21426            }
21427        }
21428    }
21429
21430    private void sendPackageChangedBroadcast(String packageName,
21431            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21432        if (DEBUG_INSTALL)
21433            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21434                    + componentNames);
21435        Bundle extras = new Bundle(4);
21436        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21437        String nameList[] = new String[componentNames.size()];
21438        componentNames.toArray(nameList);
21439        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21440        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21441        extras.putInt(Intent.EXTRA_UID, packageUid);
21442        // If this is not reporting a change of the overall package, then only send it
21443        // to registered receivers.  We don't want to launch a swath of apps for every
21444        // little component state change.
21445        final int flags = !componentNames.contains(packageName)
21446                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21447        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21448                new int[] {UserHandle.getUserId(packageUid)});
21449    }
21450
21451    @Override
21452    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21453        if (!sUserManager.exists(userId)) return;
21454        final int callingUid = Binder.getCallingUid();
21455        if (getInstantAppPackageName(callingUid) != null) {
21456            return;
21457        }
21458        final int permission = mContext.checkCallingOrSelfPermission(
21459                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21460        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21461        enforceCrossUserPermission(callingUid, userId,
21462                true /* requireFullPermission */, true /* checkShell */, "stop package");
21463        // writer
21464        synchronized (mPackages) {
21465            final PackageSetting ps = mSettings.mPackages.get(packageName);
21466            if (!filterAppAccessLPr(ps, callingUid, userId)
21467                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21468                            allowedByPermission, callingUid, userId)) {
21469                scheduleWritePackageRestrictionsLocked(userId);
21470            }
21471        }
21472    }
21473
21474    @Override
21475    public String getInstallerPackageName(String packageName) {
21476        final int callingUid = Binder.getCallingUid();
21477        if (getInstantAppPackageName(callingUid) != null) {
21478            return null;
21479        }
21480        // reader
21481        synchronized (mPackages) {
21482            final PackageSetting ps = mSettings.mPackages.get(packageName);
21483            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21484                return null;
21485            }
21486            return mSettings.getInstallerPackageNameLPr(packageName);
21487        }
21488    }
21489
21490    public boolean isOrphaned(String packageName) {
21491        // reader
21492        synchronized (mPackages) {
21493            return mSettings.isOrphaned(packageName);
21494        }
21495    }
21496
21497    @Override
21498    public int getApplicationEnabledSetting(String packageName, int userId) {
21499        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21500        int callingUid = Binder.getCallingUid();
21501        enforceCrossUserPermission(callingUid, userId,
21502                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21503        // reader
21504        synchronized (mPackages) {
21505            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21506                return COMPONENT_ENABLED_STATE_DISABLED;
21507            }
21508            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21509        }
21510    }
21511
21512    @Override
21513    public int getComponentEnabledSetting(ComponentName component, int userId) {
21514        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21515        int callingUid = Binder.getCallingUid();
21516        enforceCrossUserPermission(callingUid, userId,
21517                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21518        synchronized (mPackages) {
21519            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21520                    component, TYPE_UNKNOWN, userId)) {
21521                return COMPONENT_ENABLED_STATE_DISABLED;
21522            }
21523            return mSettings.getComponentEnabledSettingLPr(component, userId);
21524        }
21525    }
21526
21527    @Override
21528    public void enterSafeMode() {
21529        enforceSystemOrRoot("Only the system can request entering safe mode");
21530
21531        if (!mSystemReady) {
21532            mSafeMode = true;
21533        }
21534    }
21535
21536    @Override
21537    public void systemReady() {
21538        enforceSystemOrRoot("Only the system can claim the system is ready");
21539
21540        mSystemReady = true;
21541        final ContentResolver resolver = mContext.getContentResolver();
21542        ContentObserver co = new ContentObserver(mHandler) {
21543            @Override
21544            public void onChange(boolean selfChange) {
21545                mEphemeralAppsDisabled =
21546                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21547                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21548            }
21549        };
21550        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21551                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21552                false, co, UserHandle.USER_SYSTEM);
21553        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21554                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21555        co.onChange(true);
21556
21557        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21558        // disabled after already being started.
21559        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21560                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21561
21562        // Read the compatibilty setting when the system is ready.
21563        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21564                mContext.getContentResolver(),
21565                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21566        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21567        if (DEBUG_SETTINGS) {
21568            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21569        }
21570
21571        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21572
21573        synchronized (mPackages) {
21574            // Verify that all of the preferred activity components actually
21575            // exist.  It is possible for applications to be updated and at
21576            // that point remove a previously declared activity component that
21577            // had been set as a preferred activity.  We try to clean this up
21578            // the next time we encounter that preferred activity, but it is
21579            // possible for the user flow to never be able to return to that
21580            // situation so here we do a sanity check to make sure we haven't
21581            // left any junk around.
21582            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21583            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21584                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21585                removed.clear();
21586                for (PreferredActivity pa : pir.filterSet()) {
21587                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21588                        removed.add(pa);
21589                    }
21590                }
21591                if (removed.size() > 0) {
21592                    for (int r=0; r<removed.size(); r++) {
21593                        PreferredActivity pa = removed.get(r);
21594                        Slog.w(TAG, "Removing dangling preferred activity: "
21595                                + pa.mPref.mComponent);
21596                        pir.removeFilter(pa);
21597                    }
21598                    mSettings.writePackageRestrictionsLPr(
21599                            mSettings.mPreferredActivities.keyAt(i));
21600                }
21601            }
21602
21603            for (int userId : UserManagerService.getInstance().getUserIds()) {
21604                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21605                    grantPermissionsUserIds = ArrayUtils.appendInt(
21606                            grantPermissionsUserIds, userId);
21607                }
21608            }
21609        }
21610        sUserManager.systemReady();
21611
21612        // If we upgraded grant all default permissions before kicking off.
21613        for (int userId : grantPermissionsUserIds) {
21614            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21615        }
21616
21617        // If we did not grant default permissions, we preload from this the
21618        // default permission exceptions lazily to ensure we don't hit the
21619        // disk on a new user creation.
21620        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21621            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21622        }
21623
21624        // Kick off any messages waiting for system ready
21625        if (mPostSystemReadyMessages != null) {
21626            for (Message msg : mPostSystemReadyMessages) {
21627                msg.sendToTarget();
21628            }
21629            mPostSystemReadyMessages = null;
21630        }
21631
21632        // Watch for external volumes that come and go over time
21633        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21634        storage.registerListener(mStorageListener);
21635
21636        mInstallerService.systemReady();
21637        mPackageDexOptimizer.systemReady();
21638
21639        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21640                StorageManagerInternal.class);
21641        StorageManagerInternal.addExternalStoragePolicy(
21642                new StorageManagerInternal.ExternalStorageMountPolicy() {
21643            @Override
21644            public int getMountMode(int uid, String packageName) {
21645                if (Process.isIsolated(uid)) {
21646                    return Zygote.MOUNT_EXTERNAL_NONE;
21647                }
21648                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21649                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21650                }
21651                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21652                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21653                }
21654                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21655                    return Zygote.MOUNT_EXTERNAL_READ;
21656                }
21657                return Zygote.MOUNT_EXTERNAL_WRITE;
21658            }
21659
21660            @Override
21661            public boolean hasExternalStorage(int uid, String packageName) {
21662                return true;
21663            }
21664        });
21665
21666        // Now that we're mostly running, clean up stale users and apps
21667        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21668        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21669
21670        if (mPrivappPermissionsViolations != null) {
21671            Slog.wtf(TAG,"Signature|privileged permissions not in "
21672                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21673            mPrivappPermissionsViolations = null;
21674        }
21675    }
21676
21677    public void waitForAppDataPrepared() {
21678        if (mPrepareAppDataFuture == null) {
21679            return;
21680        }
21681        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21682        mPrepareAppDataFuture = null;
21683    }
21684
21685    @Override
21686    public boolean isSafeMode() {
21687        // allow instant applications
21688        return mSafeMode;
21689    }
21690
21691    @Override
21692    public boolean hasSystemUidErrors() {
21693        // allow instant applications
21694        return mHasSystemUidErrors;
21695    }
21696
21697    static String arrayToString(int[] array) {
21698        StringBuffer buf = new StringBuffer(128);
21699        buf.append('[');
21700        if (array != null) {
21701            for (int i=0; i<array.length; i++) {
21702                if (i > 0) buf.append(", ");
21703                buf.append(array[i]);
21704            }
21705        }
21706        buf.append(']');
21707        return buf.toString();
21708    }
21709
21710    static class DumpState {
21711        public static final int DUMP_LIBS = 1 << 0;
21712        public static final int DUMP_FEATURES = 1 << 1;
21713        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21714        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21715        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21716        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21717        public static final int DUMP_PERMISSIONS = 1 << 6;
21718        public static final int DUMP_PACKAGES = 1 << 7;
21719        public static final int DUMP_SHARED_USERS = 1 << 8;
21720        public static final int DUMP_MESSAGES = 1 << 9;
21721        public static final int DUMP_PROVIDERS = 1 << 10;
21722        public static final int DUMP_VERIFIERS = 1 << 11;
21723        public static final int DUMP_PREFERRED = 1 << 12;
21724        public static final int DUMP_PREFERRED_XML = 1 << 13;
21725        public static final int DUMP_KEYSETS = 1 << 14;
21726        public static final int DUMP_VERSION = 1 << 15;
21727        public static final int DUMP_INSTALLS = 1 << 16;
21728        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21729        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21730        public static final int DUMP_FROZEN = 1 << 19;
21731        public static final int DUMP_DEXOPT = 1 << 20;
21732        public static final int DUMP_COMPILER_STATS = 1 << 21;
21733        public static final int DUMP_CHANGES = 1 << 22;
21734        public static final int DUMP_VOLUMES = 1 << 23;
21735
21736        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21737
21738        private int mTypes;
21739
21740        private int mOptions;
21741
21742        private boolean mTitlePrinted;
21743
21744        private SharedUserSetting mSharedUser;
21745
21746        public boolean isDumping(int type) {
21747            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21748                return true;
21749            }
21750
21751            return (mTypes & type) != 0;
21752        }
21753
21754        public void setDump(int type) {
21755            mTypes |= type;
21756        }
21757
21758        public boolean isOptionEnabled(int option) {
21759            return (mOptions & option) != 0;
21760        }
21761
21762        public void setOptionEnabled(int option) {
21763            mOptions |= option;
21764        }
21765
21766        public boolean onTitlePrinted() {
21767            final boolean printed = mTitlePrinted;
21768            mTitlePrinted = true;
21769            return printed;
21770        }
21771
21772        public boolean getTitlePrinted() {
21773            return mTitlePrinted;
21774        }
21775
21776        public void setTitlePrinted(boolean enabled) {
21777            mTitlePrinted = enabled;
21778        }
21779
21780        public SharedUserSetting getSharedUser() {
21781            return mSharedUser;
21782        }
21783
21784        public void setSharedUser(SharedUserSetting user) {
21785            mSharedUser = user;
21786        }
21787    }
21788
21789    @Override
21790    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21791            FileDescriptor err, String[] args, ShellCallback callback,
21792            ResultReceiver resultReceiver) {
21793        (new PackageManagerShellCommand(this)).exec(
21794                this, in, out, err, args, callback, resultReceiver);
21795    }
21796
21797    @Override
21798    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21799        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21800
21801        DumpState dumpState = new DumpState();
21802        boolean fullPreferred = false;
21803        boolean checkin = false;
21804
21805        String packageName = null;
21806        ArraySet<String> permissionNames = null;
21807
21808        int opti = 0;
21809        while (opti < args.length) {
21810            String opt = args[opti];
21811            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21812                break;
21813            }
21814            opti++;
21815
21816            if ("-a".equals(opt)) {
21817                // Right now we only know how to print all.
21818            } else if ("-h".equals(opt)) {
21819                pw.println("Package manager dump options:");
21820                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21821                pw.println("    --checkin: dump for a checkin");
21822                pw.println("    -f: print details of intent filters");
21823                pw.println("    -h: print this help");
21824                pw.println("  cmd may be one of:");
21825                pw.println("    l[ibraries]: list known shared libraries");
21826                pw.println("    f[eatures]: list device features");
21827                pw.println("    k[eysets]: print known keysets");
21828                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21829                pw.println("    perm[issions]: dump permissions");
21830                pw.println("    permission [name ...]: dump declaration and use of given permission");
21831                pw.println("    pref[erred]: print preferred package settings");
21832                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21833                pw.println("    prov[iders]: dump content providers");
21834                pw.println("    p[ackages]: dump installed packages");
21835                pw.println("    s[hared-users]: dump shared user IDs");
21836                pw.println("    m[essages]: print collected runtime messages");
21837                pw.println("    v[erifiers]: print package verifier info");
21838                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21839                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21840                pw.println("    version: print database version info");
21841                pw.println("    write: write current settings now");
21842                pw.println("    installs: details about install sessions");
21843                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21844                pw.println("    dexopt: dump dexopt state");
21845                pw.println("    compiler-stats: dump compiler statistics");
21846                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21847                pw.println("    <package.name>: info about given package");
21848                return;
21849            } else if ("--checkin".equals(opt)) {
21850                checkin = true;
21851            } else if ("-f".equals(opt)) {
21852                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21853            } else if ("--proto".equals(opt)) {
21854                dumpProto(fd);
21855                return;
21856            } else {
21857                pw.println("Unknown argument: " + opt + "; use -h for help");
21858            }
21859        }
21860
21861        // Is the caller requesting to dump a particular piece of data?
21862        if (opti < args.length) {
21863            String cmd = args[opti];
21864            opti++;
21865            // Is this a package name?
21866            if ("android".equals(cmd) || cmd.contains(".")) {
21867                packageName = cmd;
21868                // When dumping a single package, we always dump all of its
21869                // filter information since the amount of data will be reasonable.
21870                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21871            } else if ("check-permission".equals(cmd)) {
21872                if (opti >= args.length) {
21873                    pw.println("Error: check-permission missing permission argument");
21874                    return;
21875                }
21876                String perm = args[opti];
21877                opti++;
21878                if (opti >= args.length) {
21879                    pw.println("Error: check-permission missing package argument");
21880                    return;
21881                }
21882
21883                String pkg = args[opti];
21884                opti++;
21885                int user = UserHandle.getUserId(Binder.getCallingUid());
21886                if (opti < args.length) {
21887                    try {
21888                        user = Integer.parseInt(args[opti]);
21889                    } catch (NumberFormatException e) {
21890                        pw.println("Error: check-permission user argument is not a number: "
21891                                + args[opti]);
21892                        return;
21893                    }
21894                }
21895
21896                // Normalize package name to handle renamed packages and static libs
21897                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21898
21899                pw.println(checkPermission(perm, pkg, user));
21900                return;
21901            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21902                dumpState.setDump(DumpState.DUMP_LIBS);
21903            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21904                dumpState.setDump(DumpState.DUMP_FEATURES);
21905            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21906                if (opti >= args.length) {
21907                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21908                            | DumpState.DUMP_SERVICE_RESOLVERS
21909                            | DumpState.DUMP_RECEIVER_RESOLVERS
21910                            | DumpState.DUMP_CONTENT_RESOLVERS);
21911                } else {
21912                    while (opti < args.length) {
21913                        String name = args[opti];
21914                        if ("a".equals(name) || "activity".equals(name)) {
21915                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21916                        } else if ("s".equals(name) || "service".equals(name)) {
21917                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21918                        } else if ("r".equals(name) || "receiver".equals(name)) {
21919                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21920                        } else if ("c".equals(name) || "content".equals(name)) {
21921                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21922                        } else {
21923                            pw.println("Error: unknown resolver table type: " + name);
21924                            return;
21925                        }
21926                        opti++;
21927                    }
21928                }
21929            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21930                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21931            } else if ("permission".equals(cmd)) {
21932                if (opti >= args.length) {
21933                    pw.println("Error: permission requires permission name");
21934                    return;
21935                }
21936                permissionNames = new ArraySet<>();
21937                while (opti < args.length) {
21938                    permissionNames.add(args[opti]);
21939                    opti++;
21940                }
21941                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21942                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21943            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21944                dumpState.setDump(DumpState.DUMP_PREFERRED);
21945            } else if ("preferred-xml".equals(cmd)) {
21946                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21947                if (opti < args.length && "--full".equals(args[opti])) {
21948                    fullPreferred = true;
21949                    opti++;
21950                }
21951            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21952                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21953            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21954                dumpState.setDump(DumpState.DUMP_PACKAGES);
21955            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21956                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21957            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21958                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21959            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21960                dumpState.setDump(DumpState.DUMP_MESSAGES);
21961            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21962                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21963            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21964                    || "intent-filter-verifiers".equals(cmd)) {
21965                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21966            } else if ("version".equals(cmd)) {
21967                dumpState.setDump(DumpState.DUMP_VERSION);
21968            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21969                dumpState.setDump(DumpState.DUMP_KEYSETS);
21970            } else if ("installs".equals(cmd)) {
21971                dumpState.setDump(DumpState.DUMP_INSTALLS);
21972            } else if ("frozen".equals(cmd)) {
21973                dumpState.setDump(DumpState.DUMP_FROZEN);
21974            } else if ("volumes".equals(cmd)) {
21975                dumpState.setDump(DumpState.DUMP_VOLUMES);
21976            } else if ("dexopt".equals(cmd)) {
21977                dumpState.setDump(DumpState.DUMP_DEXOPT);
21978            } else if ("compiler-stats".equals(cmd)) {
21979                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21980            } else if ("changes".equals(cmd)) {
21981                dumpState.setDump(DumpState.DUMP_CHANGES);
21982            } else if ("write".equals(cmd)) {
21983                synchronized (mPackages) {
21984                    mSettings.writeLPr();
21985                    pw.println("Settings written.");
21986                    return;
21987                }
21988            }
21989        }
21990
21991        if (checkin) {
21992            pw.println("vers,1");
21993        }
21994
21995        // reader
21996        synchronized (mPackages) {
21997            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21998                if (!checkin) {
21999                    if (dumpState.onTitlePrinted())
22000                        pw.println();
22001                    pw.println("Database versions:");
22002                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22003                }
22004            }
22005
22006            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22007                if (!checkin) {
22008                    if (dumpState.onTitlePrinted())
22009                        pw.println();
22010                    pw.println("Verifiers:");
22011                    pw.print("  Required: ");
22012                    pw.print(mRequiredVerifierPackage);
22013                    pw.print(" (uid=");
22014                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22015                            UserHandle.USER_SYSTEM));
22016                    pw.println(")");
22017                } else if (mRequiredVerifierPackage != null) {
22018                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22019                    pw.print(",");
22020                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22021                            UserHandle.USER_SYSTEM));
22022                }
22023            }
22024
22025            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22026                    packageName == null) {
22027                if (mIntentFilterVerifierComponent != null) {
22028                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22029                    if (!checkin) {
22030                        if (dumpState.onTitlePrinted())
22031                            pw.println();
22032                        pw.println("Intent Filter Verifier:");
22033                        pw.print("  Using: ");
22034                        pw.print(verifierPackageName);
22035                        pw.print(" (uid=");
22036                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22037                                UserHandle.USER_SYSTEM));
22038                        pw.println(")");
22039                    } else if (verifierPackageName != null) {
22040                        pw.print("ifv,"); pw.print(verifierPackageName);
22041                        pw.print(",");
22042                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22043                                UserHandle.USER_SYSTEM));
22044                    }
22045                } else {
22046                    pw.println();
22047                    pw.println("No Intent Filter Verifier available!");
22048                }
22049            }
22050
22051            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22052                boolean printedHeader = false;
22053                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22054                while (it.hasNext()) {
22055                    String libName = it.next();
22056                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22057                    if (versionedLib == null) {
22058                        continue;
22059                    }
22060                    final int versionCount = versionedLib.size();
22061                    for (int i = 0; i < versionCount; i++) {
22062                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22063                        if (!checkin) {
22064                            if (!printedHeader) {
22065                                if (dumpState.onTitlePrinted())
22066                                    pw.println();
22067                                pw.println("Libraries:");
22068                                printedHeader = true;
22069                            }
22070                            pw.print("  ");
22071                        } else {
22072                            pw.print("lib,");
22073                        }
22074                        pw.print(libEntry.info.getName());
22075                        if (libEntry.info.isStatic()) {
22076                            pw.print(" version=" + libEntry.info.getVersion());
22077                        }
22078                        if (!checkin) {
22079                            pw.print(" -> ");
22080                        }
22081                        if (libEntry.path != null) {
22082                            pw.print(" (jar) ");
22083                            pw.print(libEntry.path);
22084                        } else {
22085                            pw.print(" (apk) ");
22086                            pw.print(libEntry.apk);
22087                        }
22088                        pw.println();
22089                    }
22090                }
22091            }
22092
22093            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22094                if (dumpState.onTitlePrinted())
22095                    pw.println();
22096                if (!checkin) {
22097                    pw.println("Features:");
22098                }
22099
22100                synchronized (mAvailableFeatures) {
22101                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22102                        if (checkin) {
22103                            pw.print("feat,");
22104                            pw.print(feat.name);
22105                            pw.print(",");
22106                            pw.println(feat.version);
22107                        } else {
22108                            pw.print("  ");
22109                            pw.print(feat.name);
22110                            if (feat.version > 0) {
22111                                pw.print(" version=");
22112                                pw.print(feat.version);
22113                            }
22114                            pw.println();
22115                        }
22116                    }
22117                }
22118            }
22119
22120            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22121                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22122                        : "Activity Resolver Table:", "  ", packageName,
22123                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22124                    dumpState.setTitlePrinted(true);
22125                }
22126            }
22127            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22128                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22129                        : "Receiver Resolver Table:", "  ", packageName,
22130                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22131                    dumpState.setTitlePrinted(true);
22132                }
22133            }
22134            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22135                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22136                        : "Service Resolver Table:", "  ", packageName,
22137                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22138                    dumpState.setTitlePrinted(true);
22139                }
22140            }
22141            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22142                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22143                        : "Provider Resolver Table:", "  ", packageName,
22144                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22145                    dumpState.setTitlePrinted(true);
22146                }
22147            }
22148
22149            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22150                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22151                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22152                    int user = mSettings.mPreferredActivities.keyAt(i);
22153                    if (pir.dump(pw,
22154                            dumpState.getTitlePrinted()
22155                                ? "\nPreferred Activities User " + user + ":"
22156                                : "Preferred Activities User " + user + ":", "  ",
22157                            packageName, true, false)) {
22158                        dumpState.setTitlePrinted(true);
22159                    }
22160                }
22161            }
22162
22163            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22164                pw.flush();
22165                FileOutputStream fout = new FileOutputStream(fd);
22166                BufferedOutputStream str = new BufferedOutputStream(fout);
22167                XmlSerializer serializer = new FastXmlSerializer();
22168                try {
22169                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22170                    serializer.startDocument(null, true);
22171                    serializer.setFeature(
22172                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22173                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22174                    serializer.endDocument();
22175                    serializer.flush();
22176                } catch (IllegalArgumentException e) {
22177                    pw.println("Failed writing: " + e);
22178                } catch (IllegalStateException e) {
22179                    pw.println("Failed writing: " + e);
22180                } catch (IOException e) {
22181                    pw.println("Failed writing: " + e);
22182                }
22183            }
22184
22185            if (!checkin
22186                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22187                    && packageName == null) {
22188                pw.println();
22189                int count = mSettings.mPackages.size();
22190                if (count == 0) {
22191                    pw.println("No applications!");
22192                    pw.println();
22193                } else {
22194                    final String prefix = "  ";
22195                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22196                    if (allPackageSettings.size() == 0) {
22197                        pw.println("No domain preferred apps!");
22198                        pw.println();
22199                    } else {
22200                        pw.println("App verification status:");
22201                        pw.println();
22202                        count = 0;
22203                        for (PackageSetting ps : allPackageSettings) {
22204                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22205                            if (ivi == null || ivi.getPackageName() == null) continue;
22206                            pw.println(prefix + "Package: " + ivi.getPackageName());
22207                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22208                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22209                            pw.println();
22210                            count++;
22211                        }
22212                        if (count == 0) {
22213                            pw.println(prefix + "No app verification established.");
22214                            pw.println();
22215                        }
22216                        for (int userId : sUserManager.getUserIds()) {
22217                            pw.println("App linkages for user " + userId + ":");
22218                            pw.println();
22219                            count = 0;
22220                            for (PackageSetting ps : allPackageSettings) {
22221                                final long status = ps.getDomainVerificationStatusForUser(userId);
22222                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22223                                        && !DEBUG_DOMAIN_VERIFICATION) {
22224                                    continue;
22225                                }
22226                                pw.println(prefix + "Package: " + ps.name);
22227                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22228                                String statusStr = IntentFilterVerificationInfo.
22229                                        getStatusStringFromValue(status);
22230                                pw.println(prefix + "Status:  " + statusStr);
22231                                pw.println();
22232                                count++;
22233                            }
22234                            if (count == 0) {
22235                                pw.println(prefix + "No configured app linkages.");
22236                                pw.println();
22237                            }
22238                        }
22239                    }
22240                }
22241            }
22242
22243            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22244                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22245                if (packageName == null && permissionNames == null) {
22246                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22247                        if (iperm == 0) {
22248                            if (dumpState.onTitlePrinted())
22249                                pw.println();
22250                            pw.println("AppOp Permissions:");
22251                        }
22252                        pw.print("  AppOp Permission ");
22253                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22254                        pw.println(":");
22255                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22256                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22257                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22258                        }
22259                    }
22260                }
22261            }
22262
22263            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22264                boolean printedSomething = false;
22265                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22266                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22267                        continue;
22268                    }
22269                    if (!printedSomething) {
22270                        if (dumpState.onTitlePrinted())
22271                            pw.println();
22272                        pw.println("Registered ContentProviders:");
22273                        printedSomething = true;
22274                    }
22275                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22276                    pw.print("    "); pw.println(p.toString());
22277                }
22278                printedSomething = false;
22279                for (Map.Entry<String, PackageParser.Provider> entry :
22280                        mProvidersByAuthority.entrySet()) {
22281                    PackageParser.Provider p = entry.getValue();
22282                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22283                        continue;
22284                    }
22285                    if (!printedSomething) {
22286                        if (dumpState.onTitlePrinted())
22287                            pw.println();
22288                        pw.println("ContentProvider Authorities:");
22289                        printedSomething = true;
22290                    }
22291                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22292                    pw.print("    "); pw.println(p.toString());
22293                    if (p.info != null && p.info.applicationInfo != null) {
22294                        final String appInfo = p.info.applicationInfo.toString();
22295                        pw.print("      applicationInfo="); pw.println(appInfo);
22296                    }
22297                }
22298            }
22299
22300            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22301                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22302            }
22303
22304            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22305                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22306            }
22307
22308            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22309                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22310            }
22311
22312            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22313                if (dumpState.onTitlePrinted()) pw.println();
22314                pw.println("Package Changes:");
22315                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22316                final int K = mChangedPackages.size();
22317                for (int i = 0; i < K; i++) {
22318                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22319                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22320                    final int N = changes.size();
22321                    if (N == 0) {
22322                        pw.print("    "); pw.println("No packages changed");
22323                    } else {
22324                        for (int j = 0; j < N; j++) {
22325                            final String pkgName = changes.valueAt(j);
22326                            final int sequenceNumber = changes.keyAt(j);
22327                            pw.print("    ");
22328                            pw.print("seq=");
22329                            pw.print(sequenceNumber);
22330                            pw.print(", package=");
22331                            pw.println(pkgName);
22332                        }
22333                    }
22334                }
22335            }
22336
22337            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22338                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22339            }
22340
22341            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22342                // XXX should handle packageName != null by dumping only install data that
22343                // the given package is involved with.
22344                if (dumpState.onTitlePrinted()) pw.println();
22345
22346                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22347                ipw.println();
22348                ipw.println("Frozen packages:");
22349                ipw.increaseIndent();
22350                if (mFrozenPackages.size() == 0) {
22351                    ipw.println("(none)");
22352                } else {
22353                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22354                        ipw.println(mFrozenPackages.valueAt(i));
22355                    }
22356                }
22357                ipw.decreaseIndent();
22358            }
22359
22360            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22361                if (dumpState.onTitlePrinted()) pw.println();
22362
22363                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22364                ipw.println();
22365                ipw.println("Loaded volumes:");
22366                ipw.increaseIndent();
22367                if (mLoadedVolumes.size() == 0) {
22368                    ipw.println("(none)");
22369                } else {
22370                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22371                        ipw.println(mLoadedVolumes.valueAt(i));
22372                    }
22373                }
22374                ipw.decreaseIndent();
22375            }
22376
22377            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22378                if (dumpState.onTitlePrinted()) pw.println();
22379                dumpDexoptStateLPr(pw, packageName);
22380            }
22381
22382            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22383                if (dumpState.onTitlePrinted()) pw.println();
22384                dumpCompilerStatsLPr(pw, packageName);
22385            }
22386
22387            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22388                if (dumpState.onTitlePrinted()) pw.println();
22389                mSettings.dumpReadMessagesLPr(pw, dumpState);
22390
22391                pw.println();
22392                pw.println("Package warning messages:");
22393                BufferedReader in = null;
22394                String line = null;
22395                try {
22396                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22397                    while ((line = in.readLine()) != null) {
22398                        if (line.contains("ignored: updated version")) continue;
22399                        pw.println(line);
22400                    }
22401                } catch (IOException ignored) {
22402                } finally {
22403                    IoUtils.closeQuietly(in);
22404                }
22405            }
22406
22407            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22408                BufferedReader in = null;
22409                String line = null;
22410                try {
22411                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22412                    while ((line = in.readLine()) != null) {
22413                        if (line.contains("ignored: updated version")) continue;
22414                        pw.print("msg,");
22415                        pw.println(line);
22416                    }
22417                } catch (IOException ignored) {
22418                } finally {
22419                    IoUtils.closeQuietly(in);
22420                }
22421            }
22422        }
22423
22424        // PackageInstaller should be called outside of mPackages lock
22425        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22426            // XXX should handle packageName != null by dumping only install data that
22427            // the given package is involved with.
22428            if (dumpState.onTitlePrinted()) pw.println();
22429            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22430        }
22431    }
22432
22433    private void dumpProto(FileDescriptor fd) {
22434        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22435
22436        synchronized (mPackages) {
22437            final long requiredVerifierPackageToken =
22438                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22439            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22440            proto.write(
22441                    PackageServiceDumpProto.PackageShortProto.UID,
22442                    getPackageUid(
22443                            mRequiredVerifierPackage,
22444                            MATCH_DEBUG_TRIAGED_MISSING,
22445                            UserHandle.USER_SYSTEM));
22446            proto.end(requiredVerifierPackageToken);
22447
22448            if (mIntentFilterVerifierComponent != null) {
22449                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22450                final long verifierPackageToken =
22451                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22452                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22453                proto.write(
22454                        PackageServiceDumpProto.PackageShortProto.UID,
22455                        getPackageUid(
22456                                verifierPackageName,
22457                                MATCH_DEBUG_TRIAGED_MISSING,
22458                                UserHandle.USER_SYSTEM));
22459                proto.end(verifierPackageToken);
22460            }
22461
22462            dumpSharedLibrariesProto(proto);
22463            dumpFeaturesProto(proto);
22464            mSettings.dumpPackagesProto(proto);
22465            mSettings.dumpSharedUsersProto(proto);
22466            dumpMessagesProto(proto);
22467        }
22468        proto.flush();
22469    }
22470
22471    private void dumpMessagesProto(ProtoOutputStream proto) {
22472        BufferedReader in = null;
22473        String line = null;
22474        try {
22475            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22476            while ((line = in.readLine()) != null) {
22477                if (line.contains("ignored: updated version")) continue;
22478                proto.write(PackageServiceDumpProto.MESSAGES, line);
22479            }
22480        } catch (IOException ignored) {
22481        } finally {
22482            IoUtils.closeQuietly(in);
22483        }
22484    }
22485
22486    private void dumpFeaturesProto(ProtoOutputStream proto) {
22487        synchronized (mAvailableFeatures) {
22488            final int count = mAvailableFeatures.size();
22489            for (int i = 0; i < count; i++) {
22490                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22491                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22492                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22493                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22494                proto.end(featureToken);
22495            }
22496        }
22497    }
22498
22499    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22500        final int count = mSharedLibraries.size();
22501        for (int i = 0; i < count; i++) {
22502            final String libName = mSharedLibraries.keyAt(i);
22503            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22504            if (versionedLib == null) {
22505                continue;
22506            }
22507            final int versionCount = versionedLib.size();
22508            for (int j = 0; j < versionCount; j++) {
22509                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22510                final long sharedLibraryToken =
22511                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22512                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22513                final boolean isJar = (libEntry.path != null);
22514                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22515                if (isJar) {
22516                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22517                } else {
22518                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22519                }
22520                proto.end(sharedLibraryToken);
22521            }
22522        }
22523    }
22524
22525    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22526        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22527        ipw.println();
22528        ipw.println("Dexopt state:");
22529        ipw.increaseIndent();
22530        Collection<PackageParser.Package> packages = null;
22531        if (packageName != null) {
22532            PackageParser.Package targetPackage = mPackages.get(packageName);
22533            if (targetPackage != null) {
22534                packages = Collections.singletonList(targetPackage);
22535            } else {
22536                ipw.println("Unable to find package: " + packageName);
22537                return;
22538            }
22539        } else {
22540            packages = mPackages.values();
22541        }
22542
22543        for (PackageParser.Package pkg : packages) {
22544            ipw.println("[" + pkg.packageName + "]");
22545            ipw.increaseIndent();
22546            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22547            ipw.decreaseIndent();
22548        }
22549    }
22550
22551    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22552        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22553        ipw.println();
22554        ipw.println("Compiler stats:");
22555        ipw.increaseIndent();
22556        Collection<PackageParser.Package> packages = null;
22557        if (packageName != null) {
22558            PackageParser.Package targetPackage = mPackages.get(packageName);
22559            if (targetPackage != null) {
22560                packages = Collections.singletonList(targetPackage);
22561            } else {
22562                ipw.println("Unable to find package: " + packageName);
22563                return;
22564            }
22565        } else {
22566            packages = mPackages.values();
22567        }
22568
22569        for (PackageParser.Package pkg : packages) {
22570            ipw.println("[" + pkg.packageName + "]");
22571            ipw.increaseIndent();
22572
22573            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22574            if (stats == null) {
22575                ipw.println("(No recorded stats)");
22576            } else {
22577                stats.dump(ipw);
22578            }
22579            ipw.decreaseIndent();
22580        }
22581    }
22582
22583    private String dumpDomainString(String packageName) {
22584        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22585                .getList();
22586        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22587
22588        ArraySet<String> result = new ArraySet<>();
22589        if (iviList.size() > 0) {
22590            for (IntentFilterVerificationInfo ivi : iviList) {
22591                for (String host : ivi.getDomains()) {
22592                    result.add(host);
22593                }
22594            }
22595        }
22596        if (filters != null && filters.size() > 0) {
22597            for (IntentFilter filter : filters) {
22598                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22599                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22600                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22601                    result.addAll(filter.getHostsList());
22602                }
22603            }
22604        }
22605
22606        StringBuilder sb = new StringBuilder(result.size() * 16);
22607        for (String domain : result) {
22608            if (sb.length() > 0) sb.append(" ");
22609            sb.append(domain);
22610        }
22611        return sb.toString();
22612    }
22613
22614    // ------- apps on sdcard specific code -------
22615    static final boolean DEBUG_SD_INSTALL = false;
22616
22617    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22618
22619    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22620
22621    private boolean mMediaMounted = false;
22622
22623    static String getEncryptKey() {
22624        try {
22625            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22626                    SD_ENCRYPTION_KEYSTORE_NAME);
22627            if (sdEncKey == null) {
22628                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22629                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22630                if (sdEncKey == null) {
22631                    Slog.e(TAG, "Failed to create encryption keys");
22632                    return null;
22633                }
22634            }
22635            return sdEncKey;
22636        } catch (NoSuchAlgorithmException nsae) {
22637            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22638            return null;
22639        } catch (IOException ioe) {
22640            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22641            return null;
22642        }
22643    }
22644
22645    /*
22646     * Update media status on PackageManager.
22647     */
22648    @Override
22649    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22650        enforceSystemOrRoot("Media status can only be updated by the system");
22651        // reader; this apparently protects mMediaMounted, but should probably
22652        // be a different lock in that case.
22653        synchronized (mPackages) {
22654            Log.i(TAG, "Updating external media status from "
22655                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22656                    + (mediaStatus ? "mounted" : "unmounted"));
22657            if (DEBUG_SD_INSTALL)
22658                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22659                        + ", mMediaMounted=" + mMediaMounted);
22660            if (mediaStatus == mMediaMounted) {
22661                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22662                        : 0, -1);
22663                mHandler.sendMessage(msg);
22664                return;
22665            }
22666            mMediaMounted = mediaStatus;
22667        }
22668        // Queue up an async operation since the package installation may take a
22669        // little while.
22670        mHandler.post(new Runnable() {
22671            public void run() {
22672                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22673            }
22674        });
22675    }
22676
22677    /**
22678     * Called by StorageManagerService when the initial ASECs to scan are available.
22679     * Should block until all the ASEC containers are finished being scanned.
22680     */
22681    public void scanAvailableAsecs() {
22682        updateExternalMediaStatusInner(true, false, false);
22683    }
22684
22685    /*
22686     * Collect information of applications on external media, map them against
22687     * existing containers and update information based on current mount status.
22688     * Please note that we always have to report status if reportStatus has been
22689     * set to true especially when unloading packages.
22690     */
22691    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22692            boolean externalStorage) {
22693        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22694        int[] uidArr = EmptyArray.INT;
22695
22696        final String[] list = PackageHelper.getSecureContainerList();
22697        if (ArrayUtils.isEmpty(list)) {
22698            Log.i(TAG, "No secure containers found");
22699        } else {
22700            // Process list of secure containers and categorize them
22701            // as active or stale based on their package internal state.
22702
22703            // reader
22704            synchronized (mPackages) {
22705                for (String cid : list) {
22706                    // Leave stages untouched for now; installer service owns them
22707                    if (PackageInstallerService.isStageName(cid)) continue;
22708
22709                    if (DEBUG_SD_INSTALL)
22710                        Log.i(TAG, "Processing container " + cid);
22711                    String pkgName = getAsecPackageName(cid);
22712                    if (pkgName == null) {
22713                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22714                        continue;
22715                    }
22716                    if (DEBUG_SD_INSTALL)
22717                        Log.i(TAG, "Looking for pkg : " + pkgName);
22718
22719                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22720                    if (ps == null) {
22721                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22722                        continue;
22723                    }
22724
22725                    /*
22726                     * Skip packages that are not external if we're unmounting
22727                     * external storage.
22728                     */
22729                    if (externalStorage && !isMounted && !isExternal(ps)) {
22730                        continue;
22731                    }
22732
22733                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22734                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22735                    // The package status is changed only if the code path
22736                    // matches between settings and the container id.
22737                    if (ps.codePathString != null
22738                            && ps.codePathString.startsWith(args.getCodePath())) {
22739                        if (DEBUG_SD_INSTALL) {
22740                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22741                                    + " at code path: " + ps.codePathString);
22742                        }
22743
22744                        // We do have a valid package installed on sdcard
22745                        processCids.put(args, ps.codePathString);
22746                        final int uid = ps.appId;
22747                        if (uid != -1) {
22748                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22749                        }
22750                    } else {
22751                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22752                                + ps.codePathString);
22753                    }
22754                }
22755            }
22756
22757            Arrays.sort(uidArr);
22758        }
22759
22760        // Process packages with valid entries.
22761        if (isMounted) {
22762            if (DEBUG_SD_INSTALL)
22763                Log.i(TAG, "Loading packages");
22764            loadMediaPackages(processCids, uidArr, externalStorage);
22765            startCleaningPackages();
22766            mInstallerService.onSecureContainersAvailable();
22767        } else {
22768            if (DEBUG_SD_INSTALL)
22769                Log.i(TAG, "Unloading packages");
22770            unloadMediaPackages(processCids, uidArr, reportStatus);
22771        }
22772    }
22773
22774    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22775            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22776        final int size = infos.size();
22777        final String[] packageNames = new String[size];
22778        final int[] packageUids = new int[size];
22779        for (int i = 0; i < size; i++) {
22780            final ApplicationInfo info = infos.get(i);
22781            packageNames[i] = info.packageName;
22782            packageUids[i] = info.uid;
22783        }
22784        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22785                finishedReceiver);
22786    }
22787
22788    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22789            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22790        sendResourcesChangedBroadcast(mediaStatus, replacing,
22791                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22792    }
22793
22794    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22795            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22796        int size = pkgList.length;
22797        if (size > 0) {
22798            // Send broadcasts here
22799            Bundle extras = new Bundle();
22800            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22801            if (uidArr != null) {
22802                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22803            }
22804            if (replacing) {
22805                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22806            }
22807            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22808                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22809            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22810        }
22811    }
22812
22813   /*
22814     * Look at potentially valid container ids from processCids If package
22815     * information doesn't match the one on record or package scanning fails,
22816     * the cid is added to list of removeCids. We currently don't delete stale
22817     * containers.
22818     */
22819    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22820            boolean externalStorage) {
22821        ArrayList<String> pkgList = new ArrayList<String>();
22822        Set<AsecInstallArgs> keys = processCids.keySet();
22823
22824        for (AsecInstallArgs args : keys) {
22825            String codePath = processCids.get(args);
22826            if (DEBUG_SD_INSTALL)
22827                Log.i(TAG, "Loading container : " + args.cid);
22828            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22829            try {
22830                // Make sure there are no container errors first.
22831                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22832                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22833                            + " when installing from sdcard");
22834                    continue;
22835                }
22836                // Check code path here.
22837                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22838                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22839                            + " does not match one in settings " + codePath);
22840                    continue;
22841                }
22842                // Parse package
22843                int parseFlags = mDefParseFlags;
22844                if (args.isExternalAsec()) {
22845                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22846                }
22847                if (args.isFwdLocked()) {
22848                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22849                }
22850
22851                synchronized (mInstallLock) {
22852                    PackageParser.Package pkg = null;
22853                    try {
22854                        // Sadly we don't know the package name yet to freeze it
22855                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22856                                SCAN_IGNORE_FROZEN, 0, null);
22857                    } catch (PackageManagerException e) {
22858                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22859                    }
22860                    // Scan the package
22861                    if (pkg != null) {
22862                        /*
22863                         * TODO why is the lock being held? doPostInstall is
22864                         * called in other places without the lock. This needs
22865                         * to be straightened out.
22866                         */
22867                        // writer
22868                        synchronized (mPackages) {
22869                            retCode = PackageManager.INSTALL_SUCCEEDED;
22870                            pkgList.add(pkg.packageName);
22871                            // Post process args
22872                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22873                                    pkg.applicationInfo.uid);
22874                        }
22875                    } else {
22876                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22877                    }
22878                }
22879
22880            } finally {
22881                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22882                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22883                }
22884            }
22885        }
22886        // writer
22887        synchronized (mPackages) {
22888            // If the platform SDK has changed since the last time we booted,
22889            // we need to re-grant app permission to catch any new ones that
22890            // appear. This is really a hack, and means that apps can in some
22891            // cases get permissions that the user didn't initially explicitly
22892            // allow... it would be nice to have some better way to handle
22893            // this situation.
22894            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22895                    : mSettings.getInternalVersion();
22896            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22897                    : StorageManager.UUID_PRIVATE_INTERNAL;
22898
22899            int updateFlags = UPDATE_PERMISSIONS_ALL;
22900            if (ver.sdkVersion != mSdkVersion) {
22901                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22902                        + mSdkVersion + "; regranting permissions for external");
22903                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22904            }
22905            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22906
22907            // Yay, everything is now upgraded
22908            ver.forceCurrent();
22909
22910            // can downgrade to reader
22911            // Persist settings
22912            mSettings.writeLPr();
22913        }
22914        // Send a broadcast to let everyone know we are done processing
22915        if (pkgList.size() > 0) {
22916            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22917        }
22918    }
22919
22920   /*
22921     * Utility method to unload a list of specified containers
22922     */
22923    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22924        // Just unmount all valid containers.
22925        for (AsecInstallArgs arg : cidArgs) {
22926            synchronized (mInstallLock) {
22927                arg.doPostDeleteLI(false);
22928           }
22929       }
22930   }
22931
22932    /*
22933     * Unload packages mounted on external media. This involves deleting package
22934     * data from internal structures, sending broadcasts about disabled packages,
22935     * gc'ing to free up references, unmounting all secure containers
22936     * corresponding to packages on external media, and posting a
22937     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22938     * that we always have to post this message if status has been requested no
22939     * matter what.
22940     */
22941    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22942            final boolean reportStatus) {
22943        if (DEBUG_SD_INSTALL)
22944            Log.i(TAG, "unloading media packages");
22945        ArrayList<String> pkgList = new ArrayList<String>();
22946        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22947        final Set<AsecInstallArgs> keys = processCids.keySet();
22948        for (AsecInstallArgs args : keys) {
22949            String pkgName = args.getPackageName();
22950            if (DEBUG_SD_INSTALL)
22951                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22952            // Delete package internally
22953            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22954            synchronized (mInstallLock) {
22955                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22956                final boolean res;
22957                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22958                        "unloadMediaPackages")) {
22959                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22960                            null);
22961                }
22962                if (res) {
22963                    pkgList.add(pkgName);
22964                } else {
22965                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22966                    failedList.add(args);
22967                }
22968            }
22969        }
22970
22971        // reader
22972        synchronized (mPackages) {
22973            // We didn't update the settings after removing each package;
22974            // write them now for all packages.
22975            mSettings.writeLPr();
22976        }
22977
22978        // We have to absolutely send UPDATED_MEDIA_STATUS only
22979        // after confirming that all the receivers processed the ordered
22980        // broadcast when packages get disabled, force a gc to clean things up.
22981        // and unload all the containers.
22982        if (pkgList.size() > 0) {
22983            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22984                    new IIntentReceiver.Stub() {
22985                public void performReceive(Intent intent, int resultCode, String data,
22986                        Bundle extras, boolean ordered, boolean sticky,
22987                        int sendingUser) throws RemoteException {
22988                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22989                            reportStatus ? 1 : 0, 1, keys);
22990                    mHandler.sendMessage(msg);
22991                }
22992            });
22993        } else {
22994            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22995                    keys);
22996            mHandler.sendMessage(msg);
22997        }
22998    }
22999
23000    private void loadPrivatePackages(final VolumeInfo vol) {
23001        mHandler.post(new Runnable() {
23002            @Override
23003            public void run() {
23004                loadPrivatePackagesInner(vol);
23005            }
23006        });
23007    }
23008
23009    private void loadPrivatePackagesInner(VolumeInfo vol) {
23010        final String volumeUuid = vol.fsUuid;
23011        if (TextUtils.isEmpty(volumeUuid)) {
23012            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23013            return;
23014        }
23015
23016        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23017        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23018        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23019
23020        final VersionInfo ver;
23021        final List<PackageSetting> packages;
23022        synchronized (mPackages) {
23023            ver = mSettings.findOrCreateVersion(volumeUuid);
23024            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23025        }
23026
23027        for (PackageSetting ps : packages) {
23028            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23029            synchronized (mInstallLock) {
23030                final PackageParser.Package pkg;
23031                try {
23032                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23033                    loaded.add(pkg.applicationInfo);
23034
23035                } catch (PackageManagerException e) {
23036                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23037                }
23038
23039                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23040                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23041                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23042                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23043                }
23044            }
23045        }
23046
23047        // Reconcile app data for all started/unlocked users
23048        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23049        final UserManager um = mContext.getSystemService(UserManager.class);
23050        UserManagerInternal umInternal = getUserManagerInternal();
23051        for (UserInfo user : um.getUsers()) {
23052            final int flags;
23053            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23054                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23055            } else if (umInternal.isUserRunning(user.id)) {
23056                flags = StorageManager.FLAG_STORAGE_DE;
23057            } else {
23058                continue;
23059            }
23060
23061            try {
23062                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23063                synchronized (mInstallLock) {
23064                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23065                }
23066            } catch (IllegalStateException e) {
23067                // Device was probably ejected, and we'll process that event momentarily
23068                Slog.w(TAG, "Failed to prepare storage: " + e);
23069            }
23070        }
23071
23072        synchronized (mPackages) {
23073            int updateFlags = UPDATE_PERMISSIONS_ALL;
23074            if (ver.sdkVersion != mSdkVersion) {
23075                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23076                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23077                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23078            }
23079            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23080
23081            // Yay, everything is now upgraded
23082            ver.forceCurrent();
23083
23084            mSettings.writeLPr();
23085        }
23086
23087        for (PackageFreezer freezer : freezers) {
23088            freezer.close();
23089        }
23090
23091        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23092        sendResourcesChangedBroadcast(true, false, loaded, null);
23093        mLoadedVolumes.add(vol.getId());
23094    }
23095
23096    private void unloadPrivatePackages(final VolumeInfo vol) {
23097        mHandler.post(new Runnable() {
23098            @Override
23099            public void run() {
23100                unloadPrivatePackagesInner(vol);
23101            }
23102        });
23103    }
23104
23105    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23106        final String volumeUuid = vol.fsUuid;
23107        if (TextUtils.isEmpty(volumeUuid)) {
23108            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23109            return;
23110        }
23111
23112        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23113        synchronized (mInstallLock) {
23114        synchronized (mPackages) {
23115            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23116            for (PackageSetting ps : packages) {
23117                if (ps.pkg == null) continue;
23118
23119                final ApplicationInfo info = ps.pkg.applicationInfo;
23120                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23121                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23122
23123                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23124                        "unloadPrivatePackagesInner")) {
23125                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23126                            false, null)) {
23127                        unloaded.add(info);
23128                    } else {
23129                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23130                    }
23131                }
23132
23133                // Try very hard to release any references to this package
23134                // so we don't risk the system server being killed due to
23135                // open FDs
23136                AttributeCache.instance().removePackage(ps.name);
23137            }
23138
23139            mSettings.writeLPr();
23140        }
23141        }
23142
23143        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23144        sendResourcesChangedBroadcast(false, false, unloaded, null);
23145        mLoadedVolumes.remove(vol.getId());
23146
23147        // Try very hard to release any references to this path so we don't risk
23148        // the system server being killed due to open FDs
23149        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23150
23151        for (int i = 0; i < 3; i++) {
23152            System.gc();
23153            System.runFinalization();
23154        }
23155    }
23156
23157    private void assertPackageKnown(String volumeUuid, String packageName)
23158            throws PackageManagerException {
23159        synchronized (mPackages) {
23160            // Normalize package name to handle renamed packages
23161            packageName = normalizePackageNameLPr(packageName);
23162
23163            final PackageSetting ps = mSettings.mPackages.get(packageName);
23164            if (ps == null) {
23165                throw new PackageManagerException("Package " + packageName + " is unknown");
23166            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23167                throw new PackageManagerException(
23168                        "Package " + packageName + " found on unknown volume " + volumeUuid
23169                                + "; expected volume " + ps.volumeUuid);
23170            }
23171        }
23172    }
23173
23174    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23175            throws PackageManagerException {
23176        synchronized (mPackages) {
23177            // Normalize package name to handle renamed packages
23178            packageName = normalizePackageNameLPr(packageName);
23179
23180            final PackageSetting ps = mSettings.mPackages.get(packageName);
23181            if (ps == null) {
23182                throw new PackageManagerException("Package " + packageName + " is unknown");
23183            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23184                throw new PackageManagerException(
23185                        "Package " + packageName + " found on unknown volume " + volumeUuid
23186                                + "; expected volume " + ps.volumeUuid);
23187            } else if (!ps.getInstalled(userId)) {
23188                throw new PackageManagerException(
23189                        "Package " + packageName + " not installed for user " + userId);
23190            }
23191        }
23192    }
23193
23194    private List<String> collectAbsoluteCodePaths() {
23195        synchronized (mPackages) {
23196            List<String> codePaths = new ArrayList<>();
23197            final int packageCount = mSettings.mPackages.size();
23198            for (int i = 0; i < packageCount; i++) {
23199                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23200                codePaths.add(ps.codePath.getAbsolutePath());
23201            }
23202            return codePaths;
23203        }
23204    }
23205
23206    /**
23207     * Examine all apps present on given mounted volume, and destroy apps that
23208     * aren't expected, either due to uninstallation or reinstallation on
23209     * another volume.
23210     */
23211    private void reconcileApps(String volumeUuid) {
23212        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23213        List<File> filesToDelete = null;
23214
23215        final File[] files = FileUtils.listFilesOrEmpty(
23216                Environment.getDataAppDirectory(volumeUuid));
23217        for (File file : files) {
23218            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23219                    && !PackageInstallerService.isStageName(file.getName());
23220            if (!isPackage) {
23221                // Ignore entries which are not packages
23222                continue;
23223            }
23224
23225            String absolutePath = file.getAbsolutePath();
23226
23227            boolean pathValid = false;
23228            final int absoluteCodePathCount = absoluteCodePaths.size();
23229            for (int i = 0; i < absoluteCodePathCount; i++) {
23230                String absoluteCodePath = absoluteCodePaths.get(i);
23231                if (absolutePath.startsWith(absoluteCodePath)) {
23232                    pathValid = true;
23233                    break;
23234                }
23235            }
23236
23237            if (!pathValid) {
23238                if (filesToDelete == null) {
23239                    filesToDelete = new ArrayList<>();
23240                }
23241                filesToDelete.add(file);
23242            }
23243        }
23244
23245        if (filesToDelete != null) {
23246            final int fileToDeleteCount = filesToDelete.size();
23247            for (int i = 0; i < fileToDeleteCount; i++) {
23248                File fileToDelete = filesToDelete.get(i);
23249                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23250                synchronized (mInstallLock) {
23251                    removeCodePathLI(fileToDelete);
23252                }
23253            }
23254        }
23255    }
23256
23257    /**
23258     * Reconcile all app data for the given user.
23259     * <p>
23260     * Verifies that directories exist and that ownership and labeling is
23261     * correct for all installed apps on all mounted volumes.
23262     */
23263    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23264        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23265        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23266            final String volumeUuid = vol.getFsUuid();
23267            synchronized (mInstallLock) {
23268                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23269            }
23270        }
23271    }
23272
23273    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23274            boolean migrateAppData) {
23275        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23276    }
23277
23278    /**
23279     * Reconcile all app data on given mounted volume.
23280     * <p>
23281     * Destroys app data that isn't expected, either due to uninstallation or
23282     * reinstallation on another volume.
23283     * <p>
23284     * Verifies that directories exist and that ownership and labeling is
23285     * correct for all installed apps.
23286     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23287     */
23288    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23289            boolean migrateAppData, boolean onlyCoreApps) {
23290        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23291                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23292        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23293
23294        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23295        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23296
23297        // First look for stale data that doesn't belong, and check if things
23298        // have changed since we did our last restorecon
23299        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23300            if (StorageManager.isFileEncryptedNativeOrEmulated()
23301                    && !StorageManager.isUserKeyUnlocked(userId)) {
23302                throw new RuntimeException(
23303                        "Yikes, someone asked us to reconcile CE storage while " + userId
23304                                + " was still locked; this would have caused massive data loss!");
23305            }
23306
23307            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23308            for (File file : files) {
23309                final String packageName = file.getName();
23310                try {
23311                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23312                } catch (PackageManagerException e) {
23313                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23314                    try {
23315                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23316                                StorageManager.FLAG_STORAGE_CE, 0);
23317                    } catch (InstallerException e2) {
23318                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23319                    }
23320                }
23321            }
23322        }
23323        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23324            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23325            for (File file : files) {
23326                final String packageName = file.getName();
23327                try {
23328                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23329                } catch (PackageManagerException e) {
23330                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23331                    try {
23332                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23333                                StorageManager.FLAG_STORAGE_DE, 0);
23334                    } catch (InstallerException e2) {
23335                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23336                    }
23337                }
23338            }
23339        }
23340
23341        // Ensure that data directories are ready to roll for all packages
23342        // installed for this volume and user
23343        final List<PackageSetting> packages;
23344        synchronized (mPackages) {
23345            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23346        }
23347        int preparedCount = 0;
23348        for (PackageSetting ps : packages) {
23349            final String packageName = ps.name;
23350            if (ps.pkg == null) {
23351                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23352                // TODO: might be due to legacy ASEC apps; we should circle back
23353                // and reconcile again once they're scanned
23354                continue;
23355            }
23356            // Skip non-core apps if requested
23357            if (onlyCoreApps && !ps.pkg.coreApp) {
23358                result.add(packageName);
23359                continue;
23360            }
23361
23362            if (ps.getInstalled(userId)) {
23363                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23364                preparedCount++;
23365            }
23366        }
23367
23368        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23369        return result;
23370    }
23371
23372    /**
23373     * Prepare app data for the given app just after it was installed or
23374     * upgraded. This method carefully only touches users that it's installed
23375     * for, and it forces a restorecon to handle any seinfo changes.
23376     * <p>
23377     * Verifies that directories exist and that ownership and labeling is
23378     * correct for all installed apps. If there is an ownership mismatch, it
23379     * will try recovering system apps by wiping data; third-party app data is
23380     * left intact.
23381     * <p>
23382     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23383     */
23384    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23385        final PackageSetting ps;
23386        synchronized (mPackages) {
23387            ps = mSettings.mPackages.get(pkg.packageName);
23388            mSettings.writeKernelMappingLPr(ps);
23389        }
23390
23391        final UserManager um = mContext.getSystemService(UserManager.class);
23392        UserManagerInternal umInternal = getUserManagerInternal();
23393        for (UserInfo user : um.getUsers()) {
23394            final int flags;
23395            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23396                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23397            } else if (umInternal.isUserRunning(user.id)) {
23398                flags = StorageManager.FLAG_STORAGE_DE;
23399            } else {
23400                continue;
23401            }
23402
23403            if (ps.getInstalled(user.id)) {
23404                // TODO: when user data is locked, mark that we're still dirty
23405                prepareAppDataLIF(pkg, user.id, flags);
23406            }
23407        }
23408    }
23409
23410    /**
23411     * Prepare app data for the given app.
23412     * <p>
23413     * Verifies that directories exist and that ownership and labeling is
23414     * correct for all installed apps. If there is an ownership mismatch, this
23415     * will try recovering system apps by wiping data; third-party app data is
23416     * left intact.
23417     */
23418    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23419        if (pkg == null) {
23420            Slog.wtf(TAG, "Package was null!", new Throwable());
23421            return;
23422        }
23423        prepareAppDataLeafLIF(pkg, userId, flags);
23424        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23425        for (int i = 0; i < childCount; i++) {
23426            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23427        }
23428    }
23429
23430    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23431            boolean maybeMigrateAppData) {
23432        prepareAppDataLIF(pkg, userId, flags);
23433
23434        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23435            // We may have just shuffled around app data directories, so
23436            // prepare them one more time
23437            prepareAppDataLIF(pkg, userId, flags);
23438        }
23439    }
23440
23441    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23442        if (DEBUG_APP_DATA) {
23443            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23444                    + Integer.toHexString(flags));
23445        }
23446
23447        final String volumeUuid = pkg.volumeUuid;
23448        final String packageName = pkg.packageName;
23449        final ApplicationInfo app = pkg.applicationInfo;
23450        final int appId = UserHandle.getAppId(app.uid);
23451
23452        Preconditions.checkNotNull(app.seInfo);
23453
23454        long ceDataInode = -1;
23455        try {
23456            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23457                    appId, app.seInfo, app.targetSdkVersion);
23458        } catch (InstallerException e) {
23459            if (app.isSystemApp()) {
23460                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23461                        + ", but trying to recover: " + e);
23462                destroyAppDataLeafLIF(pkg, userId, flags);
23463                try {
23464                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23465                            appId, app.seInfo, app.targetSdkVersion);
23466                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23467                } catch (InstallerException e2) {
23468                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23469                }
23470            } else {
23471                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23472            }
23473        }
23474
23475        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23476            // TODO: mark this structure as dirty so we persist it!
23477            synchronized (mPackages) {
23478                final PackageSetting ps = mSettings.mPackages.get(packageName);
23479                if (ps != null) {
23480                    ps.setCeDataInode(ceDataInode, userId);
23481                }
23482            }
23483        }
23484
23485        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23486    }
23487
23488    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23489        if (pkg == null) {
23490            Slog.wtf(TAG, "Package was null!", new Throwable());
23491            return;
23492        }
23493        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23494        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23495        for (int i = 0; i < childCount; i++) {
23496            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23497        }
23498    }
23499
23500    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23501        final String volumeUuid = pkg.volumeUuid;
23502        final String packageName = pkg.packageName;
23503        final ApplicationInfo app = pkg.applicationInfo;
23504
23505        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23506            // Create a native library symlink only if we have native libraries
23507            // and if the native libraries are 32 bit libraries. We do not provide
23508            // this symlink for 64 bit libraries.
23509            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23510                final String nativeLibPath = app.nativeLibraryDir;
23511                try {
23512                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23513                            nativeLibPath, userId);
23514                } catch (InstallerException e) {
23515                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23516                }
23517            }
23518        }
23519    }
23520
23521    /**
23522     * For system apps on non-FBE devices, this method migrates any existing
23523     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23524     * requested by the app.
23525     */
23526    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23527        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23528                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23529            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23530                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23531            try {
23532                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23533                        storageTarget);
23534            } catch (InstallerException e) {
23535                logCriticalInfo(Log.WARN,
23536                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23537            }
23538            return true;
23539        } else {
23540            return false;
23541        }
23542    }
23543
23544    public PackageFreezer freezePackage(String packageName, String killReason) {
23545        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23546    }
23547
23548    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23549        return new PackageFreezer(packageName, userId, killReason);
23550    }
23551
23552    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23553            String killReason) {
23554        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23555    }
23556
23557    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23558            String killReason) {
23559        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23560            return new PackageFreezer();
23561        } else {
23562            return freezePackage(packageName, userId, killReason);
23563        }
23564    }
23565
23566    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23567            String killReason) {
23568        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23569    }
23570
23571    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23572            String killReason) {
23573        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23574            return new PackageFreezer();
23575        } else {
23576            return freezePackage(packageName, userId, killReason);
23577        }
23578    }
23579
23580    /**
23581     * Class that freezes and kills the given package upon creation, and
23582     * unfreezes it upon closing. This is typically used when doing surgery on
23583     * app code/data to prevent the app from running while you're working.
23584     */
23585    private class PackageFreezer implements AutoCloseable {
23586        private final String mPackageName;
23587        private final PackageFreezer[] mChildren;
23588
23589        private final boolean mWeFroze;
23590
23591        private final AtomicBoolean mClosed = new AtomicBoolean();
23592        private final CloseGuard mCloseGuard = CloseGuard.get();
23593
23594        /**
23595         * Create and return a stub freezer that doesn't actually do anything,
23596         * typically used when someone requested
23597         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23598         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23599         */
23600        public PackageFreezer() {
23601            mPackageName = null;
23602            mChildren = null;
23603            mWeFroze = false;
23604            mCloseGuard.open("close");
23605        }
23606
23607        public PackageFreezer(String packageName, int userId, String killReason) {
23608            synchronized (mPackages) {
23609                mPackageName = packageName;
23610                mWeFroze = mFrozenPackages.add(mPackageName);
23611
23612                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23613                if (ps != null) {
23614                    killApplication(ps.name, ps.appId, userId, killReason);
23615                }
23616
23617                final PackageParser.Package p = mPackages.get(packageName);
23618                if (p != null && p.childPackages != null) {
23619                    final int N = p.childPackages.size();
23620                    mChildren = new PackageFreezer[N];
23621                    for (int i = 0; i < N; i++) {
23622                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23623                                userId, killReason);
23624                    }
23625                } else {
23626                    mChildren = null;
23627                }
23628            }
23629            mCloseGuard.open("close");
23630        }
23631
23632        @Override
23633        protected void finalize() throws Throwable {
23634            try {
23635                if (mCloseGuard != null) {
23636                    mCloseGuard.warnIfOpen();
23637                }
23638
23639                close();
23640            } finally {
23641                super.finalize();
23642            }
23643        }
23644
23645        @Override
23646        public void close() {
23647            mCloseGuard.close();
23648            if (mClosed.compareAndSet(false, true)) {
23649                synchronized (mPackages) {
23650                    if (mWeFroze) {
23651                        mFrozenPackages.remove(mPackageName);
23652                    }
23653
23654                    if (mChildren != null) {
23655                        for (PackageFreezer freezer : mChildren) {
23656                            freezer.close();
23657                        }
23658                    }
23659                }
23660            }
23661        }
23662    }
23663
23664    /**
23665     * Verify that given package is currently frozen.
23666     */
23667    private void checkPackageFrozen(String packageName) {
23668        synchronized (mPackages) {
23669            if (!mFrozenPackages.contains(packageName)) {
23670                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23671            }
23672        }
23673    }
23674
23675    @Override
23676    public int movePackage(final String packageName, final String volumeUuid) {
23677        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23678
23679        final int callingUid = Binder.getCallingUid();
23680        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23681        final int moveId = mNextMoveId.getAndIncrement();
23682        mHandler.post(new Runnable() {
23683            @Override
23684            public void run() {
23685                try {
23686                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23687                } catch (PackageManagerException e) {
23688                    Slog.w(TAG, "Failed to move " + packageName, e);
23689                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
23690                }
23691            }
23692        });
23693        return moveId;
23694    }
23695
23696    private void movePackageInternal(final String packageName, final String volumeUuid,
23697            final int moveId, final int callingUid, UserHandle user)
23698                    throws PackageManagerException {
23699        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23700        final PackageManager pm = mContext.getPackageManager();
23701
23702        final boolean currentAsec;
23703        final String currentVolumeUuid;
23704        final File codeFile;
23705        final String installerPackageName;
23706        final String packageAbiOverride;
23707        final int appId;
23708        final String seinfo;
23709        final String label;
23710        final int targetSdkVersion;
23711        final PackageFreezer freezer;
23712        final int[] installedUserIds;
23713
23714        // reader
23715        synchronized (mPackages) {
23716            final PackageParser.Package pkg = mPackages.get(packageName);
23717            final PackageSetting ps = mSettings.mPackages.get(packageName);
23718            if (pkg == null
23719                    || ps == null
23720                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23721                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23722            }
23723            if (pkg.applicationInfo.isSystemApp()) {
23724                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23725                        "Cannot move system application");
23726            }
23727
23728            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23729            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23730                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23731            if (isInternalStorage && !allow3rdPartyOnInternal) {
23732                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23733                        "3rd party apps are not allowed on internal storage");
23734            }
23735
23736            if (pkg.applicationInfo.isExternalAsec()) {
23737                currentAsec = true;
23738                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23739            } else if (pkg.applicationInfo.isForwardLocked()) {
23740                currentAsec = true;
23741                currentVolumeUuid = "forward_locked";
23742            } else {
23743                currentAsec = false;
23744                currentVolumeUuid = ps.volumeUuid;
23745
23746                final File probe = new File(pkg.codePath);
23747                final File probeOat = new File(probe, "oat");
23748                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23749                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23750                            "Move only supported for modern cluster style installs");
23751                }
23752            }
23753
23754            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23755                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23756                        "Package already moved to " + volumeUuid);
23757            }
23758            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23759                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23760                        "Device admin cannot be moved");
23761            }
23762
23763            if (mFrozenPackages.contains(packageName)) {
23764                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23765                        "Failed to move already frozen package");
23766            }
23767
23768            codeFile = new File(pkg.codePath);
23769            installerPackageName = ps.installerPackageName;
23770            packageAbiOverride = ps.cpuAbiOverrideString;
23771            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23772            seinfo = pkg.applicationInfo.seInfo;
23773            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23774            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23775            freezer = freezePackage(packageName, "movePackageInternal");
23776            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23777        }
23778
23779        final Bundle extras = new Bundle();
23780        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23781        extras.putString(Intent.EXTRA_TITLE, label);
23782        mMoveCallbacks.notifyCreated(moveId, extras);
23783
23784        int installFlags;
23785        final boolean moveCompleteApp;
23786        final File measurePath;
23787
23788        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23789            installFlags = INSTALL_INTERNAL;
23790            moveCompleteApp = !currentAsec;
23791            measurePath = Environment.getDataAppDirectory(volumeUuid);
23792        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23793            installFlags = INSTALL_EXTERNAL;
23794            moveCompleteApp = false;
23795            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23796        } else {
23797            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23798            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23799                    || !volume.isMountedWritable()) {
23800                freezer.close();
23801                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23802                        "Move location not mounted private volume");
23803            }
23804
23805            Preconditions.checkState(!currentAsec);
23806
23807            installFlags = INSTALL_INTERNAL;
23808            moveCompleteApp = true;
23809            measurePath = Environment.getDataAppDirectory(volumeUuid);
23810        }
23811
23812        // If we're moving app data around, we need all the users unlocked
23813        if (moveCompleteApp) {
23814            for (int userId : installedUserIds) {
23815                if (StorageManager.isFileEncryptedNativeOrEmulated()
23816                        && !StorageManager.isUserKeyUnlocked(userId)) {
23817                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
23818                            "User " + userId + " must be unlocked");
23819                }
23820            }
23821        }
23822
23823        final PackageStats stats = new PackageStats(null, -1);
23824        synchronized (mInstaller) {
23825            for (int userId : installedUserIds) {
23826                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23827                    freezer.close();
23828                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23829                            "Failed to measure package size");
23830                }
23831            }
23832        }
23833
23834        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23835                + stats.dataSize);
23836
23837        final long startFreeBytes = measurePath.getUsableSpace();
23838        final long sizeBytes;
23839        if (moveCompleteApp) {
23840            sizeBytes = stats.codeSize + stats.dataSize;
23841        } else {
23842            sizeBytes = stats.codeSize;
23843        }
23844
23845        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23846            freezer.close();
23847            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23848                    "Not enough free space to move");
23849        }
23850
23851        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23852
23853        final CountDownLatch installedLatch = new CountDownLatch(1);
23854        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23855            @Override
23856            public void onUserActionRequired(Intent intent) throws RemoteException {
23857                throw new IllegalStateException();
23858            }
23859
23860            @Override
23861            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23862                    Bundle extras) throws RemoteException {
23863                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23864                        + PackageManager.installStatusToString(returnCode, msg));
23865
23866                installedLatch.countDown();
23867                freezer.close();
23868
23869                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23870                switch (status) {
23871                    case PackageInstaller.STATUS_SUCCESS:
23872                        mMoveCallbacks.notifyStatusChanged(moveId,
23873                                PackageManager.MOVE_SUCCEEDED);
23874                        break;
23875                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23876                        mMoveCallbacks.notifyStatusChanged(moveId,
23877                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23878                        break;
23879                    default:
23880                        mMoveCallbacks.notifyStatusChanged(moveId,
23881                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23882                        break;
23883                }
23884            }
23885        };
23886
23887        final MoveInfo move;
23888        if (moveCompleteApp) {
23889            // Kick off a thread to report progress estimates
23890            new Thread() {
23891                @Override
23892                public void run() {
23893                    while (true) {
23894                        try {
23895                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23896                                break;
23897                            }
23898                        } catch (InterruptedException ignored) {
23899                        }
23900
23901                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23902                        final int progress = 10 + (int) MathUtils.constrain(
23903                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23904                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23905                    }
23906                }
23907            }.start();
23908
23909            final String dataAppName = codeFile.getName();
23910            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23911                    dataAppName, appId, seinfo, targetSdkVersion);
23912        } else {
23913            move = null;
23914        }
23915
23916        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23917
23918        final Message msg = mHandler.obtainMessage(INIT_COPY);
23919        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23920        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23921                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23922                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23923                PackageManager.INSTALL_REASON_UNKNOWN);
23924        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23925        msg.obj = params;
23926
23927        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23928                System.identityHashCode(msg.obj));
23929        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23930                System.identityHashCode(msg.obj));
23931
23932        mHandler.sendMessage(msg);
23933    }
23934
23935    @Override
23936    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23937        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23938
23939        final int realMoveId = mNextMoveId.getAndIncrement();
23940        final Bundle extras = new Bundle();
23941        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23942        mMoveCallbacks.notifyCreated(realMoveId, extras);
23943
23944        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23945            @Override
23946            public void onCreated(int moveId, Bundle extras) {
23947                // Ignored
23948            }
23949
23950            @Override
23951            public void onStatusChanged(int moveId, int status, long estMillis) {
23952                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23953            }
23954        };
23955
23956        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23957        storage.setPrimaryStorageUuid(volumeUuid, callback);
23958        return realMoveId;
23959    }
23960
23961    @Override
23962    public int getMoveStatus(int moveId) {
23963        mContext.enforceCallingOrSelfPermission(
23964                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23965        return mMoveCallbacks.mLastStatus.get(moveId);
23966    }
23967
23968    @Override
23969    public void registerMoveCallback(IPackageMoveObserver callback) {
23970        mContext.enforceCallingOrSelfPermission(
23971                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23972        mMoveCallbacks.register(callback);
23973    }
23974
23975    @Override
23976    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23977        mContext.enforceCallingOrSelfPermission(
23978                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23979        mMoveCallbacks.unregister(callback);
23980    }
23981
23982    @Override
23983    public boolean setInstallLocation(int loc) {
23984        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23985                null);
23986        if (getInstallLocation() == loc) {
23987            return true;
23988        }
23989        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23990                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23991            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23992                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23993            return true;
23994        }
23995        return false;
23996   }
23997
23998    @Override
23999    public int getInstallLocation() {
24000        // allow instant app access
24001        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24002                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24003                PackageHelper.APP_INSTALL_AUTO);
24004    }
24005
24006    /** Called by UserManagerService */
24007    void cleanUpUser(UserManagerService userManager, int userHandle) {
24008        synchronized (mPackages) {
24009            mDirtyUsers.remove(userHandle);
24010            mUserNeedsBadging.delete(userHandle);
24011            mSettings.removeUserLPw(userHandle);
24012            mPendingBroadcasts.remove(userHandle);
24013            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24014            removeUnusedPackagesLPw(userManager, userHandle);
24015        }
24016    }
24017
24018    /**
24019     * We're removing userHandle and would like to remove any downloaded packages
24020     * that are no longer in use by any other user.
24021     * @param userHandle the user being removed
24022     */
24023    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24024        final boolean DEBUG_CLEAN_APKS = false;
24025        int [] users = userManager.getUserIds();
24026        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24027        while (psit.hasNext()) {
24028            PackageSetting ps = psit.next();
24029            if (ps.pkg == null) {
24030                continue;
24031            }
24032            final String packageName = ps.pkg.packageName;
24033            // Skip over if system app
24034            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24035                continue;
24036            }
24037            if (DEBUG_CLEAN_APKS) {
24038                Slog.i(TAG, "Checking package " + packageName);
24039            }
24040            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24041            if (keep) {
24042                if (DEBUG_CLEAN_APKS) {
24043                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24044                }
24045            } else {
24046                for (int i = 0; i < users.length; i++) {
24047                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24048                        keep = true;
24049                        if (DEBUG_CLEAN_APKS) {
24050                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24051                                    + users[i]);
24052                        }
24053                        break;
24054                    }
24055                }
24056            }
24057            if (!keep) {
24058                if (DEBUG_CLEAN_APKS) {
24059                    Slog.i(TAG, "  Removing package " + packageName);
24060                }
24061                mHandler.post(new Runnable() {
24062                    public void run() {
24063                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24064                                userHandle, 0);
24065                    } //end run
24066                });
24067            }
24068        }
24069    }
24070
24071    /** Called by UserManagerService */
24072    void createNewUser(int userId, String[] disallowedPackages) {
24073        synchronized (mInstallLock) {
24074            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24075        }
24076        synchronized (mPackages) {
24077            scheduleWritePackageRestrictionsLocked(userId);
24078            scheduleWritePackageListLocked(userId);
24079            applyFactoryDefaultBrowserLPw(userId);
24080            primeDomainVerificationsLPw(userId);
24081        }
24082    }
24083
24084    void onNewUserCreated(final int userId) {
24085        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24086        // If permission review for legacy apps is required, we represent
24087        // dagerous permissions for such apps as always granted runtime
24088        // permissions to keep per user flag state whether review is needed.
24089        // Hence, if a new user is added we have to propagate dangerous
24090        // permission grants for these legacy apps.
24091        if (mPermissionReviewRequired) {
24092            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24093                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24094        }
24095    }
24096
24097    @Override
24098    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24099        mContext.enforceCallingOrSelfPermission(
24100                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24101                "Only package verification agents can read the verifier device identity");
24102
24103        synchronized (mPackages) {
24104            return mSettings.getVerifierDeviceIdentityLPw();
24105        }
24106    }
24107
24108    @Override
24109    public void setPermissionEnforced(String permission, boolean enforced) {
24110        // TODO: Now that we no longer change GID for storage, this should to away.
24111        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24112                "setPermissionEnforced");
24113        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24114            synchronized (mPackages) {
24115                if (mSettings.mReadExternalStorageEnforced == null
24116                        || mSettings.mReadExternalStorageEnforced != enforced) {
24117                    mSettings.mReadExternalStorageEnforced = enforced;
24118                    mSettings.writeLPr();
24119                }
24120            }
24121            // kill any non-foreground processes so we restart them and
24122            // grant/revoke the GID.
24123            final IActivityManager am = ActivityManager.getService();
24124            if (am != null) {
24125                final long token = Binder.clearCallingIdentity();
24126                try {
24127                    am.killProcessesBelowForeground("setPermissionEnforcement");
24128                } catch (RemoteException e) {
24129                } finally {
24130                    Binder.restoreCallingIdentity(token);
24131                }
24132            }
24133        } else {
24134            throw new IllegalArgumentException("No selective enforcement for " + permission);
24135        }
24136    }
24137
24138    @Override
24139    @Deprecated
24140    public boolean isPermissionEnforced(String permission) {
24141        // allow instant applications
24142        return true;
24143    }
24144
24145    @Override
24146    public boolean isStorageLow() {
24147        // allow instant applications
24148        final long token = Binder.clearCallingIdentity();
24149        try {
24150            final DeviceStorageMonitorInternal
24151                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24152            if (dsm != null) {
24153                return dsm.isMemoryLow();
24154            } else {
24155                return false;
24156            }
24157        } finally {
24158            Binder.restoreCallingIdentity(token);
24159        }
24160    }
24161
24162    @Override
24163    public IPackageInstaller getPackageInstaller() {
24164        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24165            return null;
24166        }
24167        return mInstallerService;
24168    }
24169
24170    private boolean userNeedsBadging(int userId) {
24171        int index = mUserNeedsBadging.indexOfKey(userId);
24172        if (index < 0) {
24173            final UserInfo userInfo;
24174            final long token = Binder.clearCallingIdentity();
24175            try {
24176                userInfo = sUserManager.getUserInfo(userId);
24177            } finally {
24178                Binder.restoreCallingIdentity(token);
24179            }
24180            final boolean b;
24181            if (userInfo != null && userInfo.isManagedProfile()) {
24182                b = true;
24183            } else {
24184                b = false;
24185            }
24186            mUserNeedsBadging.put(userId, b);
24187            return b;
24188        }
24189        return mUserNeedsBadging.valueAt(index);
24190    }
24191
24192    @Override
24193    public KeySet getKeySetByAlias(String packageName, String alias) {
24194        if (packageName == null || alias == null) {
24195            return null;
24196        }
24197        synchronized(mPackages) {
24198            final PackageParser.Package pkg = mPackages.get(packageName);
24199            if (pkg == null) {
24200                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24201                throw new IllegalArgumentException("Unknown package: " + packageName);
24202            }
24203            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24204            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24205                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24206                throw new IllegalArgumentException("Unknown package: " + packageName);
24207            }
24208            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24209            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24210        }
24211    }
24212
24213    @Override
24214    public KeySet getSigningKeySet(String packageName) {
24215        if (packageName == null) {
24216            return null;
24217        }
24218        synchronized(mPackages) {
24219            final int callingUid = Binder.getCallingUid();
24220            final int callingUserId = UserHandle.getUserId(callingUid);
24221            final PackageParser.Package pkg = mPackages.get(packageName);
24222            if (pkg == null) {
24223                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24224                throw new IllegalArgumentException("Unknown package: " + packageName);
24225            }
24226            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24227            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24228                // filter and pretend the package doesn't exist
24229                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24230                        + ", uid:" + callingUid);
24231                throw new IllegalArgumentException("Unknown package: " + packageName);
24232            }
24233            if (pkg.applicationInfo.uid != callingUid
24234                    && Process.SYSTEM_UID != callingUid) {
24235                throw new SecurityException("May not access signing KeySet of other apps.");
24236            }
24237            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24238            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24239        }
24240    }
24241
24242    @Override
24243    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24244        final int callingUid = Binder.getCallingUid();
24245        if (getInstantAppPackageName(callingUid) != null) {
24246            return false;
24247        }
24248        if (packageName == null || ks == null) {
24249            return false;
24250        }
24251        synchronized(mPackages) {
24252            final PackageParser.Package pkg = mPackages.get(packageName);
24253            if (pkg == null
24254                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24255                            UserHandle.getUserId(callingUid))) {
24256                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24257                throw new IllegalArgumentException("Unknown package: " + packageName);
24258            }
24259            IBinder ksh = ks.getToken();
24260            if (ksh instanceof KeySetHandle) {
24261                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24262                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24263            }
24264            return false;
24265        }
24266    }
24267
24268    @Override
24269    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24270        final int callingUid = Binder.getCallingUid();
24271        if (getInstantAppPackageName(callingUid) != null) {
24272            return false;
24273        }
24274        if (packageName == null || ks == null) {
24275            return false;
24276        }
24277        synchronized(mPackages) {
24278            final PackageParser.Package pkg = mPackages.get(packageName);
24279            if (pkg == null
24280                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24281                            UserHandle.getUserId(callingUid))) {
24282                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24283                throw new IllegalArgumentException("Unknown package: " + packageName);
24284            }
24285            IBinder ksh = ks.getToken();
24286            if (ksh instanceof KeySetHandle) {
24287                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24288                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24289            }
24290            return false;
24291        }
24292    }
24293
24294    private void deletePackageIfUnusedLPr(final String packageName) {
24295        PackageSetting ps = mSettings.mPackages.get(packageName);
24296        if (ps == null) {
24297            return;
24298        }
24299        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24300            // TODO Implement atomic delete if package is unused
24301            // It is currently possible that the package will be deleted even if it is installed
24302            // after this method returns.
24303            mHandler.post(new Runnable() {
24304                public void run() {
24305                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24306                            0, PackageManager.DELETE_ALL_USERS);
24307                }
24308            });
24309        }
24310    }
24311
24312    /**
24313     * Check and throw if the given before/after packages would be considered a
24314     * downgrade.
24315     */
24316    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24317            throws PackageManagerException {
24318        if (after.versionCode < before.mVersionCode) {
24319            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24320                    "Update version code " + after.versionCode + " is older than current "
24321                    + before.mVersionCode);
24322        } else if (after.versionCode == before.mVersionCode) {
24323            if (after.baseRevisionCode < before.baseRevisionCode) {
24324                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24325                        "Update base revision code " + after.baseRevisionCode
24326                        + " is older than current " + before.baseRevisionCode);
24327            }
24328
24329            if (!ArrayUtils.isEmpty(after.splitNames)) {
24330                for (int i = 0; i < after.splitNames.length; i++) {
24331                    final String splitName = after.splitNames[i];
24332                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24333                    if (j != -1) {
24334                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24335                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24336                                    "Update split " + splitName + " revision code "
24337                                    + after.splitRevisionCodes[i] + " is older than current "
24338                                    + before.splitRevisionCodes[j]);
24339                        }
24340                    }
24341                }
24342            }
24343        }
24344    }
24345
24346    private static class MoveCallbacks extends Handler {
24347        private static final int MSG_CREATED = 1;
24348        private static final int MSG_STATUS_CHANGED = 2;
24349
24350        private final RemoteCallbackList<IPackageMoveObserver>
24351                mCallbacks = new RemoteCallbackList<>();
24352
24353        private final SparseIntArray mLastStatus = new SparseIntArray();
24354
24355        public MoveCallbacks(Looper looper) {
24356            super(looper);
24357        }
24358
24359        public void register(IPackageMoveObserver callback) {
24360            mCallbacks.register(callback);
24361        }
24362
24363        public void unregister(IPackageMoveObserver callback) {
24364            mCallbacks.unregister(callback);
24365        }
24366
24367        @Override
24368        public void handleMessage(Message msg) {
24369            final SomeArgs args = (SomeArgs) msg.obj;
24370            final int n = mCallbacks.beginBroadcast();
24371            for (int i = 0; i < n; i++) {
24372                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24373                try {
24374                    invokeCallback(callback, msg.what, args);
24375                } catch (RemoteException ignored) {
24376                }
24377            }
24378            mCallbacks.finishBroadcast();
24379            args.recycle();
24380        }
24381
24382        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24383                throws RemoteException {
24384            switch (what) {
24385                case MSG_CREATED: {
24386                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24387                    break;
24388                }
24389                case MSG_STATUS_CHANGED: {
24390                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24391                    break;
24392                }
24393            }
24394        }
24395
24396        private void notifyCreated(int moveId, Bundle extras) {
24397            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24398
24399            final SomeArgs args = SomeArgs.obtain();
24400            args.argi1 = moveId;
24401            args.arg2 = extras;
24402            obtainMessage(MSG_CREATED, args).sendToTarget();
24403        }
24404
24405        private void notifyStatusChanged(int moveId, int status) {
24406            notifyStatusChanged(moveId, status, -1);
24407        }
24408
24409        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24410            Slog.v(TAG, "Move " + moveId + " status " + status);
24411
24412            final SomeArgs args = SomeArgs.obtain();
24413            args.argi1 = moveId;
24414            args.argi2 = status;
24415            args.arg3 = estMillis;
24416            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24417
24418            synchronized (mLastStatus) {
24419                mLastStatus.put(moveId, status);
24420            }
24421        }
24422    }
24423
24424    private final static class OnPermissionChangeListeners extends Handler {
24425        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24426
24427        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24428                new RemoteCallbackList<>();
24429
24430        public OnPermissionChangeListeners(Looper looper) {
24431            super(looper);
24432        }
24433
24434        @Override
24435        public void handleMessage(Message msg) {
24436            switch (msg.what) {
24437                case MSG_ON_PERMISSIONS_CHANGED: {
24438                    final int uid = msg.arg1;
24439                    handleOnPermissionsChanged(uid);
24440                } break;
24441            }
24442        }
24443
24444        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24445            mPermissionListeners.register(listener);
24446
24447        }
24448
24449        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24450            mPermissionListeners.unregister(listener);
24451        }
24452
24453        public void onPermissionsChanged(int uid) {
24454            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24455                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24456            }
24457        }
24458
24459        private void handleOnPermissionsChanged(int uid) {
24460            final int count = mPermissionListeners.beginBroadcast();
24461            try {
24462                for (int i = 0; i < count; i++) {
24463                    IOnPermissionsChangeListener callback = mPermissionListeners
24464                            .getBroadcastItem(i);
24465                    try {
24466                        callback.onPermissionsChanged(uid);
24467                    } catch (RemoteException e) {
24468                        Log.e(TAG, "Permission listener is dead", e);
24469                    }
24470                }
24471            } finally {
24472                mPermissionListeners.finishBroadcast();
24473            }
24474        }
24475    }
24476
24477    private class PackageManagerInternalImpl extends PackageManagerInternal {
24478        @Override
24479        public void setLocationPackagesProvider(PackagesProvider provider) {
24480            synchronized (mPackages) {
24481                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24482            }
24483        }
24484
24485        @Override
24486        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24487            synchronized (mPackages) {
24488                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24489            }
24490        }
24491
24492        @Override
24493        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24494            synchronized (mPackages) {
24495                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24496            }
24497        }
24498
24499        @Override
24500        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24501            synchronized (mPackages) {
24502                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24503            }
24504        }
24505
24506        @Override
24507        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24508            synchronized (mPackages) {
24509                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24510            }
24511        }
24512
24513        @Override
24514        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24515            synchronized (mPackages) {
24516                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24517            }
24518        }
24519
24520        @Override
24521        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24522            synchronized (mPackages) {
24523                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24524                        packageName, userId);
24525            }
24526        }
24527
24528        @Override
24529        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24530            synchronized (mPackages) {
24531                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24532                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24533                        packageName, userId);
24534            }
24535        }
24536
24537        @Override
24538        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24539            synchronized (mPackages) {
24540                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24541                        packageName, userId);
24542            }
24543        }
24544
24545        @Override
24546        public void setKeepUninstalledPackages(final List<String> packageList) {
24547            Preconditions.checkNotNull(packageList);
24548            List<String> removedFromList = null;
24549            synchronized (mPackages) {
24550                if (mKeepUninstalledPackages != null) {
24551                    final int packagesCount = mKeepUninstalledPackages.size();
24552                    for (int i = 0; i < packagesCount; i++) {
24553                        String oldPackage = mKeepUninstalledPackages.get(i);
24554                        if (packageList != null && packageList.contains(oldPackage)) {
24555                            continue;
24556                        }
24557                        if (removedFromList == null) {
24558                            removedFromList = new ArrayList<>();
24559                        }
24560                        removedFromList.add(oldPackage);
24561                    }
24562                }
24563                mKeepUninstalledPackages = new ArrayList<>(packageList);
24564                if (removedFromList != null) {
24565                    final int removedCount = removedFromList.size();
24566                    for (int i = 0; i < removedCount; i++) {
24567                        deletePackageIfUnusedLPr(removedFromList.get(i));
24568                    }
24569                }
24570            }
24571        }
24572
24573        @Override
24574        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24575            synchronized (mPackages) {
24576                // If we do not support permission review, done.
24577                if (!mPermissionReviewRequired) {
24578                    return false;
24579                }
24580
24581                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24582                if (packageSetting == null) {
24583                    return false;
24584                }
24585
24586                // Permission review applies only to apps not supporting the new permission model.
24587                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24588                    return false;
24589                }
24590
24591                // Legacy apps have the permission and get user consent on launch.
24592                PermissionsState permissionsState = packageSetting.getPermissionsState();
24593                return permissionsState.isPermissionReviewRequired(userId);
24594            }
24595        }
24596
24597        @Override
24598        public PackageInfo getPackageInfo(
24599                String packageName, int flags, int filterCallingUid, int userId) {
24600            return PackageManagerService.this
24601                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24602                            flags, filterCallingUid, userId);
24603        }
24604
24605        @Override
24606        public ApplicationInfo getApplicationInfo(
24607                String packageName, int flags, int filterCallingUid, int userId) {
24608            return PackageManagerService.this
24609                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24610        }
24611
24612        @Override
24613        public ActivityInfo getActivityInfo(
24614                ComponentName component, int flags, int filterCallingUid, int userId) {
24615            return PackageManagerService.this
24616                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24617        }
24618
24619        @Override
24620        public List<ResolveInfo> queryIntentActivities(
24621                Intent intent, int flags, int filterCallingUid, int userId) {
24622            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24623            return PackageManagerService.this
24624                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24625                            userId, false /*resolveForStart*/);
24626        }
24627
24628        @Override
24629        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24630                int userId) {
24631            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24632        }
24633
24634        @Override
24635        public void setDeviceAndProfileOwnerPackages(
24636                int deviceOwnerUserId, String deviceOwnerPackage,
24637                SparseArray<String> profileOwnerPackages) {
24638            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24639                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24640        }
24641
24642        @Override
24643        public boolean isPackageDataProtected(int userId, String packageName) {
24644            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24645        }
24646
24647        @Override
24648        public boolean isPackageEphemeral(int userId, String packageName) {
24649            synchronized (mPackages) {
24650                final PackageSetting ps = mSettings.mPackages.get(packageName);
24651                return ps != null ? ps.getInstantApp(userId) : false;
24652            }
24653        }
24654
24655        @Override
24656        public boolean wasPackageEverLaunched(String packageName, int userId) {
24657            synchronized (mPackages) {
24658                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24659            }
24660        }
24661
24662        @Override
24663        public void grantRuntimePermission(String packageName, String name, int userId,
24664                boolean overridePolicy) {
24665            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24666                    overridePolicy);
24667        }
24668
24669        @Override
24670        public void revokeRuntimePermission(String packageName, String name, int userId,
24671                boolean overridePolicy) {
24672            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24673                    overridePolicy);
24674        }
24675
24676        @Override
24677        public String getNameForUid(int uid) {
24678            return PackageManagerService.this.getNameForUid(uid);
24679        }
24680
24681        @Override
24682        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24683                Intent origIntent, String resolvedType, String callingPackage,
24684                Bundle verificationBundle, int userId) {
24685            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24686                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24687                    userId);
24688        }
24689
24690        @Override
24691        public void grantEphemeralAccess(int userId, Intent intent,
24692                int targetAppId, int ephemeralAppId) {
24693            synchronized (mPackages) {
24694                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24695                        targetAppId, ephemeralAppId);
24696            }
24697        }
24698
24699        @Override
24700        public boolean isInstantAppInstallerComponent(ComponentName component) {
24701            synchronized (mPackages) {
24702                return mInstantAppInstallerActivity != null
24703                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24704            }
24705        }
24706
24707        @Override
24708        public void pruneInstantApps() {
24709            mInstantAppRegistry.pruneInstantApps();
24710        }
24711
24712        @Override
24713        public String getSetupWizardPackageName() {
24714            return mSetupWizardPackage;
24715        }
24716
24717        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24718            if (policy != null) {
24719                mExternalSourcesPolicy = policy;
24720            }
24721        }
24722
24723        @Override
24724        public boolean isPackagePersistent(String packageName) {
24725            synchronized (mPackages) {
24726                PackageParser.Package pkg = mPackages.get(packageName);
24727                return pkg != null
24728                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24729                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24730                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24731                        : false;
24732            }
24733        }
24734
24735        @Override
24736        public List<PackageInfo> getOverlayPackages(int userId) {
24737            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24738            synchronized (mPackages) {
24739                for (PackageParser.Package p : mPackages.values()) {
24740                    if (p.mOverlayTarget != null) {
24741                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24742                        if (pkg != null) {
24743                            overlayPackages.add(pkg);
24744                        }
24745                    }
24746                }
24747            }
24748            return overlayPackages;
24749        }
24750
24751        @Override
24752        public List<String> getTargetPackageNames(int userId) {
24753            List<String> targetPackages = new ArrayList<>();
24754            synchronized (mPackages) {
24755                for (PackageParser.Package p : mPackages.values()) {
24756                    if (p.mOverlayTarget == null) {
24757                        targetPackages.add(p.packageName);
24758                    }
24759                }
24760            }
24761            return targetPackages;
24762        }
24763
24764        @Override
24765        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24766                @Nullable List<String> overlayPackageNames) {
24767            synchronized (mPackages) {
24768                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24769                    Slog.e(TAG, "failed to find package " + targetPackageName);
24770                    return false;
24771                }
24772                ArrayList<String> overlayPaths = null;
24773                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24774                    final int N = overlayPackageNames.size();
24775                    overlayPaths = new ArrayList<>(N);
24776                    for (int i = 0; i < N; i++) {
24777                        final String packageName = overlayPackageNames.get(i);
24778                        final PackageParser.Package pkg = mPackages.get(packageName);
24779                        if (pkg == null) {
24780                            Slog.e(TAG, "failed to find package " + packageName);
24781                            return false;
24782                        }
24783                        overlayPaths.add(pkg.baseCodePath);
24784                    }
24785                }
24786
24787                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24788                ps.setOverlayPaths(overlayPaths, userId);
24789                return true;
24790            }
24791        }
24792
24793        @Override
24794        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24795                int flags, int userId) {
24796            return resolveIntentInternal(
24797                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24798        }
24799
24800        @Override
24801        public ResolveInfo resolveService(Intent intent, String resolvedType,
24802                int flags, int userId, int callingUid) {
24803            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24804        }
24805
24806        @Override
24807        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24808            synchronized (mPackages) {
24809                mIsolatedOwners.put(isolatedUid, ownerUid);
24810            }
24811        }
24812
24813        @Override
24814        public void removeIsolatedUid(int isolatedUid) {
24815            synchronized (mPackages) {
24816                mIsolatedOwners.delete(isolatedUid);
24817            }
24818        }
24819
24820        @Override
24821        public int getUidTargetSdkVersion(int uid) {
24822            synchronized (mPackages) {
24823                return getUidTargetSdkVersionLockedLPr(uid);
24824            }
24825        }
24826
24827        @Override
24828        public boolean canAccessInstantApps(int callingUid, int userId) {
24829            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24830        }
24831    }
24832
24833    @Override
24834    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24835        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24836        synchronized (mPackages) {
24837            final long identity = Binder.clearCallingIdentity();
24838            try {
24839                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24840                        packageNames, userId);
24841            } finally {
24842                Binder.restoreCallingIdentity(identity);
24843            }
24844        }
24845    }
24846
24847    @Override
24848    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24849        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24850        synchronized (mPackages) {
24851            final long identity = Binder.clearCallingIdentity();
24852            try {
24853                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24854                        packageNames, userId);
24855            } finally {
24856                Binder.restoreCallingIdentity(identity);
24857            }
24858        }
24859    }
24860
24861    private static void enforceSystemOrPhoneCaller(String tag) {
24862        int callingUid = Binder.getCallingUid();
24863        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24864            throw new SecurityException(
24865                    "Cannot call " + tag + " from UID " + callingUid);
24866        }
24867    }
24868
24869    boolean isHistoricalPackageUsageAvailable() {
24870        return mPackageUsage.isHistoricalPackageUsageAvailable();
24871    }
24872
24873    /**
24874     * Return a <b>copy</b> of the collection of packages known to the package manager.
24875     * @return A copy of the values of mPackages.
24876     */
24877    Collection<PackageParser.Package> getPackages() {
24878        synchronized (mPackages) {
24879            return new ArrayList<>(mPackages.values());
24880        }
24881    }
24882
24883    /**
24884     * Logs process start information (including base APK hash) to the security log.
24885     * @hide
24886     */
24887    @Override
24888    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24889            String apkFile, int pid) {
24890        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24891            return;
24892        }
24893        if (!SecurityLog.isLoggingEnabled()) {
24894            return;
24895        }
24896        Bundle data = new Bundle();
24897        data.putLong("startTimestamp", System.currentTimeMillis());
24898        data.putString("processName", processName);
24899        data.putInt("uid", uid);
24900        data.putString("seinfo", seinfo);
24901        data.putString("apkFile", apkFile);
24902        data.putInt("pid", pid);
24903        Message msg = mProcessLoggingHandler.obtainMessage(
24904                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24905        msg.setData(data);
24906        mProcessLoggingHandler.sendMessage(msg);
24907    }
24908
24909    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24910        return mCompilerStats.getPackageStats(pkgName);
24911    }
24912
24913    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24914        return getOrCreateCompilerPackageStats(pkg.packageName);
24915    }
24916
24917    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24918        return mCompilerStats.getOrCreatePackageStats(pkgName);
24919    }
24920
24921    public void deleteCompilerPackageStats(String pkgName) {
24922        mCompilerStats.deletePackageStats(pkgName);
24923    }
24924
24925    @Override
24926    public int getInstallReason(String packageName, int userId) {
24927        final int callingUid = Binder.getCallingUid();
24928        enforceCrossUserPermission(callingUid, userId,
24929                true /* requireFullPermission */, false /* checkShell */,
24930                "get install reason");
24931        synchronized (mPackages) {
24932            final PackageSetting ps = mSettings.mPackages.get(packageName);
24933            if (filterAppAccessLPr(ps, callingUid, userId)) {
24934                return PackageManager.INSTALL_REASON_UNKNOWN;
24935            }
24936            if (ps != null) {
24937                return ps.getInstallReason(userId);
24938            }
24939        }
24940        return PackageManager.INSTALL_REASON_UNKNOWN;
24941    }
24942
24943    @Override
24944    public boolean canRequestPackageInstalls(String packageName, int userId) {
24945        return canRequestPackageInstallsInternal(packageName, 0, userId,
24946                true /* throwIfPermNotDeclared*/);
24947    }
24948
24949    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24950            boolean throwIfPermNotDeclared) {
24951        int callingUid = Binder.getCallingUid();
24952        int uid = getPackageUid(packageName, 0, userId);
24953        if (callingUid != uid && callingUid != Process.ROOT_UID
24954                && callingUid != Process.SYSTEM_UID) {
24955            throw new SecurityException(
24956                    "Caller uid " + callingUid + " does not own package " + packageName);
24957        }
24958        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24959        if (info == null) {
24960            return false;
24961        }
24962        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24963            return false;
24964        }
24965        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24966        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24967        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24968            if (throwIfPermNotDeclared) {
24969                throw new SecurityException("Need to declare " + appOpPermission
24970                        + " to call this api");
24971            } else {
24972                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24973                return false;
24974            }
24975        }
24976        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24977            return false;
24978        }
24979        if (mExternalSourcesPolicy != null) {
24980            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24981            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24982                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24983            }
24984        }
24985        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24986    }
24987
24988    @Override
24989    public ComponentName getInstantAppResolverSettingsComponent() {
24990        return mInstantAppResolverSettingsComponent;
24991    }
24992
24993    @Override
24994    public ComponentName getInstantAppInstallerComponent() {
24995        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24996            return null;
24997        }
24998        return mInstantAppInstallerActivity == null
24999                ? null : mInstantAppInstallerActivity.getComponentName();
25000    }
25001
25002    @Override
25003    public String getInstantAppAndroidId(String packageName, int userId) {
25004        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25005                "getInstantAppAndroidId");
25006        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25007                true /* requireFullPermission */, false /* checkShell */,
25008                "getInstantAppAndroidId");
25009        // Make sure the target is an Instant App.
25010        if (!isInstantApp(packageName, userId)) {
25011            return null;
25012        }
25013        synchronized (mPackages) {
25014            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25015        }
25016    }
25017
25018    boolean canHaveOatDir(String packageName) {
25019        synchronized (mPackages) {
25020            PackageParser.Package p = mPackages.get(packageName);
25021            if (p == null) {
25022                return false;
25023            }
25024            return p.canHaveOatDir();
25025        }
25026    }
25027
25028    private String getOatDir(PackageParser.Package pkg) {
25029        if (!pkg.canHaveOatDir()) {
25030            return null;
25031        }
25032        File codePath = new File(pkg.codePath);
25033        if (codePath.isDirectory()) {
25034            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25035        }
25036        return null;
25037    }
25038
25039    void deleteOatArtifactsOfPackage(String packageName) {
25040        final String[] instructionSets;
25041        final List<String> codePaths;
25042        final String oatDir;
25043        final PackageParser.Package pkg;
25044        synchronized (mPackages) {
25045            pkg = mPackages.get(packageName);
25046        }
25047        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25048        codePaths = pkg.getAllCodePaths();
25049        oatDir = getOatDir(pkg);
25050
25051        for (String codePath : codePaths) {
25052            for (String isa : instructionSets) {
25053                try {
25054                    mInstaller.deleteOdex(codePath, isa, oatDir);
25055                } catch (InstallerException e) {
25056                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25057                }
25058            }
25059        }
25060    }
25061
25062    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25063        Set<String> unusedPackages = new HashSet<>();
25064        long currentTimeInMillis = System.currentTimeMillis();
25065        synchronized (mPackages) {
25066            for (PackageParser.Package pkg : mPackages.values()) {
25067                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25068                if (ps == null) {
25069                    continue;
25070                }
25071                PackageDexUsage.PackageUseInfo packageUseInfo = getDexManager().getPackageUseInfo(
25072                        pkg.packageName);
25073                if (PackageManagerServiceUtils
25074                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25075                                downgradeTimeThresholdMillis, packageUseInfo,
25076                                pkg.getLatestPackageUseTimeInMills(),
25077                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25078                    unusedPackages.add(pkg.packageName);
25079                }
25080            }
25081        }
25082        return unusedPackages;
25083    }
25084}
25085
25086interface PackageSender {
25087    void sendPackageBroadcast(final String action, final String pkg,
25088        final Bundle extras, final int flags, final String targetPkg,
25089        final IIntentReceiver finishedReceiver, final int[] userIds);
25090    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
25091        int appId, int... userIds);
25092}
25093